mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-29 17:55:45 +01:00
Media, formats and engine crates: follow-ups from the framework migration
This commit is contained in:
1 parent
8735a8b1c5
commit
25597ecfc7
491 files changed
+18320
-50211
No files matched your search
@@ -1,4 +1,5 @@
|
||||
[package]
|
||||
autotests = false
|
||||
name = "craft-ai-core"
|
||||
description = "Shared data model for AI connections, roles, requests and jobs across the Craft apps"
|
||||
version.workspace = true
|
||||
|
||||
@@ -36,11 +36,13 @@ impl CapabilityId {
|
||||
Ok(Self(s.to_owned()))
|
||||
}
|
||||
|
||||
/// Builds an id from a modality and a task token. Fails when `task` is not a valid token.
|
||||
pub fn new(modality: &Modality, task: &str) -> Result<Self, IdError> {
|
||||
validate_token(task)?;
|
||||
Ok(Self(format!("{}.{}", modality.as_str(), task)))
|
||||
}
|
||||
|
||||
/// The full `modality.task` text.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
@@ -51,6 +53,7 @@ impl CapabilityId {
|
||||
Modality::parse(head).unwrap_or_else(|_| Modality::Other(head.to_owned()))
|
||||
}
|
||||
|
||||
/// The task half, for example `inpaint` in `image.inpaint`.
|
||||
pub fn task(&self) -> &str {
|
||||
self.0.split_once('.').map_or("", |(_, t)| t)
|
||||
}
|
||||
@@ -117,50 +120,3 @@ pub const WELL_KNOWN: &[&str] = &[
|
||||
pub fn well_known() -> Vec<CapabilityId> {
|
||||
WELL_KNOWN.iter().filter_map(|s| CapabilityId::parse(s).ok()).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn well_known_all_parse() {
|
||||
assert_eq!(well_known().len(), WELL_KNOWN.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn splits_modality_and_task() {
|
||||
let c = CapabilityId::parse("image.inpaint").unwrap();
|
||||
assert_eq!(c.modality(), Modality::Image);
|
||||
assert_eq!(c.task(), "inpaint");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_set_accepts_new_modalities() {
|
||||
let c = CapabilityId::parse("cad.explain").unwrap();
|
||||
assert_eq!(c.modality(), Modality::Other("cad".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed() {
|
||||
for bad in ["", "image", "image.", ".inpaint", "image.in.paint", "im age.x", "image.in/paint"] {
|
||||
assert!(CapabilityId::parse(bad).is_err(), "{bad:?} should be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn modality_round_trips_known_and_unknown() {
|
||||
for text in ["image", "audio", "hologram"] {
|
||||
let m = Modality::parse(text).unwrap();
|
||||
assert_eq!(m.as_str(), text);
|
||||
let back: Modality = serde_json::from_str(&serde_json::to_string(&m).unwrap()).unwrap();
|
||||
assert_eq!(m, back);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_builds_from_parts() {
|
||||
let c = CapabilityId::new(&Modality::Audio, "transcribe").unwrap();
|
||||
assert_eq!(c.as_str(), "audio.transcribe");
|
||||
assert!(CapabilityId::new(&Modality::Audio, "a.b").is_err());
|
||||
}
|
||||
}
|
||||
@@ -16,7 +16,9 @@ pub const MAX_POLLS: u32 = 1000;
|
||||
/// What a completed run produced.
|
||||
#[derive(Debug)]
|
||||
pub struct Completed {
|
||||
/// The terminal state the job reached.
|
||||
pub state: JobState,
|
||||
/// Every event the polls reported, in order.
|
||||
pub events: Vec<Event>,
|
||||
}
|
||||
|
||||
|
||||
@@ -21,6 +21,7 @@ use crate::model::ModelInfo;
|
||||
pub enum Locality {
|
||||
/// Loopback server or in-process model: nothing leaves the machine.
|
||||
Local,
|
||||
/// The model runs on another machine. Consent applies.
|
||||
Remote,
|
||||
}
|
||||
|
||||
@@ -30,17 +31,22 @@ pub enum Locality {
|
||||
pub enum Auth {
|
||||
/// No credentials (a local model, an open local server).
|
||||
None,
|
||||
/// Authenticates with a stored key, sent in a header (see `Connection::key_header`).
|
||||
ApiKey {
|
||||
/// Locator of the key.
|
||||
secret: SecretRef,
|
||||
},
|
||||
/// An official subscription route (for example the Codex app-server). `route` names it.
|
||||
Subscription {
|
||||
/// Name of the subscription route.
|
||||
route: String,
|
||||
/// Locator of the credential for the route.
|
||||
secret: SecretRef,
|
||||
},
|
||||
}
|
||||
|
||||
impl Auth {
|
||||
/// The secret locator this authentication uses, or `None` when it needs no credentials.
|
||||
pub fn secret_ref(&self) -> Option<&SecretRef> {
|
||||
match self {
|
||||
Self::None => None,
|
||||
@@ -53,28 +59,38 @@ impl Auth {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum Billing {
|
||||
/// No charge.
|
||||
Free,
|
||||
/// Pay per use, billed separately.
|
||||
Metered,
|
||||
/// Covered by an existing subscription's allowance.
|
||||
SubscriptionAllowance,
|
||||
/// The cost is not known.
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// A saved connection.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Connection {
|
||||
#[allow(missing_docs)]
|
||||
pub id: ConnectionId,
|
||||
/// Name shown to the user.
|
||||
pub label: String,
|
||||
/// Which adapter talks to it, such as `http`, `openai`, `fal`, `comfyui`, `onnx`.
|
||||
pub provider: String,
|
||||
/// Server address, such as `https://host:port`. `None` for an in-process or route-only connection.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub endpoint: Option<String>,
|
||||
/// Whether data stays on this machine. `validate` checks it against `endpoint`.
|
||||
pub locality: Locality,
|
||||
/// How the connection authenticates.
|
||||
pub auth: Auth,
|
||||
/// Who pays for use.
|
||||
pub billing: Billing,
|
||||
/// Models this connection offers. Ids must be unique.
|
||||
#[serde(default)]
|
||||
pub models: Vec<ModelInfo>,
|
||||
/// When false, the connection is kept but not offered for use. Defaults to true.
|
||||
#[serde(default = "yes")]
|
||||
pub enabled: bool,
|
||||
/// Header that carries the key, for a server that does not use `Authorization: Bearer`.
|
||||
@@ -138,7 +154,9 @@ pub fn check_key_header(name: &str) -> Result<(), &'static str> {
|
||||
/// Why a connection was refused.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ConnectionError {
|
||||
/// The provider name is not a valid id.
|
||||
Provider(IdError),
|
||||
/// The endpoint cannot be parsed.
|
||||
Endpoint(IdError),
|
||||
/// Labelled `Local` but the endpoint is not loopback.
|
||||
LocalButNotLoopback,
|
||||
@@ -146,7 +164,9 @@ pub enum ConnectionError {
|
||||
RemoteButLoopback,
|
||||
/// No endpoint, labelled `Local`, yet it uses credentials. Such a route sends data away.
|
||||
LocalWithoutEndpointNeedsNoAuth,
|
||||
/// The label is empty or only whitespace.
|
||||
EmptyLabel,
|
||||
/// Two models share this id.
|
||||
DuplicateModel(String),
|
||||
/// A key header name that is not allowed, or a header named for a connection with no key.
|
||||
KeyHeader(&'static str),
|
||||
@@ -211,6 +231,7 @@ impl Connection {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The model with this id, if the connection lists it.
|
||||
pub fn model(&self, id: &crate::ids::ModelId) -> Option<&ModelInfo> {
|
||||
self.models.iter().find(|m| &m.id == id)
|
||||
}
|
||||
@@ -234,89 +255,4 @@ pub(crate) mod fixtures {
|
||||
key_header: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local(id: &str) -> Connection {
|
||||
Connection {
|
||||
endpoint: Some("http://127.0.0.1:8188".into()),
|
||||
locality: Locality::Local,
|
||||
auth: Auth::None,
|
||||
billing: Billing::Free,
|
||||
..remote(id)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::fixtures::{local, remote};
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn good_connections_validate() {
|
||||
assert!(remote("a").validate().is_ok());
|
||||
assert!(local("b").validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_remote_host_cannot_be_labelled_local() {
|
||||
let mut c = remote("a");
|
||||
c.locality = Locality::Local;
|
||||
assert_eq!(c.validate(), Err(ConnectionError::LocalButNotLoopback));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_userinfo_trick_cannot_make_a_remote_host_local() {
|
||||
let mut c = local("a");
|
||||
c.endpoint = Some("http://127.0.0.1@evil.example/".into());
|
||||
assert!(matches!(c.validate(), Err(ConnectionError::Endpoint(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loopback_labelled_remote_is_flagged() {
|
||||
let mut c = local("a");
|
||||
c.locality = Locality::Remote;
|
||||
assert_eq!(c.validate(), Err(ConnectionError::RemoteButLoopback));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subscription_route_without_endpoint_cannot_be_local() {
|
||||
let mut c = remote("codex");
|
||||
c.endpoint = None;
|
||||
c.auth = Auth::Subscription { route: "codex-app-server".into(), secret: SecretRef::new("s").unwrap() };
|
||||
c.locality = Locality::Local;
|
||||
assert_eq!(c.validate(), Err(ConnectionError::LocalWithoutEndpointNeedsNoAuth));
|
||||
c.locality = Locality::Remote;
|
||||
assert!(c.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn in_process_model_can_be_local_without_endpoint() {
|
||||
let mut c = local("onnx");
|
||||
c.endpoint = None;
|
||||
assert!(c.validate().is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_models_and_empty_labels_are_refused() {
|
||||
let mut c = remote("a");
|
||||
let m = ModelInfo::new(crate::ids::ModelId::new("m").unwrap(), "M");
|
||||
c.models = vec![m.clone(), m];
|
||||
assert!(matches!(c.validate(), Err(ConnectionError::DuplicateModel(_))));
|
||||
let mut c = remote("b");
|
||||
c.label = " ".into();
|
||||
assert_eq!(c.validate(), Err(ConnectionError::EmptyLabel));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialized_form_holds_a_reference_not_a_secret() {
|
||||
let json = serde_json::to_string(&remote("a")).unwrap();
|
||||
assert!(json.contains("\"secret\":\"secret-a\""));
|
||||
assert!(!json.to_lowercase().contains("sk-"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_round_trip() {
|
||||
let c = remote("a");
|
||||
assert_eq!(serde_json::from_str::<Connection>(&serde_json::to_string(&c).unwrap()).unwrap(), c);
|
||||
}
|
||||
}
|
||||
+14
-160
@@ -24,27 +24,35 @@ use crate::request::Request;
|
||||
/// One thing a request sends.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct DisclosureItem {
|
||||
/// The role the input plays in the request.
|
||||
pub role: InputRole,
|
||||
/// The kind of data sent.
|
||||
pub kind: PayloadKind,
|
||||
/// Size in bytes when known.
|
||||
pub bytes: Option<u64>,
|
||||
}
|
||||
|
||||
/// What a request will send to a connection.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Disclosure {
|
||||
/// The app that sends the request.
|
||||
pub app: AppId,
|
||||
/// The connection the request goes to.
|
||||
pub connection: ConnectionId,
|
||||
/// What the request asks the connection to do. Consent is given per capability.
|
||||
pub capability: CapabilityId,
|
||||
/// Whether the connection is local or remote.
|
||||
pub locality: Locality,
|
||||
/// `scheme://host[:port]`, or the route name when there is no endpoint.
|
||||
pub destination: String,
|
||||
/// The inputs the request sends.
|
||||
pub items: Vec<DisclosureItem>,
|
||||
/// Parameter names only, never values.
|
||||
pub param_names: Vec<String>,
|
||||
}
|
||||
|
||||
impl Disclosure {
|
||||
/// Builds the disclosure for sending `request` from `app` through `connection`.
|
||||
pub fn for_request(app: &AppId, connection: &Connection, request: &Request) -> Self {
|
||||
let destination = connection
|
||||
.endpoint
|
||||
@@ -85,7 +93,9 @@ impl Disclosure {
|
||||
/// another's.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ConsentRecord {
|
||||
/// The app that agreed.
|
||||
pub app: AppId,
|
||||
/// The connection agreed to.
|
||||
pub connection: ConnectionId,
|
||||
/// The destination agreed to. A different destination needs fresh consent.
|
||||
pub destination: String,
|
||||
@@ -93,6 +103,7 @@ pub struct ConsentRecord {
|
||||
/// none and covers nothing, so the person is asked once more.
|
||||
#[serde(default)]
|
||||
pub capability: Option<CapabilityId>,
|
||||
/// The kinds of data the agreement covers.
|
||||
pub kinds: Vec<PayloadKind>,
|
||||
/// Unix seconds. The agreement holds while the clock is before this; `None` holds until
|
||||
/// revoked.
|
||||
@@ -111,6 +122,7 @@ impl ConsentRecord {
|
||||
/// An app's saved agreements.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ConsentLedger {
|
||||
/// The saved agreements.
|
||||
#[serde(default)]
|
||||
pub records: Vec<ConsentRecord>,
|
||||
}
|
||||
@@ -165,6 +177,7 @@ impl ConsentLedger {
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes every agreement the app has for the connection, whatever the destination or capability.
|
||||
pub fn revoke(&mut self, app: &AppId, connection: &ConnectionId) {
|
||||
self.records.retain(|r| !(&r.app == app && &r.connection == connection));
|
||||
}
|
||||
@@ -174,7 +187,7 @@ impl ConsentLedger {
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::capability::CapabilityId;
|
||||
use crate::connection::fixtures::{local, remote};
|
||||
use crate::connection::fixtures::remote;
|
||||
use crate::payload::Payload;
|
||||
|
||||
fn app() -> AppId {
|
||||
@@ -188,32 +201,6 @@ mod tests {
|
||||
.with_param("seed", 7.into())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disclosure_lists_kinds_sizes_and_param_names_not_contents() {
|
||||
let d = Disclosure::for_request(&app(), &remote("a"), &req());
|
||||
assert_eq!(d.destination, "https://api.example.com");
|
||||
assert_eq!(d.kinds(), vec![PayloadKind::Text, PayloadKind::Image]);
|
||||
assert_eq!(d.items.first().and_then(|i| i.bytes), Some(10));
|
||||
assert_eq!(d.param_names, vec!["seed".to_string()]);
|
||||
let json = serde_json::to_string(&d).unwrap();
|
||||
assert!(!json.contains("a cat"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_connections_never_ask() {
|
||||
let d = Disclosure::for_request(&app(), &local("a"), &req());
|
||||
assert!(!ConsentLedger::default().needs_consent(&d, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_asks_until_granted_then_stops() {
|
||||
let d = Disclosure::for_request(&app(), &remote("a"), &req());
|
||||
let mut ledger = ConsentLedger::default();
|
||||
assert!(ledger.needs_consent(&d, 0));
|
||||
ledger.grant(&d);
|
||||
assert!(!ledger.needs_consent(&d, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_kind_of_data_asks_again() {
|
||||
let mut ledger = ConsentLedger::default();
|
||||
@@ -226,113 +213,10 @@ mod tests {
|
||||
assert_eq!(ledger.records.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_the_host_invalidates_consent() {
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant(&Disclosure::for_request(&app(), &remote("a"), &req()));
|
||||
let mut moved = remote("a");
|
||||
moved.endpoint = Some("https://other.example.org".into());
|
||||
assert!(ledger.needs_consent(&Disclosure::for_request(&app(), &moved, &req()), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consent_is_per_app_and_revocable() {
|
||||
let mut ledger = ConsentLedger::default();
|
||||
let d = Disclosure::for_request(&app(), &remote("a"), &req());
|
||||
ledger.grant(&d);
|
||||
let other = Disclosure::for_request(&AppId::new("wordcraft").unwrap(), &remote("a"), &req());
|
||||
assert!(ledger.needs_consent(&other, 0));
|
||||
ledger.revoke(&app(), &remote("a").id);
|
||||
assert!(ledger.needs_consent(&d, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parameters_alone_still_need_consent() {
|
||||
let only_params = Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_param("negative", "a private note".into());
|
||||
let d = disclosure_for(&only_params);
|
||||
assert_eq!(d.kinds(), vec![PayloadKind::Text]);
|
||||
let mut ledger = ConsentLedger::default();
|
||||
assert!(ledger.needs_consent(&d, 0));
|
||||
ledger.grant(&d);
|
||||
assert!(!ledger.needs_consent(&d, 0));
|
||||
}
|
||||
|
||||
fn upscale_req() -> Request {
|
||||
Request::new(CapabilityId::parse("image.upscale").unwrap()).with_input(InputRole::Source, Payload::inline("image/png", vec![0; 10]).unwrap())
|
||||
}
|
||||
|
||||
fn disclosure_for(r: &Request) -> Disclosure {
|
||||
Disclosure::for_request(&app(), &remote("a"), r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disclosure_names_the_capability() {
|
||||
assert_eq!(disclosure_for(&req()).capability, CapabilityId::parse("image.inpaint").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consent_for_one_capability_does_not_cover_another() {
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant(&disclosure_for(&req()));
|
||||
let other = disclosure_for(&upscale_req());
|
||||
assert!(ledger.needs_consent(&other, 0));
|
||||
ledger.grant(&other);
|
||||
assert!(!ledger.needs_consent(&other, 0));
|
||||
assert!(!ledger.needs_consent(&disclosure_for(&req()), 0));
|
||||
assert_eq!(ledger.records.len(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timed_agreement_lapses_at_its_expiry() {
|
||||
let d = disclosure_for(&req());
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant_until(&d, 1_000);
|
||||
assert!(!ledger.needs_consent(&d, 0));
|
||||
assert!(!ledger.needs_consent(&d, 999));
|
||||
assert!(ledger.needs_consent(&d, 1_000));
|
||||
assert!(ledger.needs_consent(&d, 5_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_open_agreement_never_lapses() {
|
||||
let d = disclosure_for(&req());
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant(&d);
|
||||
assert!(!ledger.needs_consent(&d, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agreeing_again_after_it_lapsed_renews_it() {
|
||||
let d = disclosure_for(&req());
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant_until(&d, 1_000);
|
||||
assert!(ledger.needs_consent(&d, 2_000));
|
||||
ledger.grant_until(&d, 3_000);
|
||||
assert!(!ledger.needs_consent(&d, 2_000));
|
||||
assert!(ledger.needs_consent(&d, 3_000));
|
||||
assert_eq!(ledger.records.len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_latest_agreement_sets_the_expiry_for_that_capability() {
|
||||
let d = disclosure_for(&req());
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant(&d);
|
||||
ledger.grant_until(&d, 1_000);
|
||||
assert!(ledger.needs_consent(&d, 1_000));
|
||||
ledger.grant(&d);
|
||||
assert!(!ledger.needs_consent(&d, u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_timed_agreement_for_one_capability_leaves_another_open() {
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant(&disclosure_for(&req()));
|
||||
ledger.grant_until(&disclosure_for(&upscale_req()), 1_000);
|
||||
assert!(!ledger.needs_consent(&disclosure_for(&req()), 5_000));
|
||||
assert!(ledger.needs_consent(&disclosure_for(&upscale_req()), 5_000));
|
||||
}
|
||||
|
||||
fn text_only_req() -> Request {
|
||||
Request::new(CapabilityId::parse("image.inpaint").unwrap()).with_input(InputRole::Prompt, Payload::text("a cat"))
|
||||
}
|
||||
@@ -347,34 +231,4 @@ mod tests {
|
||||
assert!(!ledger.needs_consent(&text, 2_000));
|
||||
assert!(ledger.needs_consent(&disclosure_for(&req()), 2_000), "image consent lapsed at 1000 and was not renewed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renewing_one_kind_leaves_the_others_on_their_own_expiry() {
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant_until(&disclosure_for(&req()), 1_000);
|
||||
ledger.grant(&disclosure_for(&text_only_req()));
|
||||
let both = disclosure_for(&req());
|
||||
assert!(!ledger.needs_consent(&both, 999));
|
||||
assert!(ledger.needs_consent(&both, 1_000));
|
||||
assert!(!ledger.needs_consent(&disclosure_for(&text_only_req()), u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_record_from_before_scoping_loads_but_covers_nothing() {
|
||||
let old = r#"{"records":[{"app":"photocraft","connection":"a","destination":"https://api.example.com","kinds":["text","image"]}]}"#;
|
||||
let ledger: ConsentLedger = serde_json::from_str(old).unwrap();
|
||||
assert_eq!(ledger.records.len(), 1);
|
||||
assert_eq!(ledger.records[0].capability, None);
|
||||
assert_eq!(ledger.records[0].expires_at, None);
|
||||
assert!(ledger.needs_consent(&disclosure_for(&req()), 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_capability_and_expiry_survive_a_save() {
|
||||
let mut ledger = ConsentLedger::default();
|
||||
ledger.grant_until(&disclosure_for(&req()), 1_000);
|
||||
let back: ConsentLedger = serde_json::from_str(&serde_json::to_string(&ledger).unwrap()).unwrap();
|
||||
assert_eq!(back, ledger);
|
||||
assert_eq!(back.records[0].expires_at, Some(1_000));
|
||||
}
|
||||
}
|
||||
@@ -40,10 +40,13 @@ pub struct Preset {
|
||||
pub key: &'static str,
|
||||
/// What the button says.
|
||||
pub name: &'static str,
|
||||
/// Adapter name the preset selects.
|
||||
pub provider: &'static str,
|
||||
/// Empty for "type your own".
|
||||
pub endpoint: &'static str,
|
||||
/// Billing the preset assumes.
|
||||
pub billing: Billing,
|
||||
/// Whether the form asks for a key.
|
||||
pub needs_key: bool,
|
||||
/// One line about it, shown under the name.
|
||||
pub note: &'static str,
|
||||
@@ -182,9 +185,13 @@ fn preset_models(preset: &Preset) -> Vec<ModelInfo> {
|
||||
/// Which box a problem belongs to, so a form can mark it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Field {
|
||||
#[allow(missing_docs)]
|
||||
Label,
|
||||
#[allow(missing_docs)]
|
||||
Provider,
|
||||
#[allow(missing_docs)]
|
||||
Address,
|
||||
#[allow(missing_docs)]
|
||||
Key,
|
||||
/// The name of the header that carries the key.
|
||||
KeyHeader,
|
||||
@@ -193,7 +200,9 @@ pub enum Field {
|
||||
/// Why a draft was refused. The message is safe to show.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct DraftError {
|
||||
/// The box the problem belongs to.
|
||||
pub field: Field,
|
||||
/// What to tell the user.
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
@@ -216,6 +225,7 @@ impl std::error::Error for DraftError {}
|
||||
pub enum KeyChange {
|
||||
/// Leave whatever is saved.
|
||||
Keep,
|
||||
/// Save this key, replacing any saved one.
|
||||
Set(SecretString),
|
||||
/// The connection no longer uses a key; remove the saved one.
|
||||
Clear,
|
||||
@@ -224,7 +234,9 @@ pub enum KeyChange {
|
||||
/// A checked connection and what to do with its key.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Prepared {
|
||||
/// The validated connection to save.
|
||||
pub connection: Connection,
|
||||
/// What to do with the stored key.
|
||||
pub key: KeyChange,
|
||||
}
|
||||
|
||||
@@ -233,17 +245,23 @@ pub struct Prepared {
|
||||
pub struct ConnectionDraft {
|
||||
/// `Some` when editing an existing connection.
|
||||
pub editing: Option<ConnectionId>,
|
||||
#[allow(missing_docs)]
|
||||
pub label: String,
|
||||
#[allow(missing_docs)]
|
||||
pub provider: String,
|
||||
#[allow(missing_docs)]
|
||||
pub endpoint: String,
|
||||
#[allow(missing_docs)]
|
||||
pub billing: Billing,
|
||||
/// Whether the connection authenticates with a key.
|
||||
pub uses_key: bool,
|
||||
/// Text typed into the key box. Empty while editing means "keep the saved key". It is a plain
|
||||
/// string only because a text box needs one; [`Debug`] never prints it and [`prepare`]
|
||||
/// string only because a text box needs one; [`Debug`] never prints it and [`Self::prepare`]
|
||||
/// (Self::prepare) turns it into a [`SecretString`].
|
||||
pub key: String,
|
||||
/// Header that carries the key; empty sends it as `Authorization: Bearer`.
|
||||
pub key_header: String,
|
||||
/// Whether the connection is offered for use.
|
||||
pub enabled: bool,
|
||||
/// Models carried onto the saved connection. Assigning here declares them by hand and records
|
||||
/// no address, so they survive any address change; models a test found go through
|
||||
@@ -329,7 +347,7 @@ impl ConnectionDraft {
|
||||
/// A test is not instant and the address stays editable while it runs, so its answer can
|
||||
/// arrive after the address has changed, or after a later test at the new address has already
|
||||
/// answered. Recording it then would file one endpoint's models under another, which is what
|
||||
/// [`models_fit`](Self::models_fit) exists to prevent. An answer is therefore taken only while
|
||||
/// `models_fit` exists to prevent. An answer is therefore taken only while
|
||||
/// the field still holds the address it was asked of, and a late one is dropped. Returns
|
||||
/// whether the models were taken, so a caller can say "this result is out of date".
|
||||
///
|
||||
|
||||
@@ -10,120 +10,6 @@ fn with_key(mut d: ConnectionDraft, key: &str) -> ConnectionDraft {
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_preset_with_an_address_makes_a_valid_connection() {
|
||||
for p in PRESETS.iter().filter(|p| !p.endpoint.is_empty()) {
|
||||
let d = with_key(ConnectionDraft::from_preset(p), "sk-test-123");
|
||||
let prepared = d.prepare(&[]).unwrap_or_else(|e| panic!("{}: {e}", p.key));
|
||||
assert!(prepared.connection.validate().is_ok());
|
||||
assert_eq!(prepared.connection.auth.secret_ref().is_some(), p.needs_key, "{}", p.key);
|
||||
}
|
||||
// The custom preset needs an address typed in.
|
||||
let custom = with_key(draft("custom"), "k");
|
||||
assert_eq!(custom.prepare(&[]).unwrap_err().field, Field::Address);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn artcraft_api_key_preset_is_distinct_from_unverified_account_access() {
|
||||
let p = PRESETS.iter().find(|p| p.key == "artcraft-omni").unwrap();
|
||||
assert_eq!(p.provider, "artcraft-omni");
|
||||
assert!(p.needs_key);
|
||||
assert_eq!(p.endpoint, "https://api.storyteller.ai");
|
||||
assert!(!PRESETS.iter().any(|p| p.key == "artcraft-account"));
|
||||
let prepared = with_key(ConnectionDraft::from_preset(p), "test-key").prepare(&[]).unwrap();
|
||||
assert_eq!(prepared.connection.models.len(), 2);
|
||||
assert!(prepared.connection.models.iter().any(|m| m.id.as_str() == "nano_banana"));
|
||||
assert!(prepared.connection.models.iter().any(|m| m.id.as_str() == "seedance_2p0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn where_it_goes_decides_local_or_remote() {
|
||||
assert_eq!(draft("ollama").locality(), Some(Locality::Local));
|
||||
assert_eq!(draft("openai").locality(), Some(Locality::Remote));
|
||||
let mut d = draft("custom");
|
||||
assert_eq!(d.locality(), None, "no address yet");
|
||||
d.endpoint = "https://localhost.evil.example".into();
|
||||
assert_eq!(d.locality(), Some(Locality::Remote), "a lookalike host is remote");
|
||||
d.endpoint = "not a url".into();
|
||||
assert_eq!(d.locality(), None);
|
||||
// The connection carries what the address says, whatever the preset hoped.
|
||||
let mut o = with_key(draft("ollama"), "");
|
||||
o.endpoint = "https://api.example.com/v1".into();
|
||||
let c = o.prepare(&[]).unwrap().connection;
|
||||
assert_eq!(c.locality, Locality::Remote);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_http_is_refused_unless_it_is_this_computer() {
|
||||
let mut d = with_key(draft("custom"), "k");
|
||||
d.endpoint = "http://192.168.1.20:8000/v1".into();
|
||||
let e = d.prepare(&[]).unwrap_err();
|
||||
assert_eq!(e.field, Field::Address);
|
||||
assert!(e.message.contains("https://"), "{e}");
|
||||
d.endpoint = "http://user:pw@127.0.0.1/v1".into();
|
||||
assert!(d.prepare(&[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_must_be_one_clean_line() {
|
||||
for bad in ["sk-abc\ndef", "sk abc", "sk-\u{e9}", "sk-abc\u{0}", &"x".repeat(MAX_KEY_BYTES + 1)] {
|
||||
let d = with_key(draft("openai"), bad);
|
||||
let e = d.prepare(&[]).unwrap_err();
|
||||
assert_eq!(e.field, Field::Key, "{bad:?}");
|
||||
assert!(!e.message.contains("abc"), "the message must not echo the key");
|
||||
}
|
||||
// Surrounding whitespace from a paste is trimmed, not refused.
|
||||
let d = with_key(draft("openai"), " sk-good-key\r\n");
|
||||
match d.prepare(&[]).unwrap().key {
|
||||
KeyChange::Set(k) => assert_eq!(k.expose(), "sk-good-key"),
|
||||
other => panic!("{other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_connection_that_needs_a_key_must_have_one() {
|
||||
let e = draft("openai").prepare(&[]).unwrap_err();
|
||||
assert_eq!(e.field, Field::Key);
|
||||
// Turning the key off makes it a no-key connection.
|
||||
let mut d = draft("openai");
|
||||
d.uses_key = false;
|
||||
let p = d.prepare(&[]).unwrap();
|
||||
assert_eq!(p.connection.auth, Auth::None);
|
||||
assert!(matches!(p.key, KeyChange::Keep), "nothing saved, nothing to clear");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn names_are_checked() {
|
||||
let mut d = with_key(draft("openai"), "k");
|
||||
d.label = " ".into();
|
||||
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label);
|
||||
d.label = "two\nlines".into();
|
||||
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label);
|
||||
d.label = "x".repeat(MAX_LABEL_CHARS + 1);
|
||||
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Label);
|
||||
d.label = "OpenAI".into();
|
||||
d.provider = "bad provider!".into();
|
||||
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::Provider);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_come_from_the_name_and_stay_unique() {
|
||||
let first = with_key(draft("openai"), "k").prepare(&[]).unwrap();
|
||||
assert_eq!(first.connection.id.as_str(), "openai");
|
||||
assert_eq!(first.connection.auth.secret_ref().unwrap().as_str(), "openai.key");
|
||||
let second = with_key(draft("openai"), "k2").prepare(std::slice::from_ref(&first.connection)).unwrap();
|
||||
assert_eq!(second.connection.id.as_str(), "openai-2");
|
||||
// Two connections never share a key, even with the same name.
|
||||
assert_eq!(second.connection.auth.secret_ref().unwrap().as_str(), "openai-2.key");
|
||||
let mut odd = with_key(draft("openai"), "k");
|
||||
odd.label = "!!! Café Ünïcode ???".into();
|
||||
let c = odd.prepare(&[]).unwrap().connection;
|
||||
assert_eq!(c.id.as_str(), "caf-n-code");
|
||||
odd.label = "???".into();
|
||||
assert_eq!(odd.prepare(&[]).unwrap().connection.id.as_str(), "connection");
|
||||
assert_eq!(c.label, "!!! Café Ünïcode ???", "the label itself is kept as typed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_taken_key_locator_is_never_reused() {
|
||||
let mut other = with_key(draft("openai"), "k").prepare(&[]).unwrap().connection;
|
||||
@@ -133,117 +19,3 @@ fn a_taken_key_locator_is_never_reused() {
|
||||
let p = with_key(draft("openai"), "k2").prepare(&[other]).unwrap();
|
||||
assert_eq!(p.connection.auth.secret_ref().unwrap().as_str(), "openai.key2");
|
||||
}
|
||||
|
||||
fn saved_openai() -> Connection {
|
||||
let mut c = with_key(draft("openai"), "sk-x").prepare(&[]).unwrap().connection;
|
||||
c.models = vec![ModelInfo::new(crate::ids::ModelId::new("gpt-x").unwrap(), "GPT X")];
|
||||
c
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_keeps_the_saved_key_unless_a_new_one_is_typed() {
|
||||
let saved = saved_openai();
|
||||
let mut d = ConnectionDraft::from_connection(&saved);
|
||||
assert!(d.key.is_empty());
|
||||
d.label = "Work OpenAI".into();
|
||||
let p = d.prepare(std::slice::from_ref(&saved)).unwrap();
|
||||
assert!(matches!(p.key, KeyChange::Keep));
|
||||
assert_eq!(p.connection.id, saved.id, "the id never changes on rename");
|
||||
assert_eq!(p.connection.auth, saved.auth, "same secret locator");
|
||||
d.key = "sk-new".into();
|
||||
assert!(matches!(d.prepare(std::slice::from_ref(&saved)).unwrap().key, KeyChange::Set(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn turning_the_key_off_clears_the_saved_one() {
|
||||
let saved = saved_openai();
|
||||
let mut d = ConnectionDraft::from_connection(&saved);
|
||||
d.uses_key = false;
|
||||
let p = d.prepare(std::slice::from_ref(&saved)).unwrap();
|
||||
assert!(matches!(p.key, KeyChange::Clear));
|
||||
assert_eq!(p.connection.auth, Auth::None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_follow_the_address() {
|
||||
let saved = saved_openai();
|
||||
let same = ConnectionDraft::from_connection(&saved);
|
||||
assert_eq!(same.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.len(), 1);
|
||||
let mut moved = ConnectionDraft::from_connection(&saved);
|
||||
moved.endpoint = "https://other.example.com/v1".into();
|
||||
assert!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_found_at_the_new_address_are_kept() {
|
||||
let saved = saved_openai();
|
||||
let found = vec![ModelInfo::new(crate::ids::ModelId::new("llama-x").unwrap(), "Llama X")];
|
||||
let mut moved = ConnectionDraft::from_connection(&saved);
|
||||
moved.endpoint = "https://other.example.com/v1".into();
|
||||
assert!(moved.set_models("https://other.example.com/v1", found.clone()));
|
||||
assert_eq!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, found);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_retest_that_finds_the_same_models_keeps_them() {
|
||||
let saved = saved_openai();
|
||||
let mut moved = ConnectionDraft::from_connection(&saved);
|
||||
moved.endpoint = "https://other.example.com/v1".into();
|
||||
assert!(moved.set_models("https://other.example.com/v1", saved.models.clone()));
|
||||
assert_eq!(moved.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, saved.models);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_found_before_the_address_changed_are_dropped() {
|
||||
let saved = saved_openai();
|
||||
let found = vec![ModelInfo::new(crate::ids::ModelId::new("llama-x").unwrap(), "Llama X")];
|
||||
let mut d = ConnectionDraft::from_connection(&saved);
|
||||
let at = d.endpoint.clone();
|
||||
assert!(d.set_models(&at, found));
|
||||
d.endpoint = "https://other.example.com/v1".into();
|
||||
assert!(d.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_something_removed_elsewhere_is_an_error() {
|
||||
let saved = saved_openai();
|
||||
let d = ConnectionDraft::from_connection(&saved);
|
||||
assert!(d.prepare(&[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_secret_shows_in_debug_or_errors() {
|
||||
let d = with_key(draft("openai"), "sk-very-secret-value");
|
||||
assert!(!format!("{d:?}").contains("secret-value"));
|
||||
let mut bad = d.clone();
|
||||
bad.endpoint = "nope".into();
|
||||
let e = bad.prepare(&[]).unwrap_err();
|
||||
assert!(!format!("{e} {e:?}").contains("secret-value"));
|
||||
let p = d.prepare(&[]).unwrap();
|
||||
assert!(!format!("{p:?}").contains("secret-value"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_text_never_panics() {
|
||||
let nasty = ["", "\0", "\u{202e}rtl", "💥💥💥", &"a".repeat(100_000), "http://[::1", "https://", "%00%00", "' OR 1=1 --"];
|
||||
for a in nasty {
|
||||
for b in nasty {
|
||||
let mut d = draft("custom");
|
||||
d.label = a.to_owned();
|
||||
d.endpoint = b.to_owned();
|
||||
d.provider = a.to_owned();
|
||||
d.key = b.to_owned();
|
||||
let _ = d.prepare(&[]);
|
||||
let _ = d.locality();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seedance_connects_through_byteplus_modelark_with_an_api_key() {
|
||||
let p = PRESETS.iter().find(|p| p.key == "seedance").unwrap();
|
||||
assert_eq!(p.endpoint, "https://ark.ap-southeast.bytepluses.com/api/v3");
|
||||
assert!(p.name.contains("BytePlus"), "{}", p.name);
|
||||
assert!(!p.name.contains("Volcengine"), "{}", p.name);
|
||||
assert!(p.needs_key);
|
||||
}
|
||||
@@ -15,8 +15,11 @@ const MAX_ENDPOINT_LEN: usize = 2048;
|
||||
/// A parsed endpoint.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Endpoint {
|
||||
/// True for `https`, false for `http`.
|
||||
pub https: bool,
|
||||
/// Host name or address, without port.
|
||||
pub host: String,
|
||||
/// Explicit port, or `None` for the scheme default.
|
||||
pub port: Option<u16>,
|
||||
}
|
||||
|
||||
@@ -100,26 +103,6 @@ fn parse_port(p: &str) -> Result<u16, IdError> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn loopback_forms() {
|
||||
for ok in ["http://localhost:8188", "http://127.0.0.1:11434/v1", "http://127.9.9.9", "http://[::1]:8080/x"] {
|
||||
assert!(Endpoint::parse(ok).unwrap().is_loopback(), "{ok}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_https() {
|
||||
let e = Endpoint::parse("https://api.example.com/v1").unwrap();
|
||||
assert!(!e.is_loopback());
|
||||
assert_eq!(e.fingerprint(), "https://api.example.com");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_http_to_a_remote_host_is_refused() {
|
||||
assert!(Endpoint::parse("http://api.example.com").is_err());
|
||||
assert!(Endpoint::parse("http://192.168.1.20:8188").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn userinfo_trick_is_refused() {
|
||||
assert!(Endpoint::parse("http://127.0.0.1@evil.example/").is_err());
|
||||
@@ -135,32 +118,4 @@ mod tests {
|
||||
assert!(!Endpoint::parse(host).unwrap().is_loopback(), "{host}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_garbage_without_panicking() {
|
||||
for bad in [
|
||||
"",
|
||||
"ftp://x",
|
||||
"https://",
|
||||
"https://:80",
|
||||
"http://[::1",
|
||||
"http://[::1]x",
|
||||
"https://a b",
|
||||
"https://a:99999",
|
||||
"https://a\\b",
|
||||
"localhost:8080",
|
||||
] {
|
||||
assert!(Endpoint::parse(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
assert!(Endpoint::parse(&format!("https://{}", "a".repeat(5000))).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fingerprint_changes_with_host_and_port() {
|
||||
let a = Endpoint::parse("https://a.example:8443/x").unwrap().fingerprint();
|
||||
let b = Endpoint::parse("https://b.example:8443/x").unwrap().fingerprint();
|
||||
assert_eq!(a, "https://a.example:8443");
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(Endpoint::parse("http://[::1]:80").unwrap().fingerprint(), "http://[::1]:80");
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,7 @@ pub enum ErrorKind {
|
||||
}
|
||||
|
||||
impl ErrorKind {
|
||||
/// A short lowercase name for messages and logs.
|
||||
pub fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Unsupported => "unsupported",
|
||||
@@ -57,25 +58,32 @@ impl ErrorKind {
|
||||
/// The error type of the whole crate.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AiError {
|
||||
/// What went wrong, for the app to act on.
|
||||
pub kind: ErrorKind,
|
||||
/// Human-readable detail. Secrets are scrubbed when built with [`AiError::redacted`].
|
||||
pub message: String,
|
||||
/// How long to wait before retrying, when the provider said so.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub retry_after_secs: Option<u64>,
|
||||
}
|
||||
|
||||
impl AiError {
|
||||
/// Builds an error of the given kind.
|
||||
pub fn new(kind: ErrorKind, message: impl Into<String>) -> Self {
|
||||
Self { kind, message: message.into(), retry_after_secs: None }
|
||||
}
|
||||
|
||||
/// Builds an [`ErrorKind::Unsupported`] error.
|
||||
pub fn unsupported(message: impl Into<String>) -> Self {
|
||||
Self::new(ErrorKind::Unsupported, message)
|
||||
}
|
||||
|
||||
/// Builds an [`ErrorKind::InvalidRequest`] error.
|
||||
pub fn invalid(message: impl Into<String>) -> Self {
|
||||
Self::new(ErrorKind::InvalidRequest, message)
|
||||
}
|
||||
|
||||
/// Builds an [`ErrorKind::Cancelled`] error.
|
||||
pub fn cancelled() -> Self {
|
||||
Self::new(ErrorKind::Cancelled, "cancelled")
|
||||
}
|
||||
@@ -85,6 +93,7 @@ impl AiError {
|
||||
Self::new(kind, redact(message, secrets))
|
||||
}
|
||||
|
||||
/// Sets the wait, in seconds, before a retry.
|
||||
pub fn with_retry_after(mut self, secs: u64) -> Self {
|
||||
self.retry_after_secs = Some(secs);
|
||||
self
|
||||
@@ -103,38 +112,3 @@ impl fmt::Display for AiError {
|
||||
}
|
||||
|
||||
impl std::error::Error for AiError {}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn redacted_removes_the_key() {
|
||||
let key = SecretString::new("sk-test-999");
|
||||
let e = AiError::redacted(ErrorKind::Auth, "invalid key sk-test-999", &[&key]);
|
||||
assert!(!e.message.contains("999"));
|
||||
assert!(!format!("{e}").contains("999"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn consent_required_is_not_retryable_and_round_trips() {
|
||||
let e = AiError::new(ErrorKind::ConsentRequired, "ask first");
|
||||
assert!(!e.is_retryable());
|
||||
let back: AiError = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
|
||||
assert_eq!(back.kind, ErrorKind::ConsentRequired);
|
||||
assert!(format!("{e}").starts_with("consent required"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retryable_kinds() {
|
||||
assert!(AiError::new(ErrorKind::RateLimited, "x").is_retryable());
|
||||
assert!(!AiError::unsupported("x").is_retryable());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips_through_json() {
|
||||
let e = AiError::new(ErrorKind::RateLimited, "slow down").with_retry_after(30);
|
||||
let back: AiError = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
|
||||
assert_eq!(e, back);
|
||||
}
|
||||
}
|
||||
@@ -28,27 +28,41 @@ pub const MAX_PROMPT_CHARS: usize = 2000;
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "status", rename_all = "snake_case")]
|
||||
pub enum Outcome {
|
||||
/// The job finished and produced a result.
|
||||
Done,
|
||||
Failed { kind: ErrorKind },
|
||||
/// The job failed. Only the error kind is kept, never the message.
|
||||
Failed {
|
||||
/// What kind of failure it was.
|
||||
kind: ErrorKind,
|
||||
},
|
||||
/// The user or app cancelled the job.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
/// Written when a job is submitted (or refused by the provider).
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct StartRecord {
|
||||
/// Schema version, [`HISTORY_SCHEMA`].
|
||||
pub v: u32,
|
||||
/// Joins this line to its [`EndRecord`]. Unique across apps and runs.
|
||||
pub run: String,
|
||||
/// Unix milliseconds.
|
||||
pub at_ms: u64,
|
||||
/// Id of the app that submitted the job.
|
||||
pub app: String,
|
||||
/// Id of the role the job ran for.
|
||||
pub role_id: String,
|
||||
/// The feature as the user knows it, such as "Generative Fill".
|
||||
pub role_label: String,
|
||||
/// The capability requested, as `<modality>.<task>`.
|
||||
pub capability: String,
|
||||
/// Id of the connection used.
|
||||
pub connection: String,
|
||||
/// The connection's label when the job ran, kept in case the connection is later renamed or removed.
|
||||
pub connection_label: String,
|
||||
/// Id of the model used.
|
||||
pub model: String,
|
||||
/// Whether the connection was local or remote.
|
||||
pub locality: Locality,
|
||||
/// `scheme://host[:port]`, or the route name when there is no endpoint.
|
||||
pub destination: String,
|
||||
@@ -73,9 +87,13 @@ pub struct StartRecord {
|
||||
/// Written when a job reaches a final state.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct EndRecord {
|
||||
/// Schema version, [`HISTORY_SCHEMA`].
|
||||
pub v: u32,
|
||||
/// The run id shared with the [`StartRecord`].
|
||||
pub run: String,
|
||||
/// Unix milliseconds when the job ended.
|
||||
pub at_ms: u64,
|
||||
/// How the job ended.
|
||||
pub outcome: Outcome,
|
||||
/// What the provider reported, or `None`. Never an estimate of ours.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
@@ -88,14 +106,18 @@ pub struct EndRecord {
|
||||
#[serde(tag = "phase", rename_all = "snake_case")]
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
pub enum HistoryRecord {
|
||||
/// The line written at submission.
|
||||
Start(StartRecord),
|
||||
/// The line written at the final state.
|
||||
End(EndRecord),
|
||||
}
|
||||
|
||||
/// A job as the history list shows it: the start line and, if seen, the end line.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct HistoryEntry {
|
||||
/// The submission line.
|
||||
pub start: StartRecord,
|
||||
/// The final line, or `None` while unfinished.
|
||||
pub end: Option<EndRecord>,
|
||||
}
|
||||
|
||||
@@ -106,6 +128,7 @@ impl HistoryEntry {
|
||||
end.at_ms.checked_sub(self.start.at_ms)
|
||||
}
|
||||
|
||||
/// How the job ended, or `None` while unfinished.
|
||||
pub fn outcome(&self) -> Option<&Outcome> {
|
||||
self.end.as_ref().map(|e| &e.outcome)
|
||||
}
|
||||
@@ -120,7 +143,9 @@ impl HistoryEntry {
|
||||
/// Entries newest first, plus how many lines could not be read.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HistoryLog {
|
||||
/// Jobs, newest first.
|
||||
pub entries: Vec<HistoryEntry>,
|
||||
/// Lines that could not be read and were left out.
|
||||
pub skipped: usize,
|
||||
}
|
||||
|
||||
@@ -161,6 +186,3 @@ pub fn clip_prompt(text: &str) -> String {
|
||||
}
|
||||
|
||||
pub mod report;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -16,8 +16,11 @@ const DAY_MS: i64 = 86_400_000;
|
||||
/// A calendar day.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Day {
|
||||
#[allow(missing_docs)]
|
||||
pub year: i32,
|
||||
/// Month number, 1 to 12.
|
||||
pub month: u8,
|
||||
/// Day of the month, starting at 1.
|
||||
pub day: u8,
|
||||
}
|
||||
|
||||
@@ -38,6 +41,7 @@ impl Day {
|
||||
civil_from_days(days)
|
||||
}
|
||||
|
||||
/// The month this day falls in.
|
||||
pub fn month(self) -> Month {
|
||||
Month { year: self.year, month: self.month }
|
||||
}
|
||||
@@ -52,7 +56,9 @@ impl fmt::Display for Day {
|
||||
/// A calendar month.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct Month {
|
||||
#[allow(missing_docs)]
|
||||
pub year: i32,
|
||||
/// Month number, 1 to 12.
|
||||
pub month: u8,
|
||||
}
|
||||
|
||||
@@ -128,19 +134,23 @@ fn exact_amount(micros: u64) -> String {
|
||||
/// Which entries to show. An empty filter shows everything.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct HistoryFilter {
|
||||
/// Only jobs from this app id.
|
||||
pub app: Option<String>,
|
||||
/// Only jobs that used this model id.
|
||||
pub model: Option<String>,
|
||||
/// Only jobs that started at or after this Unix-millisecond time.
|
||||
pub since_ms: Option<u64>,
|
||||
}
|
||||
|
||||
impl HistoryFilter {
|
||||
/// Whether `entry` passes every filter that is set.
|
||||
pub fn matches(&self, entry: &HistoryEntry) -> bool {
|
||||
self.app.as_ref().is_none_or(|a| *a == entry.start.app)
|
||||
&& self.model.as_ref().is_none_or(|m| *m == entry.start.model)
|
||||
&& self.since_ms.is_none_or(|t| entry.start.at_ms >= t)
|
||||
}
|
||||
|
||||
/// The entries that pass, in their original order.
|
||||
pub fn apply<'a>(&self, entries: &'a [HistoryEntry]) -> Vec<&'a HistoryEntry> {
|
||||
entries.iter().filter(|e| self.matches(e)).collect()
|
||||
}
|
||||
@@ -164,9 +174,13 @@ fn distinct<'a>(items: impl Iterator<Item = &'a str>) -> Vec<String> {
|
||||
/// A count of jobs and the money the providers reported for them.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct Totals {
|
||||
/// Every job counted, finished or not.
|
||||
pub jobs: usize,
|
||||
/// Jobs that finished successfully.
|
||||
pub done: usize,
|
||||
/// Jobs that failed.
|
||||
pub failed: usize,
|
||||
/// Jobs that were cancelled.
|
||||
pub cancelled: usize,
|
||||
/// Started, but the app closed before the end was seen.
|
||||
pub unfinished: usize,
|
||||
@@ -181,6 +195,7 @@ pub struct Totals {
|
||||
}
|
||||
|
||||
impl Totals {
|
||||
/// Counts one entry into the totals.
|
||||
pub fn add(&mut self, entry: &HistoryEntry) {
|
||||
self.jobs += 1;
|
||||
if matches!(entry.outcome(), Some(Outcome::Done))
|
||||
@@ -213,6 +228,7 @@ impl Totals {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sums `entries` into one [`Totals`].
|
||||
pub fn totals<'a>(entries: impl IntoIterator<Item = &'a HistoryEntry>) -> Totals {
|
||||
let mut t = Totals::default();
|
||||
for e in entries {
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
use super::*;
|
||||
use crate::connection::Locality;
|
||||
use crate::error::ErrorKind;
|
||||
use crate::history::{EndRecord, HISTORY_SCHEMA, HistoryRecord, StartRecord, merge};
|
||||
use crate::job::{CostEstimate, Usage};
|
||||
use crate::job::Usage;
|
||||
|
||||
const HOUR: u64 = 3_600_000;
|
||||
const T0: u64 = 1_760_000_000_000; // 2025-10-09T08:53:20Z
|
||||
|
||||
fn start(run: &str, at_ms: u64, app: &str, model: &str) -> StartRecord {
|
||||
@@ -63,112 +61,6 @@ fn days_are_right_across_leap_days_epoch_and_year_ends() {
|
||||
assert_eq!(day_of(T0, 0).to_string(), "2025-10-09");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_offset_moves_the_day_boundary_both_ways() {
|
||||
let late = 1_767_225_599_000; // 2025-12-31T23:59:59Z
|
||||
assert_eq!(day_of(late, 60).to_string(), "2026-01-01");
|
||||
assert_eq!(day_of(late, -300).to_string(), "2025-12-31");
|
||||
let early = 1_767_225_600_000; // 2026-01-01T00:00:00Z
|
||||
assert_eq!(day_of(early, -1).to_string(), "2025-12-31");
|
||||
assert_eq!(day_of(0, -60).to_string(), "1969-12-31");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iso_time_is_utc_and_padded() {
|
||||
assert_eq!(iso_utc(T0), "2025-10-09T08:53:20Z");
|
||||
assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amounts_are_exact_and_small_costs_are_not_zero() {
|
||||
assert_eq!(amount_text(31_000), "0.03");
|
||||
assert_eq!(amount_text(1_234_567), "1.23");
|
||||
assert_eq!(amount_text(1_500), "0.0015");
|
||||
assert_eq!(amount_text(0), "0.0000");
|
||||
assert_eq!(exact_amount(31_000), "0.031000");
|
||||
assert_eq!(exact_amount(2_000_001), "2.000001");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_filter_narrows_by_app_model_and_time_and_empty_shows_all() {
|
||||
let e = entries(&[
|
||||
("a", T0, "photocraft", "m1", Some(Outcome::Done), Some(1)),
|
||||
("b", T0 + HOUR, "wordcraft", "m1", Some(Outcome::Done), None),
|
||||
("c", T0 + 2 * HOUR, "photocraft", "m2", None, None),
|
||||
]);
|
||||
assert_eq!(HistoryFilter::default().apply(&e).len(), 3);
|
||||
let photo = HistoryFilter { app: Some("photocraft".into()), ..HistoryFilter::default() };
|
||||
assert_eq!(photo.apply(&e).len(), 2);
|
||||
let both = HistoryFilter { model: Some("m2".into()), ..photo.clone() };
|
||||
assert_eq!(both.apply(&e).len(), 1);
|
||||
let recent = HistoryFilter { since_ms: Some(T0 + HOUR), ..HistoryFilter::default() };
|
||||
let runs: Vec<_> = recent.apply(&e).iter().map(|x| x.start.run.clone()).collect();
|
||||
assert_eq!(runs, ["c", "b"], "inclusive of the boundary, newest first");
|
||||
assert_eq!(apps(&e), ["photocraft", "wordcraft"]);
|
||||
assert_eq!(models(&e), ["m1", "m2"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn totals_count_outcomes_and_sum_cost_per_currency() {
|
||||
let e = entries(&[
|
||||
("a", T0, "p", "m", Some(Outcome::Done), Some(40_000)),
|
||||
("b", T0 + 1, "p", "m", Some(Outcome::Done), Some(25_000)),
|
||||
("c", T0 + 2, "p", "m", Some(Outcome::Done), None),
|
||||
("d", T0 + 3, "p", "m", Some(Outcome::Failed { kind: ErrorKind::Quota }), None),
|
||||
("e", T0 + 4, "p", "m", Some(Outcome::Cancelled), None),
|
||||
("f", T0 + 5, "p", "m", None, None),
|
||||
]);
|
||||
let t = totals(&e);
|
||||
assert_eq!(t.jobs, 6);
|
||||
assert_eq!((t.done, t.failed, t.cancelled, t.unfinished), (3, 1, 1, 1));
|
||||
assert_eq!(t.cost_micros.get("USD"), Some(&65_000));
|
||||
assert_eq!(t.without_cost, 1, "only a finished success counts as unpriced");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_huge_cost_saturates_instead_of_wrapping() {
|
||||
let e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), Some(u64::MAX)), ("b", T0 + 1, "p", "m", Some(Outcome::Done), Some(10))]);
|
||||
assert_eq!(totals(&e).cost_micros.get("USD"), Some(&u64::MAX));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn days_and_months_group_newest_first() {
|
||||
let day = 24 * HOUR;
|
||||
let e = entries(&[
|
||||
("a", T0, "p", "m", Some(Outcome::Done), Some(10_000)),
|
||||
("b", T0 + HOUR, "p", "m", Some(Outcome::Done), Some(20_000)),
|
||||
("c", T0 + day, "p", "m", Some(Outcome::Done), Some(5_000)),
|
||||
("d", T0 + 30 * day, "p", "m", Some(Outcome::Done), Some(1_000)),
|
||||
]);
|
||||
let refs: Vec<&HistoryEntry> = e.iter().collect();
|
||||
let days = by_day(&refs, 0);
|
||||
let labels: Vec<_> = days.iter().map(|(d, t)| (d.to_string(), t.jobs)).collect();
|
||||
assert_eq!(labels, [("2025-11-08".to_owned(), 1), ("2025-10-10".to_owned(), 1), ("2025-10-09".to_owned(), 2)]);
|
||||
let months = by_month(&refs, 0);
|
||||
let labels: Vec<_> = months.iter().map(|(m, t)| (m.to_string(), t.jobs, t.cost_micros.get("USD").copied())).collect();
|
||||
assert_eq!(labels, [("2025-11".to_owned(), 1, Some(1_000)), ("2025-10".to_owned(), 3, Some(35_000))]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_has_a_header_one_row_per_entry_and_matching_column_counts() {
|
||||
let mut e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), Some(31_000)), ("b", T0 + 5, "p", "m", None, None)]);
|
||||
e[0].start.estimate = Some(CostEstimate { micros: 30_000, currency: "USD".into(), billing: crate::Billing::Metered });
|
||||
let refs: Vec<&HistoryEntry> = e.iter().collect();
|
||||
let csv = to_csv(&refs);
|
||||
let lines: Vec<&str> = csv.split("\r\n").collect();
|
||||
assert_eq!(lines.len(), 4, "header, two rows, trailing empty");
|
||||
assert!(lines[0].starts_with("started_utc,app,feature"));
|
||||
assert_eq!(lines[0].split(',').count(), CSV_HEADER.len());
|
||||
// Newest first: the unfinished job (b) is the first row.
|
||||
assert!(lines[1].contains(",unfinished,"), "{}", lines[1]);
|
||||
assert!(lines[1].contains("0.030000,USD"), "estimate: {}", lines[1]);
|
||||
assert!(lines[2].contains("0.031000,USD"), "{}", lines[2]);
|
||||
assert!(lines[2].contains(",done,"), "{}", lines[2]);
|
||||
assert!(lines[2].contains(",2.000,"), "two seconds: {}", lines[2]);
|
||||
assert_eq!(lines[1].split(',').count(), CSV_HEADER.len());
|
||||
assert_eq!(lines[2].split(',').count(), CSV_HEADER.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_quotes_awkward_text_and_defuses_formulas() {
|
||||
let mut e = entries(&[("a", T0, "p", "m", Some(Outcome::Done), None)]);
|
||||
@@ -183,27 +75,6 @@ fn csv_quotes_awkward_text_and_defuses_formulas() {
|
||||
assert!(!csv.contains(",=HYPERLINK"), "{csv}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_job_exports_its_error_kind() {
|
||||
let e = entries(&[("a", T0, "p", "m", Some(Outcome::Failed { kind: ErrorKind::RateLimited }), None)]);
|
||||
let refs: Vec<&HistoryEntry> = e.iter().collect();
|
||||
assert!(to_csv(&refs).contains(",failed,rate_limited,"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn list_times_and_day_starts_follow_the_offset() {
|
||||
assert_eq!(time_text(T0, 0), "2025-10-09 08:53");
|
||||
assert_eq!(time_text(T0, 120), "2025-10-09 10:53");
|
||||
assert_eq!(time_text(T0, -540), "2025-10-08 23:53");
|
||||
// 2025-10-09T08:53:20Z; the UTC day began at 00:00Z.
|
||||
assert_eq!(start_of_day_ms(T0, 0), 1_759_968_000_000);
|
||||
// At UTC+2 the local day began at 22:00Z the evening before.
|
||||
assert_eq!(start_of_day_ms(T0, 120), 1_759_968_000_000 - 2 * HOUR);
|
||||
// At UTC-9 the local day (Oct 8) began at 09:00Z on Oct 8.
|
||||
assert_eq!(start_of_day_ms(T0, -540), 1_759_968_000_000 - 24 * HOUR + 9 * HOUR);
|
||||
assert_eq!(start_of_day_ms(0, 0), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn days_convert_to_and_from_the_epoch_count_both_ways() {
|
||||
for ms in [0, 951_782_400_000, 1_709_164_800_000, 1_767_225_599_000, T0] {
|
||||
@@ -232,41 +103,3 @@ fn days_convert_to_and_from_the_epoch_count_both_ways() {
|
||||
}
|
||||
|
||||
const DAY_MS_FOR_TESTS: u64 = 86_400_000;
|
||||
|
||||
#[test]
|
||||
fn the_daily_series_fills_empty_days_and_keeps_the_most_recent() {
|
||||
let day = DAY_MS_FOR_TESTS;
|
||||
let e = entries(&[
|
||||
("a", T0, "p", "m", Some(Outcome::Done), Some(10_000)),
|
||||
("b", T0 + 3 * day, "p", "m", Some(Outcome::Done), Some(5_000)),
|
||||
("c", T0 + 3 * day + 1, "p", "m", None, None),
|
||||
]);
|
||||
let refs: Vec<&HistoryEntry> = e.iter().collect();
|
||||
let all = daily(&refs, 0, 31);
|
||||
let shape: Vec<(String, usize)> = all.iter().map(|(d, t)| (d.to_string(), t.jobs)).collect();
|
||||
assert_eq!(shape, [("2025-10-09".to_owned(), 1), ("2025-10-10".to_owned(), 0), ("2025-10-11".to_owned(), 0), ("2025-10-12".to_owned(), 2)]);
|
||||
let recent = daily(&refs, 0, 2);
|
||||
let shape: Vec<String> = recent.iter().map(|(d, _)| d.to_string()).collect();
|
||||
assert_eq!(shape, ["2025-10-11", "2025-10-12"]);
|
||||
assert!(daily(&[], 0, 31).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn models_and_apps_group_busiest_first_and_average_only_successful_timed_jobs() {
|
||||
let e = entries(&[
|
||||
("a", T0, "photocraft", "flux", Some(Outcome::Done), Some(50_000)),
|
||||
("b", T0 + 10, "photocraft", "flux", Some(Outcome::Done), Some(50_000)),
|
||||
("c", T0 + 20, "wordcraft", "gpt", Some(Outcome::Done), Some(1_000)),
|
||||
("d", T0 + 30, "wordcraft", "gpt", Some(Outcome::Failed { kind: ErrorKind::Network }), None),
|
||||
("e", T0 + 40, "wordcraft", "gpt", None, None),
|
||||
]);
|
||||
let refs: Vec<&HistoryEntry> = e.iter().collect();
|
||||
let models = by_model(&refs);
|
||||
assert_eq!(models.iter().map(|(k, t)| (k.as_str(), t.jobs)).collect::<Vec<_>>(), [("gpt", 3), ("flux", 2)]);
|
||||
let apps = by_app(&refs);
|
||||
assert_eq!(apps[0].0, "wordcraft");
|
||||
// Each finished job took two seconds in the fixture; the failed and unfinished ones do not count.
|
||||
assert_eq!(models[0].1.average_ms(), Some(2_000));
|
||||
assert_eq!(models[0].1.timed, 1);
|
||||
assert_eq!(Totals::default().average_ms(), None);
|
||||
}
|
||||
@@ -1,114 +0,0 @@
|
||||
use super::*;
|
||||
|
||||
fn start(run: &str, at_ms: u64) -> StartRecord {
|
||||
StartRecord {
|
||||
v: HISTORY_SCHEMA,
|
||||
run: run.into(),
|
||||
at_ms,
|
||||
app: "photocraft".into(),
|
||||
role_id: "fill".into(),
|
||||
role_label: "Generative Fill".into(),
|
||||
capability: "image.inpaint".into(),
|
||||
connection: "conn1".into(),
|
||||
connection_label: "Hosted".into(),
|
||||
model: "m1".into(),
|
||||
locality: Locality::Remote,
|
||||
destination: "https://api.example.com".into(),
|
||||
sent: Vec::new(),
|
||||
params: vec!["seed".into()],
|
||||
provider_job: Some("gen-9".into()),
|
||||
estimate: None,
|
||||
prompt: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn end(run: &str, at_ms: u64, outcome: Outcome) -> EndRecord {
|
||||
EndRecord { v: HISTORY_SCHEMA, run: run.into(), at_ms, outcome, usage: None }
|
||||
}
|
||||
|
||||
fn s(r: StartRecord) -> HistoryRecord {
|
||||
HistoryRecord::Start(r)
|
||||
}
|
||||
|
||||
fn e(r: EndRecord) -> HistoryRecord {
|
||||
HistoryRecord::End(r)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_round_trips_and_leaves_out_what_is_absent() {
|
||||
let line = serde_json::to_string(&s(start("a", 5))).unwrap();
|
||||
assert!(!line.contains('\n'));
|
||||
assert!(!line.contains("prompt"), "{line}");
|
||||
assert!(!line.contains("estimate"), "{line}");
|
||||
assert_eq!(serde_json::from_str::<HistoryRecord>(&line).unwrap(), s(start("a", 5)));
|
||||
let failed = e(end("a", 9, Outcome::Failed { kind: ErrorKind::Quota }));
|
||||
let line = serde_json::to_string(&failed).unwrap();
|
||||
assert!(line.contains("\"phase\":\"end\""), "{line}");
|
||||
assert_eq!(serde_json::from_str::<HistoryRecord>(&line).unwrap(), failed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_phase_does_not_parse_so_readers_can_skip_it() {
|
||||
assert!(serde_json::from_str::<HistoryRecord>(r#"{"phase":"pause","run":"a"}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_and_end_join_by_run_and_the_list_is_newest_first() {
|
||||
let log = merge(vec![s(start("old", 10)), s(start("new", 30)), e(end("new", 45, Outcome::Done)), e(end("old", 12, Outcome::Cancelled))], 0);
|
||||
let runs: Vec<_> = log.entries.iter().map(|x| x.start.run.as_str()).collect();
|
||||
assert_eq!(runs, ["new", "old"]);
|
||||
assert_eq!(log.entries[0].duration_ms(), Some(15));
|
||||
assert_eq!(log.entries[1].outcome(), Some(&Outcome::Cancelled));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_start_with_no_end_stays_unfinished() {
|
||||
let log = merge(vec![s(start("a", 10))], 0);
|
||||
assert_eq!(log.entries.len(), 1);
|
||||
assert_eq!(log.entries[0].outcome(), None);
|
||||
assert_eq!(log.entries[0].duration_ms(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_end_whose_start_was_rotated_away_is_dropped() {
|
||||
let log = merge(vec![e(end("gone", 5, Outcome::Done))], 2);
|
||||
assert!(log.entries.is_empty());
|
||||
assert_eq!(log.skipped, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_first_end_wins_and_a_repeated_start_is_ignored() {
|
||||
let log = merge(vec![s(start("a", 10)), s(start("a", 99)), e(end("a", 20, Outcome::Done)), e(end("a", 30, Outcome::Cancelled))], 0);
|
||||
assert_eq!(log.entries.len(), 1);
|
||||
assert_eq!(log.entries[0].start.at_ms, 10);
|
||||
assert_eq!(log.entries[0].outcome(), Some(&Outcome::Done));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_clock_that_went_backwards_gives_no_duration() {
|
||||
let log = merge(vec![s(start("a", 50)), e(end("a", 40, Outcome::Done))], 0);
|
||||
assert_eq!(log.entries[0].duration_ms(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cost_is_only_what_the_provider_reported() {
|
||||
let mut finished = end("a", 20, Outcome::Done);
|
||||
let mut log = merge(vec![s(start("a", 10)), e(finished.clone())], 0);
|
||||
assert_eq!(log.entries[0].reported_cost(), None);
|
||||
|
||||
finished.usage = Some(Usage { cost_micros: Some(40_000), currency: None, ..Usage::default() });
|
||||
log = merge(vec![s(start("a", 10)), e(finished.clone())], 0);
|
||||
assert_eq!(log.entries[0].reported_cost(), None, "no currency, no cost");
|
||||
|
||||
finished.usage = Some(Usage { cost_micros: Some(40_000), currency: Some("USD".into()), ..Usage::default() });
|
||||
log = merge(vec![s(start("a", 10)), e(finished)], 0);
|
||||
assert_eq!(log.entries[0].reported_cost(), Some((40_000, "USD")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn prompts_are_clipped_on_a_character_boundary() {
|
||||
let long = "é".repeat(MAX_PROMPT_CHARS + 50);
|
||||
let clipped = clip_prompt(&long);
|
||||
assert_eq!(clipped.chars().count(), MAX_PROMPT_CHARS);
|
||||
assert_eq!(clip_prompt("short"), "short");
|
||||
}
|
||||
+16
-41
@@ -13,9 +13,18 @@ pub const MAX_ID_LEN: usize = 128;
|
||||
/// Why a string was refused as an identifier.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum IdError {
|
||||
/// The value is empty.
|
||||
Empty,
|
||||
TooLong { len: usize, max: usize },
|
||||
/// The value is longer than the limit.
|
||||
TooLong {
|
||||
/// Length of the value in bytes.
|
||||
len: usize,
|
||||
/// Longest allowed length in bytes.
|
||||
max: usize,
|
||||
},
|
||||
/// The value contains a character outside the allowed set.
|
||||
BadChar(char),
|
||||
/// The value is the wrong shape. The text says how.
|
||||
Malformed(&'static str),
|
||||
}
|
||||
|
||||
@@ -71,6 +80,7 @@ macro_rules! validated_string {
|
||||
Ok(Self(value))
|
||||
}
|
||||
|
||||
/// The wrapped string.
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.0
|
||||
}
|
||||
@@ -118,12 +128,16 @@ macro_rules! open_enum {
|
||||
$(#[$m])*
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum $name {
|
||||
$($var,)+
|
||||
$(
|
||||
#[allow(missing_docs)]
|
||||
$var,
|
||||
)+
|
||||
/// A well-formed value this library does not know by name.
|
||||
Other(String),
|
||||
}
|
||||
|
||||
impl $name {
|
||||
/// The well-known name, or the text of `Other`.
|
||||
pub fn as_str(&self) -> &str {
|
||||
match self {
|
||||
$(Self::$var => $text,)+
|
||||
@@ -197,42 +211,3 @@ validated_string!(
|
||||
SecretRef,
|
||||
validate_id
|
||||
);
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ids_accept_normal_values() {
|
||||
assert!(ModelId::new("black-forest-labs/flux-1.1-pro").is_ok());
|
||||
assert!(ConnectionId::new("conn_01hx").is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_reject_bad_values_without_panicking() {
|
||||
assert_eq!(ModelId::new(""), Err(IdError::Empty));
|
||||
assert_eq!(ModelId::new("a b"), Err(IdError::BadChar(' ')));
|
||||
assert_eq!(ModelId::new("a\0b"), Err(IdError::BadChar('\0')));
|
||||
assert!(matches!(ModelId::new("x".repeat(MAX_ID_LEN + 1)), Err(IdError::TooLong { .. })));
|
||||
assert!(ModelId::new("\u{202e}rtl").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_reject_dots() {
|
||||
assert!(validate_token("image").is_ok());
|
||||
assert_eq!(validate_token("a.b"), Err(IdError::BadChar('.')));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deserialize_validates() {
|
||||
let ok: Result<ModelId, _> = serde_json::from_str("\"gpt-image-1\"");
|
||||
assert!(ok.is_ok());
|
||||
let bad: Result<ModelId, _> = serde_json::from_str("\"has space\"");
|
||||
assert!(bad.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn debug_shows_type_and_value() {
|
||||
assert_eq!(format!("{:?}", AppId::new("photocraft").unwrap()), "AppId(\"photocraft\")");
|
||||
}
|
||||
}
|
||||
+36
-59
@@ -15,19 +15,26 @@ use crate::payload::Payload;
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "state", rename_all = "snake_case")]
|
||||
pub enum JobState {
|
||||
/// Accepted by the provider but not started.
|
||||
Queued,
|
||||
/// `percent` is 0 to 100 when the provider reports it.
|
||||
Running {
|
||||
/// Progress from 0 to 100, when the provider reports it.
|
||||
percent: Option<u8>,
|
||||
},
|
||||
/// Finished with outputs. Final.
|
||||
Succeeded,
|
||||
/// Ended with an error. Final.
|
||||
Failed {
|
||||
/// Why the job failed.
|
||||
error: AiError,
|
||||
},
|
||||
/// Stopped on request. Final.
|
||||
Cancelled,
|
||||
}
|
||||
|
||||
impl JobState {
|
||||
/// True for succeeded, failed and cancelled, the states that never change.
|
||||
pub fn is_terminal(&self) -> bool {
|
||||
matches!(self, Self::Succeeded | Self::Failed { .. } | Self::Cancelled)
|
||||
}
|
||||
@@ -53,6 +60,7 @@ impl JobState {
|
||||
/// A finished result.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Output {
|
||||
/// The result data.
|
||||
pub payload: Payload,
|
||||
/// Optional note such as "variation 2". Structured output arrives as an `application/json`
|
||||
/// inline payload.
|
||||
@@ -64,41 +72,66 @@ pub struct Output {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Event {
|
||||
TextDelta { text: String },
|
||||
ToolCall { name: String, arguments: String },
|
||||
/// A piece of generated text, to append to what came before.
|
||||
TextDelta {
|
||||
/// The new text.
|
||||
text: String,
|
||||
},
|
||||
/// The model asked to call a tool.
|
||||
ToolCall {
|
||||
/// Name of the tool.
|
||||
name: String,
|
||||
/// The arguments, as a JSON string.
|
||||
arguments: String,
|
||||
},
|
||||
/// A finished output.
|
||||
Output(Output),
|
||||
Notice { message: String },
|
||||
/// A message from the provider for the user, not part of the result.
|
||||
Notice {
|
||||
/// The message text.
|
||||
message: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// What a provider charged or counted. All fields optional: many providers report none.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Usage {
|
||||
/// Input the provider counted, in its own units (for example tokens).
|
||||
pub input_units: Option<u64>,
|
||||
/// Output the provider counted, in its own units.
|
||||
pub output_units: Option<u64>,
|
||||
/// Millionths of `currency`, so no floating point money.
|
||||
pub cost_micros: Option<u64>,
|
||||
/// Currency code for `cost_micros`, such as `USD`.
|
||||
pub currency: Option<String>,
|
||||
}
|
||||
|
||||
/// A price estimate shown before a job runs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CostEstimate {
|
||||
/// Estimated price in millionths of `currency`.
|
||||
pub micros: u64,
|
||||
/// Currency code, such as `USD`.
|
||||
pub currency: String,
|
||||
/// How the job will be billed.
|
||||
pub billing: Billing,
|
||||
}
|
||||
|
||||
/// One poll's answer.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct JobSnapshot {
|
||||
/// Where the job is now.
|
||||
pub state: JobState,
|
||||
/// Events since the previous poll, oldest first.
|
||||
#[serde(default)]
|
||||
pub events: Vec<Event>,
|
||||
/// What the provider reported charging, when it did.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub usage: Option<Usage>,
|
||||
}
|
||||
|
||||
impl JobSnapshot {
|
||||
/// A snapshot with the given state and no events or usage.
|
||||
pub fn new(state: JobState) -> Self {
|
||||
Self { state, events: Vec::new(), usage: None }
|
||||
}
|
||||
@@ -111,59 +144,3 @@ impl JobSnapshot {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use JobState::{Cancelled, Failed, Queued, Running, Succeeded};
|
||||
|
||||
fn failed() -> JobState {
|
||||
Failed { error: AiError::new(crate::error::ErrorKind::Provider, "boom") }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forward_moves_are_legal() {
|
||||
assert!(Queued.can_become(&Running { percent: None }));
|
||||
assert!(Running { percent: Some(10) }.can_become(&Running { percent: Some(10) }));
|
||||
assert!(Running { percent: Some(10) }.can_become(&Running { percent: Some(80) }));
|
||||
assert!(Running { percent: Some(80) }.can_become(&Succeeded));
|
||||
assert!(Running { percent: None }.can_become(&failed()));
|
||||
assert!(Queued.can_become(&Succeeded));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn progress_cannot_go_backwards() {
|
||||
assert!(!Running { percent: Some(50) }.can_become(&Running { percent: Some(40) }));
|
||||
assert!(!Running { percent: Some(50) }.can_become(&Running { percent: None }));
|
||||
assert!(!Running { percent: Some(5) }.can_become(&Queued));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_states_are_final() {
|
||||
for t in [Succeeded, Cancelled, failed()] {
|
||||
assert!(t.is_terminal());
|
||||
assert!(t.can_become(&t.clone()));
|
||||
assert!(!t.can_become(&Running { percent: None }));
|
||||
assert!(!t.can_become(&Queued));
|
||||
}
|
||||
assert!(!Succeeded.can_become(&Cancelled));
|
||||
assert!(!Cancelled.can_become(&Succeeded));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_collects_outputs_only() {
|
||||
let mut s = JobSnapshot::new(Succeeded);
|
||||
s.events.push(Event::TextDelta { text: "hi".into() });
|
||||
s.events.push(Event::Output(Output { payload: Payload::text("done"), label: None }));
|
||||
assert_eq!(s.outputs().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_json_round_trip() {
|
||||
let mut s = JobSnapshot::new(Running { percent: Some(40) });
|
||||
s.events.push(Event::ToolCall { name: "lookup".into(), arguments: "{}".into() });
|
||||
s.usage = Some(Usage { cost_micros: Some(1200), currency: Some("USD".into()), ..Usage::default() });
|
||||
let json = serde_json::to_string(&s).unwrap();
|
||||
assert_eq!(serde_json::from_str::<JobSnapshot>(&json).unwrap(), s);
|
||||
}
|
||||
}
|
||||
@@ -68,3 +68,10 @@ pub use request::Request;
|
||||
pub use role::{Binding, Role};
|
||||
pub use secret::SecretString;
|
||||
pub use store::StoreFile;
|
||||
|
||||
#[cfg(test)]
|
||||
extern crate self as craft_ai_core;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/main.rs"]
|
||||
mod integration;
|
||||
@@ -18,7 +18,9 @@ use crate::request::Request;
|
||||
/// How a mock job ends.
|
||||
#[derive(Clone, Debug)]
|
||||
pub enum Outcome {
|
||||
/// Finish successfully with these outputs.
|
||||
Succeed(Vec<Output>),
|
||||
/// Finish in the `Failed` state with this error.
|
||||
Fail(AiError),
|
||||
}
|
||||
|
||||
@@ -29,6 +31,7 @@ pub struct Script {
|
||||
pub running_polls: u32,
|
||||
/// One text delta is emitted per poll until these run out.
|
||||
pub text_chunks: Vec<String>,
|
||||
/// How the job ends once the running polls and text chunks are done.
|
||||
pub outcome: Outcome,
|
||||
}
|
||||
|
||||
@@ -61,6 +64,7 @@ pub struct MockProvider {
|
||||
}
|
||||
|
||||
impl MockProvider {
|
||||
/// Builds a provider that offers `models` and runs every job by `script`.
|
||||
pub fn new(models: Vec<ModelInfo>, script: Script) -> Self {
|
||||
Self { models, script, limits: Limits::default(), state: Mutex::new(State::default()) }
|
||||
}
|
||||
|
||||
+17
-65
@@ -27,10 +27,13 @@ open_enum!(
|
||||
/// Optional abilities beyond the basic request and result.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Features {
|
||||
/// The model can stream text deltas as it generates.
|
||||
#[serde(default)]
|
||||
pub streaming: bool,
|
||||
/// The model can call tools.
|
||||
#[serde(default)]
|
||||
pub tools: bool,
|
||||
/// The model can return JSON that follows a schema.
|
||||
#[serde(default)]
|
||||
pub structured_output: bool,
|
||||
}
|
||||
@@ -38,6 +41,7 @@ pub struct Features {
|
||||
/// What one model can do for one capability.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CapabilitySpec {
|
||||
/// The capability this spec describes.
|
||||
pub capability: CapabilityId,
|
||||
/// Inputs the model accepts, with the most of each. An input role not listed is unsupported.
|
||||
pub accepts: BTreeMap<InputRole, u32>,
|
||||
@@ -47,6 +51,7 @@ pub struct CapabilitySpec {
|
||||
/// Most outputs one request can return (variations count here).
|
||||
#[serde(default = "one")]
|
||||
pub max_outputs: u32,
|
||||
/// Optional abilities the model has for this capability.
|
||||
#[serde(default)]
|
||||
pub features: Features,
|
||||
}
|
||||
@@ -56,16 +61,19 @@ fn one() -> u32 {
|
||||
}
|
||||
|
||||
impl CapabilitySpec {
|
||||
/// A spec that accepts the given inputs (one of each) and requires none.
|
||||
/// A spec for `capability` that accepts no inputs, requires none and returns one output; add
|
||||
/// inputs with [`accepting`](Self::accepting).
|
||||
pub fn new(capability: CapabilityId) -> Self {
|
||||
Self { capability, accepts: BTreeMap::new(), requires: Vec::new(), max_outputs: 1, features: Features::default() }
|
||||
}
|
||||
|
||||
/// Accepts up to `max` inputs of `role`.
|
||||
pub fn accepting(mut self, role: InputRole, max: u32) -> Self {
|
||||
self.accepts.insert(role, max);
|
||||
self
|
||||
}
|
||||
|
||||
/// Requires an input of `role`. Adding the same role twice has no effect.
|
||||
pub fn requiring(mut self, role: InputRole) -> Self {
|
||||
if !self.requires.contains(&role) {
|
||||
self.requires.push(role);
|
||||
@@ -73,11 +81,13 @@ impl CapabilitySpec {
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the most outputs one request can return.
|
||||
pub fn max_outputs(mut self, n: u32) -> Self {
|
||||
self.max_outputs = n;
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the optional abilities.
|
||||
pub fn with_features(mut self, features: Features) -> Self {
|
||||
self.features = features;
|
||||
self
|
||||
@@ -102,8 +112,11 @@ pub struct Pricing {
|
||||
/// One model as offered by one connection.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ModelInfo {
|
||||
#[allow(missing_docs)]
|
||||
pub id: ModelId,
|
||||
/// Name shown to the user.
|
||||
pub label: String,
|
||||
/// What the model can do, one spec per capability.
|
||||
#[serde(default)]
|
||||
pub capabilities: Vec<CapabilitySpec>,
|
||||
/// Reported by the provider where it can be (OpenRouter does). Absent in stores written before
|
||||
@@ -123,80 +136,19 @@ pub struct ModelInfo {
|
||||
}
|
||||
|
||||
impl ModelInfo {
|
||||
/// Builds a model with no capabilities. Add them with [`ModelInfo::with`].
|
||||
pub fn new(id: ModelId, label: impl Into<String>) -> Self {
|
||||
Self { id, label: label.into(), capabilities: Vec::new(), pricing: None, released: None, tags: Vec::new(), local_file: None }
|
||||
}
|
||||
|
||||
/// Adds a capability spec.
|
||||
pub fn with(mut self, spec: CapabilitySpec) -> Self {
|
||||
self.capabilities.push(spec);
|
||||
self
|
||||
}
|
||||
|
||||
/// The spec for `capability`, if the model supports it.
|
||||
pub fn spec_for(&self, capability: &CapabilityId) -> Option<&CapabilitySpec> {
|
||||
self.capabilities.iter().find(|s| &s.capability == capability)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn cap(s: &str) -> CapabilityId {
|
||||
CapabilityId::parse(s).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_store_written_before_pricing_existed_still_loads_and_leaves_it_out_when_absent() {
|
||||
let old = r#"{"id":"gpt-4o","label":"gpt-4o","capabilities":[]}"#;
|
||||
let info: ModelInfo = serde_json::from_str(old).unwrap();
|
||||
assert_eq!((info.pricing.clone(), info.released, info.tags.clone()), (None, None, Vec::new()));
|
||||
let again = serde_json::to_string(&info).unwrap();
|
||||
assert!(!again.contains("pricing") && !again.contains("released") && !again.contains("tags"), "{again}");
|
||||
let priced = ModelInfo {
|
||||
pricing: Some(Pricing { per_image_micros: Some(40_000), ..Pricing::default() }),
|
||||
released: Some(1_760_000_000),
|
||||
tags: vec!["recommended".into()],
|
||||
..info
|
||||
};
|
||||
let back: ModelInfo = serde_json::from_str(&serde_json::to_string(&priced).unwrap()).unwrap();
|
||||
assert_eq!(back, priced);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_roles_round_trip_including_custom() {
|
||||
for text in ["mask", "reference", "depth-map"] {
|
||||
let r = InputRole::parse(text).unwrap();
|
||||
assert_eq!(r.as_str(), text);
|
||||
assert_eq!(serde_json::from_str::<InputRole>(&serde_json::to_string(&r).unwrap()).unwrap(), r);
|
||||
}
|
||||
assert!(InputRole::parse("bad role").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spec_round_trips_with_map_keys() {
|
||||
let spec = CapabilitySpec::new(cap("image.inpaint"))
|
||||
.accepting(InputRole::Source, 1)
|
||||
.accepting(InputRole::Mask, 1)
|
||||
.accepting(InputRole::Reference, 3)
|
||||
.requiring(InputRole::Source)
|
||||
.max_outputs(4);
|
||||
let json = serde_json::to_string(&spec).unwrap();
|
||||
assert!(json.contains("\"reference\":3"));
|
||||
assert_eq!(serde_json::from_str::<CapabilitySpec>(&json).unwrap(), spec);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_fields_take_defaults() {
|
||||
let spec: CapabilitySpec = serde_json::from_str(r#"{"capability":"text.complete","accepts":{"prompt":1}}"#).unwrap();
|
||||
assert_eq!(spec.max_outputs, 1);
|
||||
assert!(!spec.features.streaming);
|
||||
assert!(spec.requires.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_finds_its_spec() {
|
||||
let m = ModelInfo::new(ModelId::new("m1").unwrap(), "M1").with(CapabilitySpec::new(cap("image.generate")));
|
||||
assert!(m.spec_for(&cap("image.generate")).is_some());
|
||||
assert!(m.spec_for(&cap("image.inpaint")).is_none());
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,9 @@ const MAX_URI_LEN: usize = 4096;
|
||||
/// Size limits applied to payloads in a request.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Limits {
|
||||
/// Largest inline binary payload, in bytes.
|
||||
pub max_inline_bytes: u64,
|
||||
/// Largest text payload, in bytes.
|
||||
pub max_text_bytes: usize,
|
||||
}
|
||||
|
||||
@@ -52,6 +54,7 @@ validated_string!(
|
||||
);
|
||||
|
||||
impl MediaType {
|
||||
/// The coarse kind for this media type. Unknown types are `Other`; `application/json` counts as text.
|
||||
pub fn kind(&self) -> PayloadKind {
|
||||
let s = self.as_str();
|
||||
if s.starts_with("image/") {
|
||||
@@ -75,19 +78,28 @@ impl MediaType {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PayloadKind {
|
||||
#[allow(missing_docs)]
|
||||
Text,
|
||||
#[allow(missing_docs)]
|
||||
Image,
|
||||
#[allow(missing_docs)]
|
||||
Video,
|
||||
#[allow(missing_docs)]
|
||||
Audio,
|
||||
/// A document such as a PDF.
|
||||
Document,
|
||||
/// Any other media type.
|
||||
Other,
|
||||
}
|
||||
|
||||
/// A reference to data that stays where it is until a provider adapter streams it.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PayloadHandle {
|
||||
/// Where the data lives, such as a file path or URL. Never empty and has no control characters.
|
||||
pub uri: String,
|
||||
/// What the data is.
|
||||
pub media_type: MediaType,
|
||||
/// Size in bytes, when known.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub size_bytes: Option<u64>,
|
||||
}
|
||||
@@ -96,27 +108,36 @@ pub struct PayloadHandle {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum Payload {
|
||||
/// Plain text.
|
||||
Text {
|
||||
/// The text.
|
||||
text: String,
|
||||
},
|
||||
/// Binary data carried in the payload, serialized as base64.
|
||||
Inline {
|
||||
/// What the data is.
|
||||
media_type: MediaType,
|
||||
/// The raw bytes.
|
||||
#[serde(with = "base64_bytes")]
|
||||
data: Vec<u8>,
|
||||
},
|
||||
/// Data kept where it is, referenced by a handle.
|
||||
Handle(PayloadHandle),
|
||||
}
|
||||
|
||||
impl Payload {
|
||||
/// A text payload.
|
||||
pub fn text(text: impl Into<String>) -> Self {
|
||||
Self::Text { text: text.into() }
|
||||
}
|
||||
|
||||
/// An inline payload. Fails when `media_type` is not a valid media type.
|
||||
pub fn inline(media_type: &str, data: Vec<u8>) -> Result<Self, AiError> {
|
||||
let media_type = MediaType::new(media_type).map_err(|e| AiError::invalid(format!("media type: {e}")))?;
|
||||
Ok(Self::Inline { media_type, data })
|
||||
}
|
||||
|
||||
/// A handle payload. Fails on an empty, over-long (4096 bytes) or control-character URI, or an invalid media type.
|
||||
pub fn handle(uri: &str, media_type: &str, size_bytes: Option<u64>) -> Result<Self, AiError> {
|
||||
if uri.is_empty() || uri.len() > MAX_URI_LEN || uri.chars().any(char::is_control) {
|
||||
return Err(AiError::invalid("payload uri is empty, too long, or has control characters"));
|
||||
@@ -125,6 +146,7 @@ impl Payload {
|
||||
Ok(Self::Handle(PayloadHandle { uri: uri.to_owned(), media_type, size_bytes }))
|
||||
}
|
||||
|
||||
/// The coarse kind: text for `Text`, otherwise from the media type.
|
||||
pub fn kind(&self) -> PayloadKind {
|
||||
match self {
|
||||
Self::Text { .. } => PayloadKind::Text,
|
||||
@@ -224,79 +246,3 @@ mod base64_bytes {
|
||||
super::base64_decode(&text).ok_or_else(|| serde::de::Error::custom("invalid base64"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn base64_matches_known_vectors() {
|
||||
for (raw, enc) in [("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("foobar", "Zm9vYmFy")] {
|
||||
assert_eq!(base64_encode(raw.as_bytes()), enc);
|
||||
assert_eq!(base64_decode(enc).unwrap(), raw.as_bytes());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_round_trips_all_byte_values() {
|
||||
let data: Vec<u8> = (0..=255u8).collect();
|
||||
assert_eq!(base64_decode(&base64_encode(&data)).unwrap(), data);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn base64_rejects_malformed() {
|
||||
for bad in ["Zg=", "Z", "Zm9v!", "=Zm9", "Zg==Zg==", "Zm=v", "Z===", "Zm9v\n"] {
|
||||
assert!(base64_decode(bad).is_none(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn media_type_validation() {
|
||||
assert!(MediaType::new("image/png").is_ok());
|
||||
assert!(MediaType::new("application/vnd.api+json").is_ok());
|
||||
for bad in ["", "png", "image/", "/png", "Image/PNG", "image/png/x", "image/p ng"] {
|
||||
assert!(MediaType::new(bad).is_err(), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kinds_follow_media_type() {
|
||||
assert_eq!(Payload::inline("image/png", vec![1]).unwrap().kind(), PayloadKind::Image);
|
||||
assert_eq!(Payload::inline("application/pdf", vec![1]).unwrap().kind(), PayloadKind::Document);
|
||||
assert_eq!(Payload::text("hi").kind(), PayloadKind::Text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inline_over_limit_is_refused_with_a_hint() {
|
||||
let limits = Limits { max_inline_bytes: 4, max_text_bytes: 4 };
|
||||
let err = Payload::inline("image/png", vec![0; 5]).unwrap().check(&limits).unwrap_err();
|
||||
assert!(err.message.contains("handle"));
|
||||
assert!(Payload::text("12345").check(&limits).is_err());
|
||||
assert!(Payload::text("1234").check(&limits).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_skip_the_inline_limit() {
|
||||
let limits = Limits { max_inline_bytes: 4, max_text_bytes: 4 };
|
||||
let h = Payload::handle("file:///big.mov", "video/quicktime", Some(10_000_000_000)).unwrap();
|
||||
assert!(h.check(&limits).is_ok());
|
||||
assert_eq!(h.size_hint(), Some(10_000_000_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handle_rejects_bad_uris() {
|
||||
assert!(Payload::handle("", "video/mp4", None).is_err());
|
||||
assert!(Payload::handle("file:///a\nb", "video/mp4", None).is_err());
|
||||
assert!(Payload::handle(&"x".repeat(MAX_URI_LEN + 1), "video/mp4", None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_round_trip() {
|
||||
let p = Payload::inline("image/png", vec![0, 1, 2, 250, 255]).unwrap();
|
||||
let json = serde_json::to_string(&p).unwrap();
|
||||
assert!(json.contains("\"type\":\"inline\""));
|
||||
assert_eq!(serde_json::from_str::<Payload>(&json).unwrap(), p);
|
||||
let bad = r#"{"type":"inline","media_type":"image/png","data":"!!"}"#;
|
||||
assert!(serde_json::from_str::<Payload>(bad).is_err());
|
||||
}
|
||||
}
|
||||
@@ -27,10 +27,15 @@ pub const MAX_CATALOG_BYTES: usize = 256 * 1024;
|
||||
pub enum Pick {
|
||||
/// The one we would choose: a balance of quality, speed and price.
|
||||
Recommended,
|
||||
/// The model with the best output quality, as judged by whoever keeps the catalog.
|
||||
BestResult,
|
||||
/// The model with the lowest reported price.
|
||||
LowestCost,
|
||||
/// The model judged fastest, as kept in the catalog.
|
||||
Fastest,
|
||||
/// The most recently released model.
|
||||
Newest,
|
||||
/// The model judged most used, as kept in the catalog.
|
||||
MostPopular,
|
||||
}
|
||||
|
||||
@@ -43,6 +48,7 @@ impl Pick {
|
||||
!matches!(self, Pick::LowestCost | Pick::Newest)
|
||||
}
|
||||
|
||||
/// The stable text form, used in the catalog file.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Pick::Recommended => "recommended",
|
||||
@@ -58,19 +64,23 @@ impl Pick {
|
||||
/// One curated pick: for this job, on this kind of connection, this model earns this tag.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct CatalogEntry {
|
||||
/// The capability the pick is for, as `<modality>.<task>`.
|
||||
pub capability: String,
|
||||
/// The tag it earns, as [`Pick::key`].
|
||||
pub pick: String,
|
||||
/// The connection's provider key, such as `openrouter`.
|
||||
pub provider: String,
|
||||
/// The model id.
|
||||
pub model: String,
|
||||
}
|
||||
|
||||
/// The curated picks. Earlier entries for the same job and tag win.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Catalog {
|
||||
/// Catalog version. [`Catalog::over`] keeps the higher of the two.
|
||||
#[serde(default)]
|
||||
pub version: u32,
|
||||
/// The picks. Earlier entries win over later ones for the same job and tag.
|
||||
#[serde(default)]
|
||||
pub entries: Vec<CatalogEntry>,
|
||||
}
|
||||
@@ -78,7 +88,9 @@ pub struct Catalog {
|
||||
/// Why a catalog could not be used.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum CatalogError {
|
||||
/// The text is longer than [`MAX_CATALOG_BYTES`].
|
||||
TooLarge,
|
||||
/// The text is not valid catalog JSON. The string says why.
|
||||
Syntax(String),
|
||||
}
|
||||
|
||||
@@ -100,6 +112,7 @@ impl Catalog {
|
||||
Self::from_json(include_str!("catalog.json")).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Parses a catalog file. Fails when it is over [`MAX_CATALOG_BYTES`] or not valid JSON.
|
||||
pub fn from_json(text: &str) -> Result<Self, CatalogError> {
|
||||
if text.len() > MAX_CATALOG_BYTES {
|
||||
return Err(CatalogError::TooLarge);
|
||||
@@ -129,6 +142,7 @@ impl Catalog {
|
||||
pub struct Candidate<'a> {
|
||||
/// The connection's provider key.
|
||||
pub provider: &'a str,
|
||||
/// The model itself.
|
||||
pub model: &'a ModelInfo,
|
||||
/// Running it costs nothing (a local model, a free connection).
|
||||
pub free: bool,
|
||||
@@ -150,8 +164,11 @@ pub enum PickedBy {
|
||||
/// A pick that was earned, and by which candidate (an index into the candidates given).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Picked {
|
||||
/// The tag earned.
|
||||
pub pick: Pick,
|
||||
/// Index of the winning candidate in the slice that was ranked.
|
||||
pub candidate: usize,
|
||||
/// What earned it.
|
||||
pub by: PickedBy,
|
||||
}
|
||||
|
||||
@@ -211,6 +228,3 @@ fn newest(candidates: &[Candidate<'_>]) -> Option<(usize, PickedBy)> {
|
||||
})
|
||||
.map(|(i, at)| (i, PickedBy::Released(at)))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,166 +0,0 @@
|
||||
use super::*;
|
||||
use crate::ids::ModelId;
|
||||
|
||||
fn cap(s: &str) -> CapabilityId {
|
||||
CapabilityId::parse(s).unwrap()
|
||||
}
|
||||
|
||||
fn model(id: &str, price: Option<u64>, released: Option<u64>) -> ModelInfo {
|
||||
let mut m = ModelInfo::new(ModelId::new(id).unwrap(), id);
|
||||
m.pricing = price.map(|p| Pricing { per_image_micros: Some(p), ..Pricing::default() });
|
||||
m.released = released;
|
||||
m
|
||||
}
|
||||
|
||||
fn cands<'a>(models: &'a [(&'a str, ModelInfo, bool)]) -> Vec<Candidate<'a>> {
|
||||
models.iter().map(|(provider, model, free)| Candidate { provider, model, free: *free }).collect()
|
||||
}
|
||||
|
||||
fn catalog(entries: &[(&str, &str, &str, &str)]) -> Catalog {
|
||||
Catalog {
|
||||
version: 1,
|
||||
entries: entries
|
||||
.iter()
|
||||
.map(|(capability, pick, provider, model)| CatalogEntry {
|
||||
capability: (*capability).into(),
|
||||
pick: (*pick).into(),
|
||||
provider: (*provider).into(),
|
||||
model: (*model).into(),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn find(picks: &[Picked], pick: Pick) -> Option<&Picked> {
|
||||
picks.iter().find(|p| p.pick == pick)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_built_in_catalog_loads_and_starts_empty() {
|
||||
let c = Catalog::builtin();
|
||||
assert_eq!(c.version, 1);
|
||||
assert!(c.entries.is_empty(), "no curated pick is claimed until it is checked");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowest_cost_and_newest_are_worked_out_from_what_is_reported() {
|
||||
let models = [
|
||||
("or", model("a-pricey", Some(80_000), Some(300)), false),
|
||||
("or", model("b-cheap", Some(20_000), Some(100)), false),
|
||||
("or", model("c-new", Some(50_000), Some(900)), false),
|
||||
("or", model("d-unpriced", None, None), false),
|
||||
];
|
||||
let picks = choose(&cap("image.inpaint"), &cands(&models), &Catalog::default());
|
||||
let cheapest = find(&picks, Pick::LowestCost).unwrap();
|
||||
assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Price(20_000)));
|
||||
let newest = find(&picks, Pick::Newest).unwrap();
|
||||
assert_eq!((newest.candidate, &newest.by), (2, &PickedBy::Released(900)));
|
||||
assert!(find(&picks, Pick::Recommended).is_none(), "curated picks need the catalog");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_free_model_is_the_lowest_cost_and_unpriced_hosted_models_are_not_guessed_at() {
|
||||
let models = [
|
||||
("or", model("hosted", Some(1), None), false),
|
||||
("comfyui", model("local-sdxl", None, None), true),
|
||||
("or", model("unpriced", None, None), false),
|
||||
];
|
||||
let picks = choose(&cap("image.generate"), &cands(&models), &Catalog::default());
|
||||
let cheapest = find(&picks, Pick::LowestCost).unwrap();
|
||||
assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Free));
|
||||
|
||||
let only_unpriced = [("or", model("x", None, None), false)];
|
||||
let picks = choose(&cap("image.generate"), &cands(&only_unpriced), &Catalog::default());
|
||||
assert!(picks.is_empty(), "no data, no pick: {picks:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_models_compare_input_plus_output_per_million_tokens() {
|
||||
let text = |id: &str, i: u64, o: u64| {
|
||||
let mut m = ModelInfo::new(ModelId::new(id).unwrap(), id);
|
||||
m.pricing = Some(Pricing { input_micros_per_mtok: Some(i), output_micros_per_mtok: Some(o), per_image_micros: None });
|
||||
m
|
||||
};
|
||||
let models = [("or", text("big", 3_000_000, 15_000_000), false), ("or", text("small", 150_000, 600_000), false)];
|
||||
let picks = choose(&cap("text.complete"), &cands(&models), &Catalog::default());
|
||||
let cheapest = find(&picks, Pick::LowestCost).unwrap();
|
||||
assert_eq!((cheapest.candidate, &cheapest.by), (1, &PickedBy::Price(750_000)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curated_picks_come_from_the_catalog_and_only_when_the_connection_offers_the_model() {
|
||||
let models = [("or", model("flux-fill", None, None), false), ("bfl", model("flux-pro", None, None), false)];
|
||||
let c = catalog(&[
|
||||
// The first entry is for a model nobody offers, so it is skipped for the next.
|
||||
("image.inpaint", "recommended", "or", "not-offered"),
|
||||
("image.inpaint", "recommended", "bfl", "flux-pro"),
|
||||
("image.inpaint", "best_result", "or", "flux-fill"),
|
||||
// A model on the wrong provider does not match.
|
||||
("image.inpaint", "fastest", "bfl", "flux-fill"),
|
||||
// Another job's entry never leaks across.
|
||||
("text.complete", "most_popular", "or", "flux-fill"),
|
||||
]);
|
||||
let picks = choose(&cap("image.inpaint"), &cands(&models), &c);
|
||||
assert_eq!(find(&picks, Pick::Recommended).map(|p| p.candidate), Some(1));
|
||||
assert_eq!(find(&picks, Pick::BestResult).map(|p| p.candidate), Some(0));
|
||||
assert_eq!(find(&picks, Pick::Recommended).unwrap().by, PickedBy::Catalog);
|
||||
assert!(find(&picks, Pick::Fastest).is_none());
|
||||
assert!(find(&picks, Pick::MostPopular).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_model_that_disappears_stops_earning_its_pick() {
|
||||
let c = catalog(&[("image.inpaint", "recommended", "or", "flux-fill")]);
|
||||
let with = [("or", model("flux-fill", None, None), false)];
|
||||
assert!(find(&choose(&cap("image.inpaint"), &cands(&with), &c), Pick::Recommended).is_some());
|
||||
let without = [("or", model("something-else", None, None), false)];
|
||||
assert!(choose(&cap("image.inpaint"), &cands(&without), &c).is_empty());
|
||||
assert!(choose(&cap("image.inpaint"), &[], &c).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ties_go_to_the_id_that_sorts_first_so_the_answer_is_stable() {
|
||||
let models = [("or", model("zeta", Some(10_000), Some(500)), false), ("or", model("alpha", Some(10_000), Some(500)), false)];
|
||||
let picks = choose(&cap("image.generate"), &cands(&models), &Catalog::default());
|
||||
assert_eq!(find(&picks, Pick::LowestCost).unwrap().candidate, 1);
|
||||
assert_eq!(find(&picks, Pick::Newest).unwrap().candidate, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_catalog_file_loads_and_a_bad_or_oversize_one_is_refused() {
|
||||
let ok = r#"{"version":2,"entries":[{"capability":"image.inpaint","pick":"recommended","provider":"or","model":"m"},
|
||||
{"capability":"image.inpaint","pick":"a_pick_from_the_future","provider":"or","model":"m"}]}"#;
|
||||
let c = Catalog::from_json(ok).unwrap();
|
||||
assert_eq!((c.version, c.entries.len()), (2, 2));
|
||||
// The unknown tag is carried but can never match a known pick.
|
||||
let models = [("or", model("m", None, None), false)];
|
||||
let picks = choose(&cap("image.inpaint"), &cands(&models), &c);
|
||||
assert_eq!(picks.len(), 1);
|
||||
assert!(matches!(Catalog::from_json("not json"), Err(CatalogError::Syntax(_))));
|
||||
assert_eq!(Catalog::from_json(&" ".repeat(MAX_CATALOG_BYTES + 1)), Err(CatalogError::TooLarge));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn which_picks_are_judgements_and_which_are_computed() {
|
||||
let curated: Vec<_> = Pick::ALL.into_iter().filter(|p| p.is_curated()).collect();
|
||||
assert_eq!(curated, [Pick::Recommended, Pick::BestResult, Pick::Fastest, Pick::MostPopular]);
|
||||
let keys: std::collections::HashSet<_> = Pick::ALL.into_iter().map(Pick::key).collect();
|
||||
assert_eq!(keys.len(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_catalog_wins_over_the_built_in_one_and_the_rest_still_applies() {
|
||||
let newer = catalog(&[("text.complete", "recommended", "openrouter", "model-new")]);
|
||||
let built_in =
|
||||
catalog(&[("text.complete", "recommended", "openrouter", "model-old"), ("text.complete", "best_result", "openrouter", "model-best")]);
|
||||
let merged = newer.over(built_in);
|
||||
let models = [
|
||||
("openrouter", model("model-old", None, None), false),
|
||||
("openrouter", model("model-new", None, None), false),
|
||||
("openrouter", model("model-best", None, None), false),
|
||||
];
|
||||
let picks = choose(&cap("text.complete"), &cands(&models), &merged);
|
||||
let by = |p: Pick| picks.iter().find(|x| x.pick == p).map(|x| x.candidate);
|
||||
assert_eq!(by(Pick::Recommended), Some(1), "the newer entry wins");
|
||||
assert_eq!(by(Pick::BestResult), Some(2), "an entry only the old one had still counts");
|
||||
}
|
||||
@@ -21,14 +21,18 @@ pub const MAX_PARAMS_BYTES: usize = 64 * 1024;
|
||||
/// One typed input.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Input {
|
||||
/// What the input is for.
|
||||
pub role: InputRole,
|
||||
/// The data.
|
||||
pub payload: Payload,
|
||||
}
|
||||
|
||||
/// A unit of work for a model.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Request {
|
||||
/// What the model is asked to do.
|
||||
pub capability: CapabilityId,
|
||||
/// The typed inputs, in the order given.
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<Input>,
|
||||
/// Provider-neutral options such as `seed` or `size`. Capped by [`MAX_PARAMS_BYTES`].
|
||||
@@ -47,25 +51,30 @@ fn one() -> u32 {
|
||||
}
|
||||
|
||||
impl Request {
|
||||
/// A request for `capability` with no inputs or params, one output, and no streaming.
|
||||
pub fn new(capability: CapabilityId) -> Self {
|
||||
Self { capability, inputs: Vec::new(), params: Map::new(), outputs: 1, stream: false }
|
||||
}
|
||||
|
||||
/// Adds an input.
|
||||
pub fn with_input(mut self, role: InputRole, payload: Payload) -> Self {
|
||||
self.inputs.push(Input { role, payload });
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets a param, replacing any earlier value under `key`.
|
||||
pub fn with_param(mut self, key: &str, value: Value) -> Self {
|
||||
self.params.insert(key.to_owned(), value);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets how many results to return.
|
||||
pub fn with_outputs(mut self, n: u32) -> Self {
|
||||
self.outputs = n;
|
||||
self
|
||||
}
|
||||
|
||||
/// Asks for incremental results.
|
||||
pub fn streaming(mut self) -> Self {
|
||||
self.stream = true;
|
||||
self
|
||||
@@ -114,107 +123,3 @@ impl Request {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::error::ErrorKind;
|
||||
use crate::model::Features;
|
||||
|
||||
fn cap(s: &str) -> CapabilityId {
|
||||
CapabilityId::parse(s).unwrap()
|
||||
}
|
||||
|
||||
fn png() -> Payload {
|
||||
Payload::inline("image/png", vec![1, 2, 3]).unwrap()
|
||||
}
|
||||
|
||||
fn inpaint_spec() -> CapabilitySpec {
|
||||
CapabilitySpec::new(cap("image.inpaint"))
|
||||
.accepting(InputRole::Prompt, 1)
|
||||
.accepting(InputRole::Source, 1)
|
||||
.accepting(InputRole::Mask, 1)
|
||||
.accepting(InputRole::Reference, 1)
|
||||
.requiring(InputRole::Source)
|
||||
.requiring(InputRole::Mask)
|
||||
.max_outputs(3)
|
||||
}
|
||||
|
||||
fn good() -> Request {
|
||||
Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()).with_input(InputRole::Mask, png())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_well_formed_request_passes() {
|
||||
assert!(good().with_input(InputRole::Prompt, Payload::text("a cat")).validate(&inpaint_spec(), &Limits::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_input_is_a_clear_error() {
|
||||
let spec = CapabilitySpec::new(cap("image.generate")).accepting(InputRole::Prompt, 1);
|
||||
let req = Request::new(cap("image.generate")).with_input(InputRole::Mask, png());
|
||||
let err = req.validate(&spec, &Limits::default()).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unsupported);
|
||||
assert!(err.message.contains("mask"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn too_many_references_are_counted_separately_from_masks() {
|
||||
let req = good().with_input(InputRole::Reference, png()).with_input(InputRole::Reference, png());
|
||||
let err = req.validate(&inpaint_spec(), &Limits::default()).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::Unsupported);
|
||||
assert!(err.message.contains("reference"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_required_input_is_invalid() {
|
||||
let req = Request::new(cap("image.inpaint")).with_input(InputRole::Source, png());
|
||||
let err = req.validate(&inpaint_spec(), &Limits::default()).unwrap_err();
|
||||
assert_eq!(err.kind, ErrorKind::InvalidRequest);
|
||||
assert!(err.message.contains("mask"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_count_is_bounded() {
|
||||
assert!(good().with_outputs(3).validate(&inpaint_spec(), &Limits::default()).is_ok());
|
||||
assert!(good().with_outputs(4).validate(&inpaint_spec(), &Limits::default()).is_err());
|
||||
assert!(good().with_outputs(0).validate(&inpaint_spec(), &Limits::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_needs_the_feature() {
|
||||
let spec = CapabilitySpec::new(cap("text.complete")).accepting(InputRole::Prompt, 1);
|
||||
let req = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("hi")).streaming();
|
||||
assert_eq!(req.validate(&spec, &Limits::default()).unwrap_err().kind, ErrorKind::Unsupported);
|
||||
let spec = spec.with_features(Features { streaming: true, ..Features::default() });
|
||||
assert!(req.validate(&spec, &Limits::default()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capability_mismatch_is_invalid() {
|
||||
let req = Request::new(cap("image.generate"));
|
||||
assert_eq!(req.validate(&inpaint_spec(), &Limits::default()).unwrap_err().kind, ErrorKind::InvalidRequest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_inline_input_is_refused() {
|
||||
let limits = Limits { max_inline_bytes: 2, max_text_bytes: 10 };
|
||||
assert!(good().validate(&inpaint_spec(), &limits).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_params_are_refused() {
|
||||
let big = Value::String("x".repeat(MAX_PARAMS_BYTES + 1));
|
||||
assert!(good().with_param("blob", big).validate(&inpaint_spec(), &Limits::default()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_round_trips_and_defaults_apply() {
|
||||
let req = good().with_param("seed", Value::from(7)).with_outputs(2);
|
||||
let back: Request = serde_json::from_str(&serde_json::to_string(&req).unwrap()).unwrap();
|
||||
assert_eq!(req, back);
|
||||
let minimal: Request = serde_json::from_str(r#"{"capability":"image.generate"}"#).unwrap();
|
||||
assert_eq!(minimal.outputs, 1);
|
||||
assert!(!minimal.stream);
|
||||
}
|
||||
}
|
||||
+41
-71
@@ -19,8 +19,11 @@ use crate::model::{CapabilitySpec, InputRole, ModelInfo};
|
||||
/// A feature an app offers that needs a model.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Role {
|
||||
#[allow(missing_docs)]
|
||||
pub id: RoleId,
|
||||
/// Name shown to the user, such as "Generative Fill".
|
||||
pub label: String,
|
||||
/// The capability a model must offer to fill the role.
|
||||
pub capability: CapabilityId,
|
||||
/// Inputs this feature will send. A model must accept them and require no others.
|
||||
#[serde(default)]
|
||||
@@ -30,29 +33,63 @@ pub struct Role {
|
||||
/// The user's choice for one role.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Binding {
|
||||
/// The role being bound.
|
||||
pub role: RoleId,
|
||||
/// The chosen connection.
|
||||
pub connection: ConnectionId,
|
||||
/// The chosen model, offered by that connection.
|
||||
pub model: ModelId,
|
||||
}
|
||||
|
||||
/// A fully checked choice.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Resolved<'a> {
|
||||
/// The connection to send the job to.
|
||||
pub connection: &'a Connection,
|
||||
/// The model to run.
|
||||
pub model: &'a ModelInfo,
|
||||
/// The model's spec for the role's capability.
|
||||
pub spec: &'a CapabilitySpec,
|
||||
}
|
||||
|
||||
/// Why a role could not be resolved.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum ResolveError {
|
||||
/// No layer has a binding for the role.
|
||||
Unbound(RoleId),
|
||||
/// The bound connection is not in the list.
|
||||
ConnectionMissing(ConnectionId),
|
||||
/// The bound connection is switched off.
|
||||
ConnectionDisabled(ConnectionId),
|
||||
ModelMissing { connection: ConnectionId, model: ModelId },
|
||||
CapabilityMismatch { model: ModelId, capability: CapabilityId },
|
||||
InputUnsupported { model: ModelId, input: InputRole },
|
||||
InputRequired { model: ModelId, input: InputRole },
|
||||
/// The bound connection does not offer the bound model.
|
||||
ModelMissing {
|
||||
/// The bound connection.
|
||||
connection: ConnectionId,
|
||||
/// The bound model.
|
||||
model: ModelId,
|
||||
},
|
||||
/// The model has no spec for the role's capability.
|
||||
CapabilityMismatch {
|
||||
/// The bound model.
|
||||
model: ModelId,
|
||||
/// The capability the role needs.
|
||||
capability: CapabilityId,
|
||||
},
|
||||
/// The role sends an input the model does not accept.
|
||||
InputUnsupported {
|
||||
/// The bound model.
|
||||
model: ModelId,
|
||||
/// The input the model rejects.
|
||||
input: InputRole,
|
||||
},
|
||||
/// The model requires an input the role does not send.
|
||||
InputRequired {
|
||||
/// The bound model.
|
||||
model: ModelId,
|
||||
/// The input the role is missing.
|
||||
input: InputRole,
|
||||
},
|
||||
/// A tool role differs from the shared definition saved for its id.
|
||||
ToolMismatch(RoleId),
|
||||
}
|
||||
|
||||
@@ -157,21 +194,6 @@ mod tests {
|
||||
Binding { role: RoleId::new("generative-fill").unwrap(), connection: ConnectionId::new(conn).unwrap(), model: ModelId::new("m").unwrap() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolves_a_good_binding() {
|
||||
let conns = [conn("a", true)];
|
||||
let defaults = [bind("a")];
|
||||
assert!(resolve(&role(), &[&[], &defaults], &conns).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn app_override_beats_default() {
|
||||
let conns = [conn("a", true), conn("b", true)];
|
||||
let (over, def) = ([bind("b")], [bind("a")]);
|
||||
let r = resolve(&role(), &[&over, &def], &conns).unwrap();
|
||||
assert_eq!(r.connection.id.as_str(), "b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_broken_override_is_an_error_and_never_falls_through() {
|
||||
let conns = [conn("a", true)];
|
||||
@@ -179,56 +201,4 @@ mod tests {
|
||||
let err = resolve(&role(), &[&over, &def], &conns).unwrap_err();
|
||||
assert!(matches!(err, ResolveError::ConnectionMissing(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unbound_and_disabled() {
|
||||
let mut conns = [conn("a", true)];
|
||||
assert!(matches!(resolve(&role(), &[&[]], &conns), Err(ResolveError::Unbound(_))));
|
||||
conns[0].enabled = false;
|
||||
assert!(matches!(resolve(&role(), &[&[bind("a")]], &conns), Err(ResolveError::ConnectionDisabled(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_model_that_cannot_take_a_mask_does_not_resolve() {
|
||||
let conns = [conn("a", false)];
|
||||
let err = resolve(&role(), &[&[bind("a")]], &conns).unwrap_err();
|
||||
assert!(matches!(err, ResolveError::InputUnsupported { input: InputRole::Mask, .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_required_input_the_role_cannot_supply_has_a_specific_error() {
|
||||
let mut conns = [conn("a", true)];
|
||||
conns[0].models[0].capabilities[0].requires = vec![InputRole::Mask];
|
||||
let mut r = role();
|
||||
r.inputs = vec![InputRole::Source];
|
||||
let err = resolve(&r, &[&[bind("a")]], &conns).unwrap_err();
|
||||
assert!(matches!(err, ResolveError::InputRequired { input: InputRole::Mask, .. }));
|
||||
assert_eq!(err.to_string(), "model m requires a 'mask' input that this tool does not provide");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_capability_and_missing_model() {
|
||||
let mut conns = [conn("a", true)];
|
||||
let mut r = role();
|
||||
r.capability = cap("image.generate");
|
||||
assert!(matches!(resolve(&r, &[&[bind("a")]], &conns), Err(ResolveError::CapabilityMismatch { .. })));
|
||||
conns[0].models.clear();
|
||||
assert!(matches!(resolve(&role(), &[&[bind("a")]], &conns), Err(ResolveError::ModelMissing { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eligible_filters_by_capability_inputs_and_enabled() {
|
||||
let mut off = conn("c", true);
|
||||
off.enabled = false;
|
||||
let conns = [conn("a", true), conn("b", false), off];
|
||||
let list = eligible(&role(), &conns);
|
||||
assert_eq!(list.len(), 1);
|
||||
assert_eq!(list[0].connection.id.as_str(), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn error_messages_read_well() {
|
||||
let msg = ResolveError::Unbound(RoleId::new("x").unwrap()).to_string();
|
||||
assert!(msg.contains("no model is chosen"));
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ use std::fmt;
|
||||
pub struct SecretString(String);
|
||||
|
||||
impl SecretString {
|
||||
/// Wraps a secret value.
|
||||
pub fn new(value: impl Into<String>) -> Self {
|
||||
Self(value.into())
|
||||
}
|
||||
@@ -22,6 +23,7 @@ impl SecretString {
|
||||
&self.0
|
||||
}
|
||||
|
||||
/// True when the secret has no characters.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.0.is_empty()
|
||||
}
|
||||
@@ -73,21 +75,6 @@ pub fn redact(text: &str, secrets: &[&SecretString]) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn debug_and_display_never_show_the_value() {
|
||||
let s = SecretString::new("sk-live-abc123");
|
||||
assert!(!format!("{s:?}").contains("abc123"));
|
||||
assert!(!format!("{s}").contains("abc123"));
|
||||
assert!(!format!("{:?}", Some(&s)).contains("abc123"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_scrubs_every_occurrence() {
|
||||
let s = SecretString::new("sk-live-abc123");
|
||||
let out = redact("bad key sk-live-abc123 (sk-live-abc123)", &[&s]);
|
||||
assert_eq!(out, "bad key [redacted] ([redacted])");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_never_searches_its_own_markers() {
|
||||
// Each secret matches the marker the one before it wrote; replacing in turn doubled the
|
||||
@@ -105,10 +92,4 @@ mod tests {
|
||||
assert_eq!(redact("xabcdx", &[&a, &b]), "x[redacted]x");
|
||||
assert_eq!(redact("abcabc", &[&a]), "[redacted][redacted]");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn redact_ignores_empty_secret() {
|
||||
let s = SecretString::new("");
|
||||
assert_eq!(redact("hello", &[&s]), "hello");
|
||||
}
|
||||
}
|
||||
@@ -56,16 +56,23 @@ pub enum SpecAuth {
|
||||
/// `Authorization: Bearer <key>`.
|
||||
Bearer,
|
||||
/// The key is the whole value of this header.
|
||||
Header { name: String },
|
||||
Header {
|
||||
/// The header name. It must pass the same checks as a connection's key header.
|
||||
name: String,
|
||||
},
|
||||
/// No key.
|
||||
None,
|
||||
}
|
||||
|
||||
/// HTTP methods a call may use.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "UPPERCASE")]
|
||||
pub enum Method {
|
||||
#[allow(missing_docs)]
|
||||
Get,
|
||||
#[allow(missing_docs)]
|
||||
Post,
|
||||
#[allow(missing_docs)]
|
||||
Delete,
|
||||
}
|
||||
|
||||
@@ -73,10 +80,14 @@ pub enum Method {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Call {
|
||||
/// HTTP method.
|
||||
pub method: Method,
|
||||
/// Path joined to the spec's `base`. Starts with `/` and cannot name another host.
|
||||
pub path: String,
|
||||
/// Query parameters. Values may use the substitutions allowed for the call.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
pub query: BTreeMap<String, String>,
|
||||
/// JSON body template. Substitutions apply inside its string values only.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub body: Option<Value>,
|
||||
}
|
||||
@@ -93,13 +104,16 @@ pub enum ExtractAs {
|
||||
Text,
|
||||
}
|
||||
|
||||
/// Where in a reply to find a result, and what kind of data it is.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Extract {
|
||||
/// A JSON pointer (RFC 6901) into the reply.
|
||||
pub at: String,
|
||||
/// How to read the value at `at`. Written `as` in the spec file.
|
||||
#[serde(rename = "as")]
|
||||
pub kind: ExtractAs,
|
||||
/// Media type of the result, such as `image/png`. Required for `base64` and `url`.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub media_type: Option<String>,
|
||||
}
|
||||
@@ -108,40 +122,60 @@ pub struct Extract {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum StateWord {
|
||||
/// The provider has accepted the job but not started it.
|
||||
Queued,
|
||||
/// The job is in progress.
|
||||
Running,
|
||||
/// The job finished and the result is ready.
|
||||
Succeeded,
|
||||
/// The job failed.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// The call that starts a queued job.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Submit {
|
||||
/// The call to make.
|
||||
pub call: Call,
|
||||
/// Pointer to the job id in the reply.
|
||||
pub job_id_at: String,
|
||||
}
|
||||
|
||||
/// The repeated call that checks a queued job and reads its result.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Poll {
|
||||
/// The call to make. It may use `{job_id}`.
|
||||
pub call: Call,
|
||||
/// JSON pointer to the status word in the reply.
|
||||
pub status_at: String,
|
||||
/// Maps each status word the provider uses to one of the four states. A word not listed is an error.
|
||||
pub states: BTreeMap<String, StateWord>,
|
||||
/// Where to read the result once the job has succeeded.
|
||||
pub result: Extract,
|
||||
}
|
||||
|
||||
// A spec is loaded once and read many times; boxing the queue variant would only add noise.
|
||||
/// How a request becomes a result: one call, or a submit and poll queue.
|
||||
#[allow(clippy::large_enum_variant)]
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
|
||||
pub enum Flow {
|
||||
/// One call whose reply holds the result.
|
||||
RequestResponse { call: Call, result: Extract },
|
||||
RequestResponse {
|
||||
/// The one call to make.
|
||||
call: Call,
|
||||
/// Where the result is in the reply.
|
||||
result: Extract,
|
||||
},
|
||||
/// Submit, then ask for the result until it is ready.
|
||||
Queue {
|
||||
/// The call that starts the job.
|
||||
submit: Submit,
|
||||
/// The call that checks it.
|
||||
poll: Poll,
|
||||
/// Optional call that cancels the job.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
cancel: Option<Call>,
|
||||
},
|
||||
@@ -151,13 +185,18 @@ pub enum Flow {
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct SpecModel {
|
||||
/// Model id, as the provider names it. Must be a valid [`ModelId`].
|
||||
pub id: String,
|
||||
/// Name shown to the user.
|
||||
pub label: String,
|
||||
/// The capability the model offers, as `<modality>.<task>`.
|
||||
pub capability: String,
|
||||
/// Input role to the most of it the model takes.
|
||||
pub accepts: BTreeMap<String, u32>,
|
||||
/// Input roles that must be sent. Every model must require `prompt`.
|
||||
#[serde(default)]
|
||||
pub requires: Vec<String>,
|
||||
/// Most outputs one request can return. Defaults to 1.
|
||||
#[serde(default = "one")]
|
||||
pub max_outputs: u32,
|
||||
}
|
||||
@@ -196,18 +235,25 @@ impl Default for SpecLimits {
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Spec {
|
||||
/// Must equal [`SPEC_VERSION`].
|
||||
pub spec_version: u32,
|
||||
/// Id for the connection this spec makes. Must be a valid [`ConnectionId`](crate::ids::ConnectionId).
|
||||
pub id: String,
|
||||
/// Name shown to the user, 1 to 120 plain characters.
|
||||
pub label: String,
|
||||
/// `https://host[/prefix]`, or `http://` for a loopback host.
|
||||
pub base: String,
|
||||
/// How the key is sent. Defaults to a bearer token.
|
||||
#[serde(default = "bearer")]
|
||||
pub auth: SpecAuth,
|
||||
/// A free, read-only request for the Test button.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub probe: Option<Call>,
|
||||
/// The models the spec offers, at most [`MAX_MODELS`].
|
||||
pub models: Vec<SpecModel>,
|
||||
/// How a request becomes a result.
|
||||
pub flow: Flow,
|
||||
/// Bounds on one job.
|
||||
#[serde(default)]
|
||||
pub limits: SpecLimits,
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ use crate::payload::validate_media_type;
|
||||
pub struct SpecError {
|
||||
/// Where in the spec, such as `flow.submit.call.path`.
|
||||
pub at: String,
|
||||
/// What is wrong and what to do about it, in plain words.
|
||||
pub why: String,
|
||||
}
|
||||
|
||||
|
||||
@@ -9,8 +9,11 @@ use serde_json::Value;
|
||||
/// A value a template may name.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Slot {
|
||||
/// The user's prompt text.
|
||||
Prompt,
|
||||
/// The model id.
|
||||
Model,
|
||||
/// The job id a submit call returned. Only calls after the submit may use it.
|
||||
JobId,
|
||||
}
|
||||
|
||||
@@ -28,8 +31,11 @@ impl Slot {
|
||||
/// The values for one call. A slot left `None` cannot be used by that call.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub struct Values<'a> {
|
||||
/// Text for `{prompt}`.
|
||||
pub prompt: Option<&'a str>,
|
||||
/// Text for `{model}`.
|
||||
pub model: Option<&'a str>,
|
||||
/// Text for `{job_id}`.
|
||||
pub job_id: Option<&'a str>,
|
||||
}
|
||||
|
||||
|
||||
+18
-89
@@ -35,12 +35,15 @@ pub struct AppSettings {
|
||||
/// The whole store.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct StoreFile {
|
||||
/// Version of the file format, checked before anything else. [`SCHEMA_VERSION`] is the one this build writes.
|
||||
pub schema_version: u32,
|
||||
/// The saved connections. Ids must be unique.
|
||||
#[serde(default)]
|
||||
pub connections: Vec<Connection>,
|
||||
/// Default bindings, set in the launcher, used by every app unless it overrides.
|
||||
#[serde(default)]
|
||||
pub defaults: Vec<Binding>,
|
||||
/// Per-app settings, keyed by app id.
|
||||
#[serde(default)]
|
||||
pub apps: BTreeMap<AppId, AppSettings>,
|
||||
/// User-declared tool contracts, shared across the suite. A declaration does not install an adapter.
|
||||
@@ -51,23 +54,37 @@ pub struct StoreFile {
|
||||
/// Why a store file was refused.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum StoreError {
|
||||
/// The file is over [`MAX_STORE_BYTES`].
|
||||
TooLarge {
|
||||
/// Size of the file in bytes.
|
||||
len: usize,
|
||||
/// The limit in bytes.
|
||||
max: usize,
|
||||
},
|
||||
/// The file is not valid JSON for this schema. The string says why.
|
||||
Syntax(String),
|
||||
/// Written by a newer version. Do not write to it.
|
||||
TooNew {
|
||||
/// The file's schema version.
|
||||
found: u32,
|
||||
/// The newest schema version this build reads.
|
||||
supported: u32,
|
||||
},
|
||||
/// The schema version is 0.
|
||||
BadVersion(u32),
|
||||
/// Two connections share this id.
|
||||
DuplicateConnection(ConnectionId),
|
||||
/// Two custom tools share this id.
|
||||
DuplicateTool(RoleId),
|
||||
/// More than 64 custom tools. The number is the count found.
|
||||
TooManyTools(usize),
|
||||
/// A custom tool has an empty or over-long label, or no inputs, more than 8, or a repeated one.
|
||||
InvalidTool(RoleId),
|
||||
/// A connection failed its own validation.
|
||||
Invalid {
|
||||
/// The connection that failed.
|
||||
connection: ConnectionId,
|
||||
/// The rule it broke.
|
||||
why: ConnectionError,
|
||||
},
|
||||
}
|
||||
@@ -152,6 +169,7 @@ impl StoreFile {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Serializes the store as pretty-printed JSON. Does not validate; call [`StoreFile::validate`] first.
|
||||
pub fn to_json(&self) -> Result<String, StoreError> {
|
||||
serde_json::to_string_pretty(self).map_err(|e| StoreError::Syntax(e.to_string()))
|
||||
}
|
||||
@@ -204,95 +222,6 @@ mod tests {
|
||||
StoreFile { connections: vec![c], defaults: vec![binding], ..StoreFile::default() }
|
||||
}
|
||||
|
||||
fn role() -> Role {
|
||||
Role { id: RoleId::new("rewrite").unwrap(), label: "Rewrite".into(), capability: cap(), inputs: vec![InputRole::Prompt] }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trips() {
|
||||
let s = store();
|
||||
assert_eq!(StoreFile::parse(&s.to_json().unwrap()).unwrap(), s);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_fields_are_ignored() {
|
||||
let mut v: serde_json::Value = serde_json::from_str(&store().to_json().unwrap()).unwrap();
|
||||
v["added_in_a_later_release"] = serde_json::json!({"x": 1});
|
||||
v["connections"][0]["new_flag"] = serde_json::json!(true);
|
||||
assert!(StoreFile::parse(&v.to_string()).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_newer_schema_is_refused_even_if_its_shape_changed() {
|
||||
let text = r#"{"schema_version": 2, "connections": "now a different shape"}"#;
|
||||
assert_eq!(StoreFile::parse(text), Err(StoreError::TooNew { found: 2, supported: SCHEMA_VERSION }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_an_error_not_a_panic() {
|
||||
for text in
|
||||
["", "not json", "[]", "{}", r#"{"schema_version": 0}"#, r#"{"schema_version": -1}"#, r#"{"schema_version": 1, "connections": [1]}"#]
|
||||
{
|
||||
assert!(StoreFile::parse(text).is_err(), "{text:?}");
|
||||
}
|
||||
let big = format!("{{\"schema_version\":1,\"pad\":\"{}\"}}", "x".repeat(MAX_STORE_BYTES));
|
||||
assert!(matches!(StoreFile::parse(&big), Err(StoreError::TooLarge { .. })));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mislabelled_connection_is_refused_at_load() {
|
||||
let mut s = store();
|
||||
s.connections[0].locality = crate::connection::Locality::Local;
|
||||
let err = StoreFile::parse(&s.to_json().unwrap()).unwrap_err();
|
||||
assert!(matches!(err, StoreError::Invalid { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_connections_are_refused() {
|
||||
let mut s = store();
|
||||
s.connections.push(s.connections[0].clone());
|
||||
assert!(matches!(s.validate(), Err(StoreError::DuplicateConnection(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_uses_default_then_app_override() {
|
||||
let mut s = store();
|
||||
let app = AppId::new("wordcraft").unwrap();
|
||||
assert_eq!(s.resolve(&app, &role()).unwrap().connection.id.as_str(), "a");
|
||||
let mut other = remote("b");
|
||||
other.models = s.connections[0].models.clone();
|
||||
s.connections.push(other);
|
||||
let over = Binding { role: RoleId::new("rewrite").unwrap(), connection: ConnectionId::new("b").unwrap(), model: ModelId::new("m").unwrap() };
|
||||
s.apps.insert(app.clone(), AppSettings { overrides: vec![over] });
|
||||
assert_eq!(s.resolve(&app, &role()).unwrap().connection.id.as_str(), "b");
|
||||
assert_eq!(s.resolve(&AppId::new("photocraft").unwrap(), &role()).unwrap().connection.id.as_str(), "a");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dangling_bindings_are_reported() {
|
||||
let mut s = store();
|
||||
s.connections.clear();
|
||||
assert_eq!(s.dangling_bindings().len(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_and_mutated_files_never_panic() {
|
||||
let text = store().to_json().unwrap();
|
||||
for end in 0..=text.len() {
|
||||
if text.is_char_boundary(end) {
|
||||
let _ = StoreFile::parse(&text[..end]);
|
||||
}
|
||||
}
|
||||
let bytes = text.as_bytes();
|
||||
for i in (0..bytes.len()).step_by(7) {
|
||||
let mut copy = bytes.to_vec();
|
||||
copy[i] = copy[i].wrapping_add(1);
|
||||
if let Ok(s) = String::from_utf8(copy) {
|
||||
let _ = StoreFile::parse(&s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serialized_store_contains_no_secret_values() {
|
||||
let json = store().to_json().unwrap();
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use craft_ai_core::role::{eligible, fits, resolve};
|
||||
//! Integration tests of craft-ai-core: contract regressions.
|
||||
|
||||
use craft_ai_core::*;
|
||||
|
||||
fn draft(endpoint: &str) -> ConnectionDraft {
|
||||
@@ -13,154 +14,6 @@ fn models(id: &str) -> Vec<ModelInfo> {
|
||||
vec![ModelInfo::new(ModelId::new(id).unwrap(), id)]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_draft_discards_models_when_address_changes_after_probe() {
|
||||
let mut draft = draft("https://a.example/v1");
|
||||
assert!(draft.set_models("https://a.example/v1", models("a-only")));
|
||||
draft.endpoint = "https://b.example/v1".into();
|
||||
assert!(draft.prepare(&[]).unwrap().connection.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returning_to_original_address_does_not_keep_another_addresses_models() {
|
||||
let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
|
||||
let mut draft = ConnectionDraft::from_connection(&saved);
|
||||
draft.endpoint = "https://b.example/v1".into();
|
||||
assert!(draft.set_models("https://b.example/v1", models("b-only")));
|
||||
draft.endpoint = "https://a.example/v1".into();
|
||||
assert!(draft.prepare(&[saved]).unwrap().connection.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_model_contents_does_not_establish_address_provenance() {
|
||||
let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
|
||||
let mut draft = ConnectionDraft::from_connection(&saved);
|
||||
draft.models = models("refreshed-at-a");
|
||||
draft.endpoint = "https://b.example/v1".into();
|
||||
assert!(draft.prepare(&[saved]).unwrap().connection.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preset_models_belong_to_the_preset_address() {
|
||||
let preset = PRESETS.iter().find(|preset| preset.key == "vertex-express").unwrap();
|
||||
let mut draft = ConnectionDraft::from_preset(preset);
|
||||
draft.key = "test-key".into();
|
||||
assert!(!draft.prepare(&[]).unwrap().connection.models.is_empty());
|
||||
draft.endpoint = "https://other.example/v1".into();
|
||||
assert!(draft.prepare(&[]).unwrap().connection.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_test_at_each_address_keeps_its_models() {
|
||||
let saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
|
||||
let mut draft = ConnectionDraft::from_connection(&saved);
|
||||
for address in ["https://b.example/v1", "https://a.example/v1", "https://c.example/v1"] {
|
||||
draft.endpoint = format!(" {address} ");
|
||||
assert!(draft.set_models(address, models("same-model")));
|
||||
assert_eq!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, models("same-model"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn editing_and_returning_without_a_probe_preserves_original_models() {
|
||||
let mut saved = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
|
||||
saved.models = models("a-only");
|
||||
let mut draft = ConnectionDraft::from_connection(&saved);
|
||||
draft.endpoint = "https://b.example/v1".into();
|
||||
assert!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models.is_empty());
|
||||
draft.endpoint = "https://a.example/v1".into();
|
||||
assert_eq!(draft.prepare(std::slice::from_ref(&saved)).unwrap().connection.models, saved.models);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_manual_models_still_work_for_a_new_connection_and_unchanged_address() {
|
||||
let mut draft = ConnectionDraft::custom();
|
||||
draft.endpoint = "https://custom.example/v1".into();
|
||||
draft.uses_key = false;
|
||||
draft.models = models("manual-model");
|
||||
let saved = draft.prepare(&[]).unwrap().connection;
|
||||
assert_eq!(saved.models, models("manual-model"));
|
||||
let mut edited = ConnectionDraft::from_connection(&saved);
|
||||
edited.models = models("other-manual-model");
|
||||
assert_eq!(edited.prepare(&[saved]).unwrap().connection.models, models("other-manual-model"));
|
||||
}
|
||||
|
||||
fn role_and_connection() -> (Role, Connection, Binding) {
|
||||
let capability = CapabilityId::parse("image.inpaint").unwrap();
|
||||
let role = Role {
|
||||
id: RoleId::new("source-only").unwrap(),
|
||||
label: "Source only".into(),
|
||||
capability: capability.clone(),
|
||||
inputs: vec![InputRole::Source],
|
||||
};
|
||||
let mut connection = draft("https://a.example/v1").prepare(&[]).unwrap().connection;
|
||||
connection.models = vec![
|
||||
ModelInfo::new(ModelId::new("needs-mask").unwrap(), "Needs mask").with(
|
||||
CapabilitySpec::new(capability)
|
||||
.accepting(InputRole::Source, 1)
|
||||
.accepting(InputRole::Mask, 1)
|
||||
.requiring(InputRole::Source)
|
||||
.requiring(InputRole::Mask),
|
||||
),
|
||||
];
|
||||
let binding = Binding { role: role.id.clone(), connection: connection.id.clone(), model: connection.models[0].id.clone() };
|
||||
(role, connection, binding)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn model_picker_excludes_inputs_the_tool_cannot_supply() {
|
||||
let (role, connection, _) = role_and_connection();
|
||||
let request = Request::new(role.capability.clone()).with_input(InputRole::Source, Payload::inline("image/png", vec![1]).unwrap());
|
||||
assert!(request.validate(&connection.models[0].capabilities[0], &Limits::default()).is_err());
|
||||
assert!(fits(&role, &connection.models[0]).is_none());
|
||||
assert!(eligible(&role, &[connection]).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn binding_resolution_rejects_inputs_the_tool_cannot_supply() {
|
||||
let (role, connection, binding) = role_and_connection();
|
||||
assert!(resolve(&role, &[&[binding]], &[connection]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_inputs_resolve_when_supplied_and_optional_inputs_need_not_be_sent() {
|
||||
let (mut role, mut connection, binding) = role_and_connection();
|
||||
role.inputs.push(InputRole::Mask);
|
||||
assert!(fits(&role, &connection.models[0]).is_some());
|
||||
assert!(resolve(&role, &[std::slice::from_ref(&binding)], std::slice::from_ref(&connection)).is_ok());
|
||||
role.inputs = vec![InputRole::Source];
|
||||
connection.models[0].capabilities[0].requires = vec![InputRole::Source];
|
||||
assert!(fits(&role, &connection.models[0]).is_some());
|
||||
assert!(resolve(&role, &[&[binding]], &[connection]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_test_that_answers_after_the_address_moved_on_is_dropped() {
|
||||
let mut draft = draft("https://a.example/v1");
|
||||
// The test is started against a.example; the address is edited while it runs.
|
||||
draft.endpoint = "https://b.example/v1".into();
|
||||
assert!(!draft.set_models("https://a.example/v1", models("a-only")), "a late answer is not taken");
|
||||
assert!(draft.models.is_empty(), "and it leaves the form's models alone");
|
||||
assert!(draft.prepare(&[]).unwrap().connection.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_test_that_answers_while_its_address_still_stands_is_taken() {
|
||||
let mut draft = draft("https://a.example/v1");
|
||||
assert!(draft.set_models(" https://a.example/v1 ", models("a-only")), "whitespace is not a different address");
|
||||
assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("a-only"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_late_answer_does_not_overwrite_the_newer_address_own_models() {
|
||||
let mut draft = draft("https://a.example/v1");
|
||||
draft.endpoint = "https://b.example/v1".into();
|
||||
// The test at b.example answers first; the older one at a.example arrives afterwards.
|
||||
assert!(draft.set_models("https://b.example/v1", models("b-only")));
|
||||
assert!(!draft.set_models("https://a.example/v1", models("a-only")));
|
||||
assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("b-only"), "the newer answer stands");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_answer_is_judged_by_its_address_not_by_how_long_it_waited() {
|
||||
// Identity here is the address, not the test. After a.example → b.example → a.example, an
|
||||
@@ -175,24 +28,3 @@ fn an_answer_is_judged_by_its_address_not_by_how_long_it_waited() {
|
||||
assert!(draft.set_models("https://a.example/v1", models("a-only")), "an answer for the address on the form is taken");
|
||||
assert_eq!(draft.prepare(&[]).unwrap().connection.models, models("a-only"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_answer_leaves_models_already_on_the_form_untouched() {
|
||||
let mut draft = draft("https://a.example/v1");
|
||||
assert!(draft.set_models("https://a.example/v1", models("a-only")));
|
||||
draft.endpoint = "https://b.example/v1".into();
|
||||
assert!(!draft.set_models("https://a.example/v1", models("a-stale")));
|
||||
assert_eq!(draft.models, models("a-only"), "the refused set is not written over the form");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_address_differing_only_in_case_or_a_trailing_slash_is_a_different_address() {
|
||||
// The comparison is on the field's text, not a parsed URL: Endpoint drops the path, so
|
||||
// /v1 and /v2 would look equal through it. Differing the other way is safe — the answer is
|
||||
// refused and the person tests again — so this pins which way it fails.
|
||||
for other in ["https://A.Example/v1", "https://a.example/v1/", "https://a.example/v2"] {
|
||||
let mut draft = draft("https://a.example/v1");
|
||||
assert!(!draft.set_models(other, models("x")), "{other} is not the field's address");
|
||||
assert!(draft.models.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
//! u1: the rules for a custom (unlisted, OpenAI-shaped) connection: a named key header, and what
|
||||
//! a stored file may carry. The form is `ConnectionDraft`; these tests go through its public API.
|
||||
|
||||
use craft_ai_core::connection::ConnectionError;
|
||||
use craft_ai_core::{Billing, Connection, ConnectionDraft, Field, KeyChange, Locality};
|
||||
use craft_ai_core::{ConnectionDraft, Field};
|
||||
|
||||
fn custom(endpoint: &str, header: &str) -> ConnectionDraft {
|
||||
let mut d = ConnectionDraft::custom();
|
||||
@@ -13,42 +12,6 @@ fn custom(endpoint: &str, header: &str) -> ConnectionDraft {
|
||||
d
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_custom_form_starts_from_the_other_preset_with_billing_unknown() {
|
||||
let d = ConnectionDraft::custom();
|
||||
assert!(d.is_custom());
|
||||
assert_eq!(d.provider, "openai-compatible");
|
||||
assert_eq!(d.billing, Billing::Unknown);
|
||||
assert!(d.uses_key);
|
||||
assert!(d.key_header.is_empty());
|
||||
assert!(d.models.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_header_name_the_key_goes_as_a_bearer_token() {
|
||||
let p = custom("https://gw.example.com/ai/v7", "").prepare(&[]).unwrap();
|
||||
assert_eq!(p.connection.key_header, None);
|
||||
let json = serde_json::to_string(&p.connection).unwrap();
|
||||
assert!(!json.contains("key_header"), "{json}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_named_header_is_kept_saved_and_edited_back() {
|
||||
let p = custom("https://gw.example.com/ai/v7", " X-Api-Key ").prepare(&[]).unwrap();
|
||||
assert_eq!(p.connection.key_header.as_deref(), Some("X-Api-Key"));
|
||||
assert_eq!(p.connection.endpoint.as_deref(), Some("https://gw.example.com/ai/v7"));
|
||||
assert_eq!(p.connection.locality, Locality::Remote);
|
||||
assert!(matches!(p.key, KeyChange::Set(_)));
|
||||
|
||||
let again: Connection = serde_json::from_str(&serde_json::to_string(&p.connection).unwrap()).unwrap();
|
||||
assert_eq!(again, p.connection);
|
||||
let edit = ConnectionDraft::from_connection(&again);
|
||||
assert_eq!(edit.key_header, "X-Api-Key");
|
||||
let kept = edit.prepare(std::slice::from_ref(&again)).unwrap();
|
||||
assert_eq!(kept.connection.key_header.as_deref(), Some("X-Api-Key"));
|
||||
assert!(matches!(kept.key, KeyChange::Keep));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_names_that_could_break_the_request_are_refused() {
|
||||
let long = "a".repeat(65);
|
||||
@@ -74,35 +37,3 @@ fn header_names_that_could_break_the_request_are_refused() {
|
||||
assert!(!e.message.contains("k-123"), "{bad:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_key_header_names_are_accepted() {
|
||||
for ok in ["x-api-key", "api-key", "X-Goog-Api-Key", "apikey", "x_token"] {
|
||||
custom("https://gw.example.com/v1", ok).prepare(&[]).unwrap_or_else(|e| panic!("{ok}: {e}"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_header_name_without_a_key_is_refused() {
|
||||
let mut d = custom("http://127.0.0.1:9000/v1", "x-api-key");
|
||||
d.uses_key = false;
|
||||
d.key.clear();
|
||||
assert_eq!(d.prepare(&[]).unwrap_err().field, Field::KeyHeader);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stored_file_with_a_bad_header_name_is_refused_on_validate() {
|
||||
let mut c = custom("https://gw.example.com/v1", "x-api-key").prepare(&[]).unwrap().connection;
|
||||
assert!(c.validate().is_ok());
|
||||
c.key_header = Some("host".to_owned());
|
||||
assert!(matches!(c.validate(), Err(ConnectionError::KeyHeader(_))));
|
||||
c.key_header = Some("x-api-key".to_owned());
|
||||
c.auth = craft_ai_core::Auth::None;
|
||||
assert!(matches!(c.validate(), Err(ConnectionError::KeyHeader(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_http_to_a_remote_host_is_still_refused_for_a_custom_address() {
|
||||
let e = custom("http://gw.example.com/v1", "x-api-key").prepare(&[]).unwrap_err();
|
||||
assert_eq!(e.field, Field::Address);
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
use craft_ai_core::{CapabilityId, InputRole, Role, RoleId, StoreFile};
|
||||
|
||||
fn tool(id: &str) -> Role {
|
||||
Role {
|
||||
id: RoleId::new(id).unwrap(),
|
||||
label: "Describe photograph".into(),
|
||||
capability: CapabilityId::parse("image.describe").unwrap(),
|
||||
inputs: vec![InputRole::Source],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_user_tool_ids_are_refused_before_the_store_is_written() {
|
||||
let store = StoreFile { custom_tools: vec![tool("describe-photo"), tool("describe-photo")], ..StoreFile::default() };
|
||||
assert!(store.validate().is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_store_loads_and_user_tool_round_trips() {
|
||||
let old = r#"{"schema_version":1,"connections":[],"defaults":[],"apps":{}}"#;
|
||||
let mut store = StoreFile::parse(old).unwrap();
|
||||
assert!(store.custom_tools.is_empty());
|
||||
store.custom_tools.push(tool("describe-photo"));
|
||||
let again = StoreFile::parse(&store.to_json().unwrap()).unwrap();
|
||||
assert_eq!(again.custom_tools, store.custom_tools);
|
||||
assert_eq!(again.custom_tools[0].capability.as_str(), "image.describe");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_tool_declarations_are_refused_on_load() {
|
||||
let mut s = StoreFile { custom_tools: vec![tool("describe-photo"); 65], ..StoreFile::default() };
|
||||
assert!(s.validate().is_err());
|
||||
s.custom_tools.truncate(1);
|
||||
s.custom_tools[0].inputs.push(InputRole::Source);
|
||||
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
|
||||
s.custom_tools[0].inputs = vec![InputRole::Source];
|
||||
s.custom_tools[0].label = " \t ".into();
|
||||
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
|
||||
s.custom_tools[0].label = "x".repeat(121);
|
||||
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
|
||||
s.custom_tools[0].label = "Describe photograph".into();
|
||||
s.custom_tools[0].inputs.clear();
|
||||
assert!(StoreFile::parse(&s.to_json().unwrap()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_app_cannot_reinterpret_the_inputs_of_a_shared_custom_tool() {
|
||||
use craft_ai_core::role::ResolveError;
|
||||
use craft_ai_core::{AppId, Binding, CapabilitySpec, Connection, ConnectionId, ModelId, ModelInfo};
|
||||
let shared = tool("describe-photo");
|
||||
let model = ModelInfo::new(ModelId::new("m").unwrap(), "M").with(CapabilitySpec::new(shared.capability.clone()).accepting(InputRole::Source, 1));
|
||||
let connection: Connection = serde_json::from_value(serde_json::json!({
|
||||
"id":"service", "label":"Service", "provider":"test",
|
||||
"endpoint":"http://127.0.0.1:9", "locality":"local", "auth":{"kind":"none"},
|
||||
"billing":"free", "models":[model]
|
||||
}))
|
||||
.unwrap();
|
||||
let store = StoreFile {
|
||||
connections: vec![connection],
|
||||
defaults: vec![Binding { role: shared.id.clone(), connection: ConnectionId::new("service").unwrap(), model: ModelId::new("m").unwrap() }],
|
||||
custom_tools: vec![shared.clone()],
|
||||
..StoreFile::default()
|
||||
};
|
||||
let app = AppId::new("photocraft").unwrap();
|
||||
assert!(store.resolve(&app, &shared).is_ok());
|
||||
let mut redefined = shared;
|
||||
redefined.inputs.clear();
|
||||
assert!(matches!(store.resolve(&app, &redefined), Err(ResolveError::ToolMismatch(_))));
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
//! Integration tests, built into the library's own test executable.
|
||||
|
||||
mod contract_regressions;
|
||||
mod custom_connection;
|
||||
mod mock_conformance;
|
||||
mod spec_rules;
|
||||
mod spec_support;
|
||||
mod spec_template;
|
||||
@@ -1,12 +1,8 @@
|
||||
//! Drives the mock provider through the shared conformance checks, and shows the model working
|
||||
//! end to end the way an app would use it: declare roles, resolve through the store, check
|
||||
//! consent, submit, poll, cancel. Also proves one library serves different modalities.
|
||||
//! Drives the mock provider through the shared conformance checks.
|
||||
|
||||
use craft_ai_core::conformance::{run_cancel, run_lifecycle, run_rejects, run_unknown_job};
|
||||
use craft_ai_core::consent::Disclosure;
|
||||
use craft_ai_core::conformance::run_lifecycle;
|
||||
use craft_ai_core::job::{Event, JobState, Output};
|
||||
use craft_ai_core::mock::{MockProvider, Outcome, Script};
|
||||
use craft_ai_core::role::{Binding, Role};
|
||||
use craft_ai_core::*;
|
||||
|
||||
fn cap(s: &str) -> CapabilityId {
|
||||
@@ -33,16 +29,6 @@ fn image_model() -> ModelInfo {
|
||||
)
|
||||
}
|
||||
|
||||
fn text_model() -> ModelInfo {
|
||||
ModelInfo::new(model_id("txt"), "Text model").with(
|
||||
CapabilitySpec::new(cap("text.complete")).accepting(InputRole::Prompt, 1).accepting(InputRole::System, 1).with_features(Features {
|
||||
streaming: true,
|
||||
tools: true,
|
||||
structured_output: true,
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
fn inpaint_request() -> Request {
|
||||
Request::new(cap("image.inpaint")).with_input(InputRole::Source, png()).with_input(InputRole::Mask, png()).with_outputs(2)
|
||||
}
|
||||
@@ -58,104 +44,3 @@ fn image_job_passes_the_lifecycle_and_returns_variations() {
|
||||
assert_eq!(done.state, JobState::Succeeded);
|
||||
assert_eq!(done.events.iter().filter(|e| matches!(e, Event::Output(_))).count(), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_job_streams_deltas_in_order() {
|
||||
let script = Script { text_chunks: vec!["Hel".into(), "lo ".into(), "world".into()], ..Script::default() };
|
||||
let p = MockProvider::new(vec![text_model()], script);
|
||||
let req = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("say hello")).streaming();
|
||||
let done = run_lifecycle(&p, &model_id("txt"), &req).unwrap();
|
||||
let text: String = done.events.iter().filter_map(|e| if let Event::TextDelta { text } = e { Some(text.as_str()) } else { None }).collect();
|
||||
assert_eq!(text, "Hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn failure_is_reported_with_its_kind() {
|
||||
let err = AiError::new(ErrorKind::Quota, "out of credits");
|
||||
let p = MockProvider::new(vec![image_model()], Script { outcome: Outcome::Fail(err.clone()), ..Script::default() });
|
||||
let done = run_lifecycle(&p, &model_id("img"), &inpaint_request()).unwrap();
|
||||
assert_eq!(done.state, JobState::Failed { error: err });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_mid_job_ends_cancelled() {
|
||||
let p = MockProvider::new(vec![image_model()], Script { running_polls: 50, ..Script::default() });
|
||||
run_cancel(&p, &model_id("img"), &inpaint_request()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_requests_are_refused_before_sending() {
|
||||
let p = MockProvider::new(vec![image_model(), text_model()], Script::default());
|
||||
let with_reference = inpaint_request().with_input(InputRole::Reference, png());
|
||||
run_rejects(&p, &model_id("img"), &with_reference, ErrorKind::Unsupported).unwrap();
|
||||
let too_many = inpaint_request().with_outputs(9);
|
||||
run_rejects(&p, &model_id("img"), &too_many, ErrorKind::Unsupported).unwrap();
|
||||
let missing_mask = Request::new(cap("image.inpaint")).with_input(InputRole::Source, png());
|
||||
run_rejects(&p, &model_id("img"), &missing_mask, ErrorKind::InvalidRequest).unwrap();
|
||||
let wrong_model = Request::new(cap("text.complete")).with_input(InputRole::Prompt, Payload::text("x"));
|
||||
run_rejects(&p, &model_id("img"), &wrong_model, ErrorKind::Unsupported).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_jobs_are_errors() {
|
||||
run_unknown_job(&MockProvider::new(vec![image_model()], Script::default())).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_app_flow_from_store_to_finished_job() {
|
||||
// The launcher's store: one remote connection offering both models, defaults for two apps' roles.
|
||||
let conn = Connection {
|
||||
id: ConnectionId::new("conn1").unwrap(),
|
||||
label: "My provider".into(),
|
||||
provider: "http".into(),
|
||||
endpoint: Some("https://api.example.com".into()),
|
||||
locality: Locality::Remote,
|
||||
auth: Auth::ApiKey { secret: SecretRef::new("secret-conn1").unwrap() },
|
||||
billing: Billing::Metered,
|
||||
models: vec![image_model(), text_model()],
|
||||
enabled: true,
|
||||
key_header: None,
|
||||
};
|
||||
let fill = Role {
|
||||
id: RoleId::new("generative-fill").unwrap(),
|
||||
label: "Generative Fill".into(),
|
||||
capability: cap("image.inpaint"),
|
||||
inputs: vec![InputRole::Source, InputRole::Mask],
|
||||
};
|
||||
let rewrite =
|
||||
Role { id: RoleId::new("rewrite").unwrap(), label: "Rewrite".into(), capability: cap("text.complete"), inputs: vec![InputRole::Prompt] };
|
||||
let bind = |role: &Role, model: &str| Binding { role: role.id.clone(), connection: conn.id.clone(), model: model_id(model) };
|
||||
let store = StoreFile { connections: vec![conn.clone()], defaults: vec![bind(&fill, "img"), bind(&rewrite, "txt")], ..StoreFile::default() };
|
||||
let store = StoreFile::parse(&store.to_json().unwrap()).unwrap();
|
||||
|
||||
// Two different apps resolve their own roles from the same store.
|
||||
let photocraft = AppId::new("photocraft").unwrap();
|
||||
let wordcraft = AppId::new("wordcraft").unwrap();
|
||||
let resolved = store.resolve(&photocraft, &fill).unwrap();
|
||||
assert_eq!(resolved.model.id.as_str(), "img");
|
||||
assert_eq!(store.resolve(&wordcraft, &rewrite).unwrap().model.id.as_str(), "txt");
|
||||
|
||||
// Consent is required for a remote connection, shows kinds and sizes, and is remembered.
|
||||
let request = inpaint_request().with_input(InputRole::Prompt, Payload::text("remove the lamp"));
|
||||
let disclosure = Disclosure::for_request(&photocraft, resolved.connection, &request);
|
||||
let mut ledger = ConsentLedger::default();
|
||||
assert!(ledger.needs_consent(&disclosure, 0));
|
||||
ledger.grant(&disclosure);
|
||||
assert!(!ledger.needs_consent(&disclosure, 0));
|
||||
|
||||
// Run it through a provider built from the same model list.
|
||||
let provider = MockProvider::new(resolved.connection.models.clone(), Script { outcome: Outcome::Succeed(two_outputs()), ..Script::default() });
|
||||
resolved.spec.validate_request(&request).unwrap();
|
||||
let done = run_lifecycle(&provider, &resolved.model.id, &request).unwrap();
|
||||
assert_eq!(done.state, JobState::Succeeded);
|
||||
}
|
||||
|
||||
trait ValidateRequest {
|
||||
fn validate_request(&self, r: &Request) -> Result<(), AiError>;
|
||||
}
|
||||
|
||||
impl ValidateRequest for CapabilitySpec {
|
||||
fn validate_request(&self, r: &Request) -> Result<(), AiError> {
|
||||
r.validate(self, &Limits::default())
|
||||
}
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
//! How calls may use substitutions and what a flow must send (task u2). Each case feeds an input
|
||||
//! that only the named rule refuses.
|
||||
|
||||
mod spec_support;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use spec_support::{direct, parse, queue, refused, set};
|
||||
|
||||
#[test]
|
||||
fn only_job_id_may_appear_in_a_path_and_only_where_a_job_exists() {
|
||||
refused(set(queue(), "/flow/submit/call/path", json!("/images/{prompt}")), "flow.submit.call.path", "only {job_id} may be used in a path");
|
||||
refused(set(queue(), "/flow/submit/call/path", json!("/images/{model}")), "flow.submit.call.path", "only {job_id} may be used in a path");
|
||||
refused(set(queue(), "/flow/submit/call/path", json!("/images/{job_id}")), "flow.submit.call", "{job_id} is not available");
|
||||
refused(set(direct(), "/flow/call/path", json!("/images/{job_id}")), "flow.call", "{job_id} is not available");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_placeholder_this_version_lacks_is_refused_by_name() {
|
||||
refused(
|
||||
set(queue(), "/flow/submit/call/body", json!({"seed": "{seed}", "p": "{prompt}"})),
|
||||
"flow.submit.call.body",
|
||||
"unsupported: placeholder {seed}",
|
||||
);
|
||||
refused(
|
||||
set(queue(), "/flow/poll/call/query", json!({"id": "{job_id}", "x": "{param.size}"})),
|
||||
"flow.poll.call.query",
|
||||
"unsupported: placeholder {param.size}",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_key_cannot_be_a_template() {
|
||||
refused(set(queue(), "/flow/submit/call/body", json!({"{prompt}": 1, "p": "{prompt}"})), "flow.submit.call.body", "a key cannot hold a brace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_polling_and_cancel_calls_must_name_the_job() {
|
||||
refused(set(queue(), "/flow/poll/call/query", json!({"id": "fixed"})), "flow.poll.call", "never uses {job_id}");
|
||||
refused(set(queue(), "/flow/cancel/path", json!("/jobs")), "flow.cancel", "never uses {job_id}");
|
||||
assert!(parse(&set(queue(), "/flow/cancel", Value::Null)).is_ok(), "cancel is optional");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_prompt_must_be_sent_and_every_model_must_require_it() {
|
||||
refused(set(queue(), "/flow/submit/call/body", json!({"n": 1})), "flow", "the prompt is never sent");
|
||||
refused(set(queue(), "/models/0/requires", json!([])), "models[0].requires", "needs every model to require a prompt");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_body_belongs_to_a_post_and_stays_small() {
|
||||
refused(set(queue(), "/flow/poll/call/body", json!({"id": "{job_id}"})), "flow.poll.call.body", "only a POST has a body");
|
||||
let pad = "x".repeat(4096);
|
||||
refused(set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "pad": pad})), "flow.submit.call.body", "at most 4 KiB");
|
||||
let fits = "x".repeat(4096 - r#"{"p":"{prompt}","pad":""}"#.len());
|
||||
assert!(parse(&set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "pad": fits}))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn query_values_are_few_plain_and_short() {
|
||||
let q = |v: Value| set(queue(), "/flow/poll/call/query", v);
|
||||
refused(q(json!({"bad name": "{job_id}"})), "flow.poll.call.query", "plain");
|
||||
refused(q(json!({"id": "x".repeat(257)})), "flow.poll.call.query", "plain");
|
||||
let nine: serde_json::Map<String, Value> = (0..9).map(|i| (format!("k{i}"), json!("{job_id}"))).collect();
|
||||
refused(q(Value::Object(nine)), "flow.poll.call.query", "at most 8");
|
||||
let eight: serde_json::Map<String, Value> = (0..8).map(|i| (format!("k{i}"), json!("{job_id}"))).collect();
|
||||
assert!(parse(&q(Value::Object(eight))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_literal_brace_is_written_doubled() {
|
||||
let body = json!({"p": "{prompt}", "note": "{{not a slot}}"});
|
||||
assert!(parse(&set(queue(), "/flow/submit/call/body", body)).is_ok());
|
||||
refused(set(queue(), "/flow/submit/call/body", json!({"p": "{prompt}", "note": "{oops"})), "flow.submit.call.body", "never closed");
|
||||
}
|
||||
@@ -1,55 +1,10 @@
|
||||
//! Rules a declarative spec must keep (task u2). Each case feeds an input that only the named rule
|
||||
//! refuses, and checks where the error points and what it says.
|
||||
|
||||
mod spec_support;
|
||||
use super::spec_support;
|
||||
|
||||
use craft_ai_core::spec::{MAX_SPEC_BYTES, Spec};
|
||||
use serde_json::{Value, json};
|
||||
use spec_support::{direct, parse, queue, refused, set};
|
||||
|
||||
#[test]
|
||||
fn both_documented_shapes_are_accepted_and_round_trip() {
|
||||
for v in [queue(), direct()] {
|
||||
let spec = parse(&v).unwrap();
|
||||
assert_eq!(Spec::parse(&serde_json::to_string(&spec).unwrap()).unwrap(), spec);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_file_size_limit_holds_at_its_edge() {
|
||||
let text = queue().to_string();
|
||||
let pad = MAX_SPEC_BYTES - text.len();
|
||||
assert!(Spec::parse(&format!("{text}{}", " ".repeat(pad))).is_ok());
|
||||
let e = Spec::parse(&format!("{text}{}", " ".repeat(pad + 1))).unwrap_err();
|
||||
assert!(e.why.contains("too large"), "{e}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_feature_this_version_lacks_is_refused_by_name_never_ignored() {
|
||||
refused(set(queue(), "/flow/submit", json!({"webhook": "x"})), "spec", "webhook");
|
||||
let mut v = queue();
|
||||
v["streaming"] = json!(true);
|
||||
refused(v, "spec", "streaming");
|
||||
let mut v = queue();
|
||||
v["models"][0]["params"] = json!(["seed"]);
|
||||
refused(v, "spec", "params");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_version_one_is_read() {
|
||||
refused(set(queue(), "/spec_version", json!(2)), "spec_version", "only version 1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_base_address_follows_the_connection_rules() {
|
||||
refused(set(queue(), "/base", json!("http://api.example.com")), "base", "plain http");
|
||||
refused(set(queue(), "/base", json!("https://u:p@api.example.com")), "base", "user-info");
|
||||
refused(set(queue(), "/base", json!("https://api.example.com/v2?x=1")), "base", "no query");
|
||||
refused(set(queue(), "/base", json!("https://api.example.com/v2#top")), "base", "no query");
|
||||
refused(set(queue(), "/base", json!("ftp://api.example.com")), "base", "http");
|
||||
refused(set(queue(), "/base", json!("https://api.example.com/v2/../x")), "base", "'..'");
|
||||
assert!(parse(&set(queue(), "/base", json!("https://api.example.com"))).is_ok());
|
||||
}
|
||||
use serde_json::json;
|
||||
use spec_support::{parse, queue, refused, set};
|
||||
|
||||
#[test]
|
||||
fn a_path_cannot_leave_the_base() {
|
||||
@@ -70,98 +25,3 @@ fn a_path_cannot_leave_the_base() {
|
||||
refused(path(&format!("/{}", "a".repeat(256))), at, "too long");
|
||||
assert!(parse(&path(&format!("/{}", "a".repeat(255)))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_key_header_follows_the_connection_rules() {
|
||||
let name = |n: &str| set(queue(), "/auth/name", json!(n));
|
||||
refused(name("authorization"), "auth", "Authorization");
|
||||
refused(name("host"), "auth", "cannot carry a key");
|
||||
refused(name("proxy-x"), "auth", "network");
|
||||
refused(name("bad name"), "auth", "letters, digits");
|
||||
refused(name(""), "auth", "1 to 64");
|
||||
assert!(parse(&set(queue(), "/auth", json!({"kind": "bearer"}))).is_ok());
|
||||
assert!(parse(&set(queue(), "/auth", json!({"kind": "none"}))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_model_is_declared_completely_or_not_at_all() {
|
||||
let m = |field: &str, to: Value| set(queue(), &format!("/models/0/{field}"), to);
|
||||
refused(m("id", json!("bad id")), "models[0].id", "");
|
||||
refused(m("capability", json!("nope")), "models[0].capability", "");
|
||||
refused(m("label", json!(" ")), "models[0].label", "label");
|
||||
refused(m("accepts", json!({})), "models[0].accepts", "at least one");
|
||||
refused(m("accepts", json!({"prompt": 0})), "models[0].accepts", "must be 1");
|
||||
refused(m("accepts", json!({"prompt": 2})), "models[0].accepts", "must be 1");
|
||||
refused(m("accepts", json!({"source": 1})), "models[0].accepts", "unsupported: input 'source'");
|
||||
refused(m("requires", json!(["source"])), "models[0].requires", "must also be accepted");
|
||||
refused(m("max_outputs", json!(0)), "models[0].max_outputs", "1 to 4");
|
||||
refused(m("max_outputs", json!(5)), "models[0].max_outputs", "1 to 4");
|
||||
refused(set(queue(), "/models", json!([])), "models", "at least one");
|
||||
let one = queue()["models"][0].clone();
|
||||
refused(set(queue(), "/models", json!([one.clone(), one.clone()])), "models[1].id", "twice");
|
||||
let many: Vec<Value> = (0..17).map(|i| set(one.clone(), "/id", json!(format!("m{i}")))).collect();
|
||||
refused(set(queue(), "/models", json!(many)), "models", "at most 16");
|
||||
let sixteen: Vec<Value> = (0..16).map(|i| set(one.clone(), "/id", json!(format!("m{i}")))).collect();
|
||||
assert!(parse(&set(queue(), "/models", json!(sixteen))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_status_table_maps_words_to_the_four_states() {
|
||||
let states = |v: Value| set(queue(), "/flow/poll/states", v);
|
||||
let at = "flow.poll.states";
|
||||
refused(states(json!({"Error": "failed"})), at, "succeeded");
|
||||
refused(states(json!({"Ready": "succeeded"})), at, "failed");
|
||||
refused(states(json!({})), at, "succeeded");
|
||||
let table = |running: usize| {
|
||||
let mut t = serde_json::Map::new();
|
||||
for i in 0..running {
|
||||
t.insert(format!("w{i}"), json!("running"));
|
||||
}
|
||||
t.insert("ok".into(), json!("succeeded"));
|
||||
t.insert("bad".into(), json!("failed"));
|
||||
Value::Object(t)
|
||||
};
|
||||
assert!(parse(&states(table(14))).is_ok(), "16 entries are allowed");
|
||||
refused(states(table(15)), at, "at most 16");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pointer_is_a_bounded_rfc_6901_path() {
|
||||
let at = |p: &str| set(queue(), "/flow/poll/result/at", json!(p));
|
||||
refused(at("result/sample"), "flow.poll.result.at", "starts with /");
|
||||
refused(at("/a/b/c/d/e/f/g/h/i"), "flow.poll.result.at", "8 levels");
|
||||
assert!(parse(&at("/a/b/c/d/e/f/g/h")).is_ok());
|
||||
refused(set(queue(), "/flow/submit/job_id_at", json!("id")), "flow.submit.job_id_at", "starts with /");
|
||||
refused(set(queue(), "/flow/poll/status_at", json!("")), "flow.poll.status_at", "starts with /");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_result_says_what_it_is() {
|
||||
let ex = |v: Value| set(queue(), "/flow/poll/result", v);
|
||||
refused(ex(json!({"at": "/x", "as": "url"})), "flow.poll.result", "media_type");
|
||||
refused(ex(json!({"at": "/x", "as": "base64"})), "flow.poll.result", "media_type");
|
||||
refused(ex(json!({"at": "/x", "as": "text", "media_type": "text/plain"})), "flow.poll.result", "text");
|
||||
refused(ex(json!({"at": "/x", "as": "url", "media_type": "not a type"})), "flow.poll.result", "media_type");
|
||||
assert!(parse(&ex(json!({"at": "/x", "as": "text"}))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn limits_are_bounded() {
|
||||
let l = |field: &str, to: Value| {
|
||||
let mut v = queue();
|
||||
v["limits"] = json!({ field: to });
|
||||
v
|
||||
};
|
||||
refused(l("max_polls", json!(0)), "limits.max_polls", "1 to 10000");
|
||||
refused(l("max_polls", json!(10001)), "limits.max_polls", "1 to 10000");
|
||||
refused(l("max_seconds", json!(0)), "limits.max_seconds", "1 to 3600");
|
||||
refused(l("max_seconds", json!(3601)), "limits.max_seconds", "1 to 3600");
|
||||
assert!(parse(&l("max_polls", json!(10000))).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_probe_is_a_free_read() {
|
||||
refused(set(queue(), "/probe/method", json!("POST")), "probe", "GET");
|
||||
refused(set(queue(), "/probe/body", json!({"a": 1})), "probe", "only a POST has a body");
|
||||
refused(set(queue(), "/probe/path", json!("/a/../b")), "probe.path", "'..'");
|
||||
}
|
||||
@@ -24,19 +24,6 @@ pub fn queue() -> Value {
|
||||
})
|
||||
}
|
||||
|
||||
pub fn direct() -> Value {
|
||||
json!({
|
||||
"spec_version": 1, "id": "plain-images", "label": "Plain Images",
|
||||
"base": "http://127.0.0.1:8080",
|
||||
"models": [{"id": "m", "label": "M", "capability": "image.generate",
|
||||
"accepts": {"prompt": 1}, "requires": ["prompt"]}],
|
||||
"flow": {"kind": "request_response",
|
||||
"call": {"method": "POST", "path": "/images",
|
||||
"body": {"model": "{model}", "prompt": "{prompt}"}},
|
||||
"result": {"at": "/data/0/b64_json", "as": "base64", "media_type": "image/png"}}
|
||||
})
|
||||
}
|
||||
|
||||
/// Replaces the value at `pointer`, or adds it when the parent object lacks that key.
|
||||
pub fn set(mut v: Value, pointer: &str, to: Value) -> Value {
|
||||
let (parent, key) = pointer.rsplit_once('/').unwrap_or(("", pointer));
|
||||
|
||||
@@ -1,32 +1,13 @@
|
||||
//! Substitution rules for declarative specs: what a template may name, and that the structure of
|
||||
//! a request can never come from the user's text.
|
||||
|
||||
use craft_ai_core::spec::template::{Slot, Values, render_text, render_value, slots, value_slots};
|
||||
use craft_ai_core::spec::template::{Values, render_text, render_value};
|
||||
use serde_json::json;
|
||||
|
||||
fn values() -> Values<'static> {
|
||||
Values { prompt: Some("a red door"), model: Some("img-1"), job_id: Some("job-7") }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_three_names_are_known_and_nothing_else() {
|
||||
assert_eq!(slots("{prompt} {model} {job_id}").unwrap(), vec![Slot::Prompt, Slot::Model, Slot::JobId]);
|
||||
assert_eq!(slots("no slots here").unwrap(), vec![]);
|
||||
for other in ["{seed}", "{param.size}", "{Prompt}", "{}", "{ prompt }"] {
|
||||
let why = slots(other).unwrap_err();
|
||||
assert!(why.contains("unsupported: placeholder"), "{other}: {why}");
|
||||
}
|
||||
assert_eq!(slots("{seed}").unwrap_err(), "unsupported: placeholder {seed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn braces_are_closed_or_doubled() {
|
||||
assert!(slots("a { b").unwrap_err().contains("never closed"));
|
||||
assert!(slots("a } b").unwrap_err().contains("lone }"));
|
||||
assert_eq!(render_text("{{literal}}", &values()).unwrap(), "{literal}");
|
||||
assert_eq!(render_text("{{{prompt}}}", &values()).unwrap(), "{a red door}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn text_is_inserted_and_never_read_again() {
|
||||
let v = Values { prompt: Some("{job_id} and {{ and }"), ..values() };
|
||||
@@ -43,37 +24,3 @@ fn a_prompt_cannot_add_a_field_or_change_a_key() {
|
||||
assert!(body.get("admin").is_none());
|
||||
assert_eq!(body["n"], json!(1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keys_are_literal_and_nested_values_are_rendered() {
|
||||
let template = json!({"a": [{"b": "{model}"}, "{job_id}"], "c": {"d": "{prompt}"}});
|
||||
let body = render_value(&template, &values()).unwrap();
|
||||
assert_eq!(body, json!({"a": [{"b": "img-1"}, "job-7"], "c": {"d": "a red door"}}));
|
||||
assert_eq!(value_slots(&template).unwrap(), vec![Slot::Model, Slot::JobId, Slot::Prompt]);
|
||||
assert!(value_slots(&json!({"{prompt}": 1})).unwrap_err().contains("key"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_is_never_substituted_even_when_it_looks_like_a_slot() {
|
||||
let body = render_value(&json!({"{prompt}": "{model}"}), &values()).unwrap();
|
||||
assert_eq!(body, json!({"{prompt}": "img-1"}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_slot_with_no_value_is_an_error_not_an_empty_string() {
|
||||
let v = Values { prompt: Some("x"), ..Values::default() };
|
||||
let why = render_text("/jobs/{job_id}", &v).unwrap_err();
|
||||
assert!(why.contains("{job_id} is not available"), "{why}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_slots_share_one_rendered_budget() {
|
||||
let prompt = "x".repeat(64 * 1024);
|
||||
let v = Values { prompt: Some(&prompt), ..values() };
|
||||
let slots = vec![json!("{prompt}"); 16];
|
||||
assert!(render_value(&json!({ "a": slots }), &v).is_ok());
|
||||
let slots = vec![json!("{prompt}{prompt}{prompt}{prompt}"); 32];
|
||||
let why = render_value(&json!({ "a": slots }), &v).unwrap_err();
|
||||
assert!(why.contains("at most"), "{why}");
|
||||
assert!(render_text(&"{prompt}".repeat(128), &v).is_err());
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
[package]
|
||||
autotests = false
|
||||
name = "craft-audio"
|
||||
description = "Audio file I/O and codecs: WAV/AIFF read and write, FLAC encoder, AAC and ALAC decoders and encoders, AC-3/E-AC-3 decoder and encoder, MP3 encoder, Opus and MP1/MP2 decoders."
|
||||
version.workspace = true
|
||||
@@ -62,15 +63,6 @@ symphonia = { version = "0.6.1", optional = true, default-features = false, feat
|
||||
[dev-dependencies]
|
||||
craft-media-testkit = { workspace = true }
|
||||
proptest = { workspace = true }
|
||||
serde_json = { workspace = true }
|
||||
|
||||
[[test]]
|
||||
name = "audio"
|
||||
required-features = ["decode", "lossless-encode", "peaks"]
|
||||
|
||||
[[test]]
|
||||
name = "codecs"
|
||||
required-features = ["decode", "encode"]
|
||||
|
||||
[[example]]
|
||||
name = "info"
|
||||
|
||||
@@ -500,94 +500,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_index_with_no_rate_does_not_panic_and_is_refused() {
|
||||
for sf_index in 13..=15 {
|
||||
let asc = AudioSpecificConfig::lc(sf_index, 2);
|
||||
assert_eq!(asc.sample_rate, 0);
|
||||
#[cfg(feature = "aac-decode")]
|
||||
assert!(crate::aac::Decoder::from_config(asc).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configs_that_would_not_parse_back_are_not_written() {
|
||||
assert!(AudioSpecificConfig::lc(4, 0).to_bytes().is_err());
|
||||
assert!(AudioSpecificConfig::lc(13, 2).to_bytes().is_err(), "a sampling rate of 0");
|
||||
let pce = ProgramConfig { front: vec![(true, 0)], ..Default::default() };
|
||||
let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) };
|
||||
assert_eq!(AudioSpecificConfig::parse(&asc.to_bytes().unwrap()).unwrap(), asc);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adts_headers_refuse_fields_they_cannot_hold() {
|
||||
for (object_type, sf_index, channel_config) in [(0, 4, 2), (5, 4, 2), (29, 4, 2), (2, 13, 2), (2, 15, 2), (2, 4, 8), (2, 4, 11), (2, 4, 12)] {
|
||||
assert!(AdtsHeader::write(object_type, sf_index, channel_config, 100, 0x7FF).is_err(), "{object_type} {sf_index} {channel_config}");
|
||||
}
|
||||
for object_type in 1..=4 {
|
||||
let h = AdtsHeader::parse(&AdtsHeader::write(object_type, 12, 7, 100, 0x7FF).unwrap()).unwrap();
|
||||
assert_eq!((h.object_type, h.sf_index, h.channel_config, h.frame_length), (object_type, 12, 7, 107));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn program_configs_refuse_more_elements_than_their_counts_hold() {
|
||||
let fits = ProgramConfig { front: vec![(false, 0); 15], lfe: vec![0; 3], assoc_data: vec![0; 7], ..Default::default() };
|
||||
assert!(fits.write(&mut BitWriter::new()).is_ok());
|
||||
for pce in [
|
||||
ProgramConfig { front: vec![(false, 0); 16], ..Default::default() },
|
||||
ProgramConfig { side: vec![(false, 0); 16], ..Default::default() },
|
||||
ProgramConfig { back: vec![(false, 0); 16], ..Default::default() },
|
||||
ProgramConfig { lfe: vec![0; 4], ..Default::default() },
|
||||
ProgramConfig { assoc_data: vec![0; 8], ..Default::default() },
|
||||
ProgramConfig { cc: vec![(false, 0); 16], ..Default::default() },
|
||||
] {
|
||||
assert!(pce.write(&mut BitWriter::new()).is_err(), "{pce:?}");
|
||||
let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) };
|
||||
assert!(asc.to_bytes().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adts_headers_refuse_frames_too_long_for_their_length() {
|
||||
let longest = AdtsHeader::write(2, 4, 2, 0x1FFF - 7, 0x7FF).unwrap();
|
||||
assert_eq!(AdtsHeader::parse(&longest).unwrap().frame_length, 0x1FFF);
|
||||
for payload in [0x1FFF - 6, 0x1FFF, usize::MAX] {
|
||||
assert!(AdtsHeader::write(2, 4, 2, payload, 0x7FF).is_err(), "{payload}");
|
||||
}
|
||||
}
|
||||
|
||||
/// An explicit sampling rate of 0 is not a rate.
|
||||
#[test]
|
||||
fn a_zero_explicit_rate_is_refused() {
|
||||
let mut bw = BitWriter::new();
|
||||
bw.write_bits(2, 5);
|
||||
bw.write_bits(15, 4);
|
||||
bw.write_bits(0, 24);
|
||||
bw.write_bits(2, 4);
|
||||
bw.write_bits(0, 3);
|
||||
assert!(AudioSpecificConfig::parse(&bw.finish()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asc_roundtrip() {
|
||||
let a = AudioSpecificConfig::lc(4, 2);
|
||||
let b = a.to_bytes().unwrap();
|
||||
assert_eq!(b, vec![0x12, 0x10]);
|
||||
assert_eq!(AudioSpecificConfig::parse(&b).unwrap(), a);
|
||||
// 48 kHz 5.1
|
||||
let a = AudioSpecificConfig::lc(3, 6);
|
||||
assert_eq!(AudioSpecificConfig::parse(&a.to_bytes().unwrap()).unwrap().channels(), 6);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn amd4_channel_configurations() {
|
||||
// 6.1 and 7.1 back (#922); 22.2 and 7.1 with heights stay unsupported
|
||||
let channels = |c| AudioSpecificConfig::parse(&AudioSpecificConfig::lc(3, c).to_bytes().unwrap()).map(|a| a.channels()).ok();
|
||||
assert_eq!([7, 11, 12].map(channels), [Some(8), Some(7), Some(8)]);
|
||||
assert_eq!([13, 14].map(config_layout), [None, None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn asc_with_pce() {
|
||||
let pce = ProgramConfig {
|
||||
@@ -604,33 +516,4 @@ mod tests {
|
||||
assert_eq!(p.channels(), 7);
|
||||
assert_eq!(p, a);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn he_aac_asc_parses_core() {
|
||||
// AOT 5, 24 kHz core, stereo, ext 48 kHz, core AOT 2
|
||||
let mut bw = BitWriter::new();
|
||||
bw.write_bits(5, 5);
|
||||
bw.write_bits(6, 4);
|
||||
bw.write_bits(2, 4);
|
||||
bw.write_bits(3, 4);
|
||||
bw.write_bits(2, 5);
|
||||
bw.write_bits(0, 3);
|
||||
let a = AudioSpecificConfig::parse(&bw.finish()).unwrap();
|
||||
assert!(a.sbr);
|
||||
assert_eq!(a.sample_rate, 24000);
|
||||
assert_eq!(a.extension_sample_rate, Some(48000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adts_roundtrip() {
|
||||
let h = AdtsHeader::write(2, 4, 2, 100, 0x7FF).unwrap();
|
||||
let mut frame = h.to_vec();
|
||||
frame.extend(std::iter::repeat_n(0u8, 100));
|
||||
let p = AdtsHeader::parse(&frame).unwrap();
|
||||
assert_eq!(p.frame_length, 107);
|
||||
assert_eq!((p.object_type, p.sf_index, p.channel_config), (2, 4, 2));
|
||||
let frames = split_adts(&frame).unwrap();
|
||||
assert_eq!(frames.len(), 1);
|
||||
assert_eq!(frames[0].1.len(), 100);
|
||||
}
|
||||
}
|
||||
@@ -618,25 +618,6 @@ mod tests {
|
||||
use super::*;
|
||||
use craft_media::bitstream::BitWriter;
|
||||
|
||||
/// Implicitly signalled HE-AAC (an AAC-LC config) is recognised from the SBR fill element.
|
||||
#[test]
|
||||
fn sbr_fill_element_marks_implicit_he_aac() {
|
||||
// AAC-LC, 22.05 kHz, stereo
|
||||
let mut dec = Decoder::new(&[0x13, 0x90]).unwrap();
|
||||
assert!(!dec.sbr());
|
||||
// ID_FIL, count 1, extension_type EXT_SBR_DATA (+ 4 bits of payload), ID_END
|
||||
let _ = dec.decode(&[0b1100_0011, 0b1010_0001, 0b1100_0000]);
|
||||
assert!(dec.sbr());
|
||||
// other fill payloads (EXT_FILL) don't
|
||||
let mut dec = Decoder::new(&[0x13, 0x90]).unwrap();
|
||||
let _ = dec.decode(&[0b1100_0010, 0b0000_0001, 0b1100_0000]);
|
||||
assert!(!dec.sbr());
|
||||
// explicit signalling: AOT 5, core 22.05 kHz, stereo, extension 44.1 kHz, core AOT 2
|
||||
let dec = Decoder::new(&[0x2B, 0x92, 0x08, 0x00]).unwrap();
|
||||
assert!(dec.sbr());
|
||||
assert_eq!(dec.sample_rate(), 22_050);
|
||||
}
|
||||
|
||||
/// An access unit whose elements are all empty: `elements` are (id, tag), then ID_END.
|
||||
fn silent_au(pce: Option<&ProgramConfig>, elements: &[(u32, u32)]) -> Vec<u8> {
|
||||
let mut bw = BitWriter::new();
|
||||
@@ -669,35 +650,6 @@ mod tests {
|
||||
assert_eq!(dec.find_slot(ElementType::Cpe, 0, &[true, true, false]), Ok(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn program_configs_place_elements_by_tag() {
|
||||
let pce = ProgramConfig { front: vec![(true, 3), (true, 5)], ..Default::default() };
|
||||
let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) };
|
||||
let dec = Decoder::from_config(asc).unwrap();
|
||||
assert_eq!(dec.find_slot(ElementType::Cpe, 5, &[false, false]), Ok(1));
|
||||
}
|
||||
|
||||
/// A program config lists its elements: one it does not list has no place.
|
||||
#[test]
|
||||
fn program_configs_refuse_unlisted_tags() {
|
||||
let pce = ProgramConfig { front: vec![(true, 3), (true, 5)], ..Default::default() };
|
||||
let asc = AudioSpecificConfig { pce: Some(pce), ..AudioSpecificConfig::lc(4, 0) };
|
||||
let dec = Decoder::from_config(asc).unwrap();
|
||||
assert!(dec.find_slot(ElementType::Cpe, 9, &[false, false]).is_err());
|
||||
assert!(dec.find_slot(ElementType::Sce, 3, &[false, false]).is_err());
|
||||
}
|
||||
|
||||
/// Some encoders code 5.1's LFE as an SCE, as ffmpeg allows. Nothing else changes type: an LFE
|
||||
/// is not written to the centre channel.
|
||||
#[test]
|
||||
fn indexed_configurations_refuse_elements_of_another_type() {
|
||||
let dec = Decoder::from_config(AudioSpecificConfig::lc(4, 6)).unwrap();
|
||||
// SCE, CPE, CPE, LFE
|
||||
assert_eq!(dec.find_slot(ElementType::Sce, 1, &[true, false, false, false]), Ok(3));
|
||||
assert!(dec.find_slot(ElementType::Lfe, 1, &[false, false, false, true]).is_err());
|
||||
assert!(dec.find_slot(ElementType::Cpe, 2, &[false, true, true, false]).is_err());
|
||||
}
|
||||
|
||||
/// A PCE in an access unit that then fails leaves the layout as it was.
|
||||
#[test]
|
||||
fn a_damaged_in_band_pce_does_not_change_the_layout() {
|
||||
@@ -730,15 +682,6 @@ mod tests {
|
||||
assert_eq!((dec.channels[0].prev_shape, dec.noise_state), (WindowShape::Kbd, noise));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_reset_restarts_the_noise_generator() {
|
||||
let mut dec = Decoder::from_config(AudioSpecificConfig::lc(4, 1)).unwrap();
|
||||
let first = dec.next_random();
|
||||
dec.next_random();
|
||||
dec.reset();
|
||||
assert_eq!(dec.next_random(), first);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_finite_spectra_do_not_reach_the_output_or_the_overlap() {
|
||||
let mut state = ChannelState { overlap: vec![0.0; 1024], prev_shape: WindowShape::Sine };
|
||||
|
||||
@@ -948,17 +948,6 @@ mod tests {
|
||||
units
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cbr_bitrate_limits_use_the_exact_bits_per_frame() {
|
||||
// 288000 b/s at 48 kHz is exactly 6144 bits per frame; one more cannot fit a mono frame.
|
||||
assert!(Encoder::new(EncoderConfig::cbr(48_000, 1, 288_000)).is_ok());
|
||||
assert!(Encoder::new(EncoderConfig::cbr(48_000, 1, 288_001)).is_err());
|
||||
// 4500 b/s at 96 kHz is exactly 48 bits per frame, the size of a silent mono frame.
|
||||
assert!(Encoder::new(EncoderConfig::cbr(96_000, 1, 4_500)).is_ok());
|
||||
assert!(Encoder::new(EncoderConfig::cbr(96_000, 1, 4_499)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig::cbr(96_000, 2, 2_000)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cbr_access_units_fit_the_decoder_buffer() {
|
||||
let sil = vec![0f32; 48_000];
|
||||
@@ -990,17 +979,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_rate_frames_are_filled_to_the_limit() {
|
||||
let sil = vec![0f32; 48_000];
|
||||
for bandwidth in [None, Some(1000)] {
|
||||
let units = encode_all(EncoderConfig::cbr(48_000, 1, 288_000).with_bandwidth(bandwidth), &sil);
|
||||
for u in &units[..units.len() - 1] {
|
||||
assert_eq!(u.len(), 768, "bandwidth {bandwidth:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cbr_fill_never_spends_more_than_the_reservoir_holds() {
|
||||
// Encode frame by frame, as `flush` does, so the bits each frame may spend are known: the
|
||||
@@ -1033,31 +1011,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_never_passes_the_request() {
|
||||
for bits in 0..3000u64 {
|
||||
let mut bw = BitWriter::new();
|
||||
let n = write_fill(&mut bw, bits);
|
||||
assert_eq!(n, bw.bit_len() as u64);
|
||||
assert!(n <= bits && n + 6 >= bits, "asked {bits}, wrote {n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vbr_quality_must_be_a_number() {
|
||||
assert!(Encoder::new(EncoderConfig::vbr(48_000, 2, f32::NAN)).is_err());
|
||||
// Infinities and other out-of-range values are clamped: they encode exactly as the nearest
|
||||
// end of the range, within the frame limit.
|
||||
let nz = noise(48_000);
|
||||
for (q, end) in [(f32::INFINITY, 6.0), (f32::NEG_INFINITY, 0.5), (100.0, 6.0), (-3.0, 0.5)] {
|
||||
let units = encode_all(EncoderConfig::vbr(48_000, 8, q).with_adts(true), &nz);
|
||||
assert!(units == encode_all(EncoderConfig::vbr(48_000, 8, end).with_adts(true), &nz), "quality {q}");
|
||||
for u in &units {
|
||||
assert!(u.len() <= 6144 + 7 && u.starts_with(&[0xFF]), "quality {q}: {}-byte unit", u.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_long_encode_call_buffers_one_frame_at_a_time() {
|
||||
let input = noise(44_100 * 2);
|
||||
|
||||
@@ -274,33 +274,6 @@ pub fn write_spectral(bw: &mut BitWriter, cb: u8, vals: &[i32]) {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn check_complete(codes: &[(u32, u8)]) {
|
||||
// Kraft sum exactly one and prefix-free.
|
||||
let max = codes.iter().map(|c| c.1).max().unwrap() as u32;
|
||||
let mut kraft = 0u64;
|
||||
for &(_, l) in codes {
|
||||
kraft += 1u64 << (max - l as u32);
|
||||
}
|
||||
assert_eq!(kraft, 1u64 << max);
|
||||
for (i, &(ci, li)) in codes.iter().enumerate() {
|
||||
for (j, &(cj, lj)) in codes.iter().enumerate() {
|
||||
if i != j && li <= lj {
|
||||
assert_ne!(cj >> (lj - li), ci, "codeword {i} is a prefix of {j}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codebooks_are_complete_prefix_codes() {
|
||||
check_complete(&SCALEFACTOR);
|
||||
assert_eq!(SCALEFACTOR[60], (0, 1));
|
||||
for b in &BOOKS {
|
||||
assert_eq!(b.codes.len() as u32, b.modulo.pow(b.dim as u32));
|
||||
check_complete(b.codes);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every codeword, followed by arbitrary bits, decodes to its own symbol and length.
|
||||
#[test]
|
||||
fn lut_decodes_every_codeword() {
|
||||
@@ -322,64 +295,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// A codeword cut off by the end of the data is `Eof`, also at an unaligned position.
|
||||
#[test]
|
||||
fn truncated_codeword_is_eof() {
|
||||
for (i, lut) in luts().iter().enumerate() {
|
||||
let codes: &[(u32, u8)] = if i == 0 { &SCALEFACTOR } else { BOOKS[i - 1].codes };
|
||||
let &(code, len) = codes.iter().max_by_key(|c| c.1).unwrap();
|
||||
for lead in 0..8u32 {
|
||||
let mut bw = BitWriter::new();
|
||||
bw.write_bits(0, lead);
|
||||
bw.write_bits(code, len as u32);
|
||||
let total = lead as usize + len as usize;
|
||||
let data = bw.finish();
|
||||
// drop the last byte if that cuts the codeword, else the codeword is whole
|
||||
let short = &data[..data.len() - 1];
|
||||
let mut br = BitReader::new(short);
|
||||
br.skip(lead as usize).unwrap();
|
||||
let r = lut.decode(&mut br);
|
||||
if short.len() * 8 < total {
|
||||
assert!(matches!(r, Err(Error::Eof)), "book {i} lead {lead}");
|
||||
} else {
|
||||
assert!(r.is_ok());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spectral_roundtrip_every_book() {
|
||||
for cb in 1..=11u8 {
|
||||
let b = book(cb);
|
||||
let lim = if cb == 11 { 8191 } else { b.lav as i32 };
|
||||
let mut vals = Vec::new();
|
||||
let mut seed = 12345u32;
|
||||
for _ in 0..400 {
|
||||
seed = seed.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
let r = (seed >> 8) as i32;
|
||||
let v = if cb == 11 && r % 3 == 0 { r % (lim + 1) } else { r % (b.lav.min(16) as i32 + 1) };
|
||||
let v = v.min(lim);
|
||||
vals.push(if b.signed || r & 1 == 0 { v } else { -v });
|
||||
}
|
||||
if b.signed {
|
||||
for v in vals.iter_mut() {
|
||||
*v = (*v).clamp(-(b.lav as i32), b.lav as i32);
|
||||
}
|
||||
}
|
||||
let mut bw = BitWriter::new();
|
||||
write_spectral(&mut bw, cb, &vals);
|
||||
assert_eq!(bw.bit_len() as u32, count_bits(cb, &vals));
|
||||
let data = bw.finish();
|
||||
let mut br = BitReader::new(&data);
|
||||
let mut out = vec![0i32; vals.len()];
|
||||
for c in out.chunks_mut(b.dim) {
|
||||
decode_spectral(&mut br, cb, c).unwrap();
|
||||
}
|
||||
assert_eq!(out, vals, "codebook {cb}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pair_count_matches_single_count() {
|
||||
let mut seed = 99u32;
|
||||
@@ -398,17 +313,4 @@ mod tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scalefactor_roundtrip() {
|
||||
let mut bw = BitWriter::new();
|
||||
for d in -60..=60 {
|
||||
write_sf(&mut bw, d);
|
||||
}
|
||||
let data = bw.finish();
|
||||
let mut br = BitReader::new(&data);
|
||||
for d in -60..=60 {
|
||||
assert_eq!(decode_sf(&mut br).unwrap(), d);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,25 +127,3 @@ impl IcsInfo {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn grouping_roundtrip() {
|
||||
let info = IcsInfo {
|
||||
window_sequence: WindowSequence::EightShort,
|
||||
window_shape: WindowShape::Kbd,
|
||||
max_sfb: 12,
|
||||
num_groups: 3,
|
||||
group_len: [3, 1, 4, 0, 0, 0, 0, 0],
|
||||
};
|
||||
let mut bw = BitWriter::new();
|
||||
info.write(&mut bw);
|
||||
let d = bw.finish();
|
||||
let p = IcsInfo::parse(&mut BitReader::new(&d), 4).unwrap();
|
||||
assert_eq!(p, info);
|
||||
assert_eq!(p.group_start(2), 4);
|
||||
}
|
||||
}
|
||||
@@ -192,13 +192,8 @@ impl Mdct {
|
||||
self.dct4(&u, out, &mut re, &mut im);
|
||||
}
|
||||
|
||||
/// Inverse MDCT (unscaled): `y[n] = Σ X[k] cos(π/M (n + ½ + M/2)(k + ½))`, `y` has length 2M.
|
||||
#[cfg(test)]
|
||||
pub fn inverse(&self, spec: &[f32], y: &mut [f32]) {
|
||||
self.inverse_with(spec, y, &mut self.scratch());
|
||||
}
|
||||
|
||||
/// [`Self::inverse`] with caller-provided working buffers from [`Self::scratch`].
|
||||
/// Inverse MDCT (unscaled): `y[n] = Σ X[k] cos(π/M (n + ½ + M/2)(k + ½))`, `y` has length 2M,
|
||||
/// with caller-provided working buffers from [`Self::scratch`].
|
||||
pub fn inverse_with(&self, spec: &[f32], y: &mut [f32], sc: &mut MdctScratch) {
|
||||
let m = self.m;
|
||||
let h = m / 2;
|
||||
@@ -301,66 +296,3 @@ pub fn window(shape: WindowShape, long: bool) -> &'static [f32] {
|
||||
};
|
||||
&w[i]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn direct(x: &[f32]) -> Vec<f64> {
|
||||
let m = x.len() / 2;
|
||||
(0..m).map(|k| (0..2 * m).map(|n| x[n] as f64 * (PI / m as f64 * (n as f64 + 0.5 + m as f64 / 2.0) * (k as f64 + 0.5)).cos()).sum()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forward_matches_definition() {
|
||||
for m in [128usize, 1024] {
|
||||
let x: Vec<f32> = (0..2 * m).map(|i| ((i * 7919) % 101) as f32 / 50.0 - 1.0).collect();
|
||||
let mut out = vec![0f32; m];
|
||||
Mdct::new(m).forward(&x, &mut out);
|
||||
let d = direct(&x);
|
||||
for k in 0..m {
|
||||
assert!((out[k] as f64 - d[k]).abs() < 1e-3 * (m as f64).sqrt(), "m={m} k={k} {} {}", out[k], d[k]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_matches_definition() {
|
||||
let m = 128;
|
||||
let spec: Vec<f32> = (0..m).map(|i| ((i * 31) % 17) as f32 - 8.0).collect();
|
||||
let mut y = vec![0f32; 2 * m];
|
||||
Mdct::new(m).inverse(&spec, &mut y);
|
||||
for n in 0..2 * m {
|
||||
let d: f64 = (0..m).map(|k| spec[k] as f64 * (PI / m as f64 * (n as f64 + 0.5 + m as f64 / 2.0) * (k as f64 + 0.5)).cos()).sum();
|
||||
assert!((y[n] as f64 - d).abs() < 1e-3, "n={n}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tdac_perfect_reconstruction() {
|
||||
let m = 1024;
|
||||
let t = Mdct::new(m);
|
||||
for shape in [WindowShape::Sine, WindowShape::Kbd] {
|
||||
let w = window(shape, true);
|
||||
let win = |n: usize| if n < m { w[n] } else { w[2 * m - 1 - n] };
|
||||
let x: Vec<f32> = (0..4 * m).map(|i| ((i as f32) * 0.013).sin() + ((i * 13) % 7) as f32 * 0.05).collect();
|
||||
let mut out = vec![0f32; 4 * m];
|
||||
for f in 0..3 {
|
||||
let seg: Vec<f32> = (0..2 * m).map(|n| x[f * m + n] * win(n)).collect();
|
||||
let mut spec = vec![0f32; m];
|
||||
t.forward(&seg, &mut spec);
|
||||
for v in spec.iter_mut() {
|
||||
*v *= 2.0;
|
||||
}
|
||||
let mut y = vec![0f32; 2 * m];
|
||||
t.inverse(&spec, &mut y);
|
||||
for n in 0..2 * m {
|
||||
out[f * m + n] += y[n] * win(n) / m as f32;
|
||||
}
|
||||
}
|
||||
for n in m..3 * m {
|
||||
assert!((out[n] - x[n]).abs() < 1e-4, "{shape:?} n={n} {} {}", out[n], x[n]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -137,29 +137,3 @@ pub fn sf_gain(sf: i32) -> f32 {
|
||||
fn sf_gain_exact(sf: i32) -> f32 {
|
||||
(0.25 * (sf as f64 - 100.0)).exp2() as f32
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn band_tables_are_monotonic_and_complete() {
|
||||
for i in 0..13u8 {
|
||||
let l = swb_offsets_long(i);
|
||||
assert_eq!(*l.last().unwrap(), 1024);
|
||||
assert!(l.windows(2).all(|w| w[0] < w[1] && (w[1] - w[0]) % 4 == 0));
|
||||
let s = swb_offsets_short(i);
|
||||
assert_eq!(*s.last().unwrap(), 128);
|
||||
assert!(s.windows(2).all(|w| w[0] < w[1] && (w[1] - w[0]) % 4 == 0));
|
||||
assert!(tns_max_bands(i, false) < l.len());
|
||||
assert!(tns_max_bands(i, true) < s.len());
|
||||
}
|
||||
assert_eq!(swb_offsets_long(3).len() - 1, 49);
|
||||
assert_eq!(swb_offsets_long(5).len() - 1, 51);
|
||||
assert_eq!(swb_offsets_long(0).len() - 1, 41);
|
||||
assert_eq!(swb_offsets_long(2).len() - 1, 47);
|
||||
assert_eq!(swb_offsets_long(6).len() - 1, 47);
|
||||
assert_eq!(swb_offsets_long(8).len() - 1, 43);
|
||||
assert_eq!(swb_offsets_long(11).len() - 1, 40);
|
||||
}
|
||||
}
|
||||
@@ -271,43 +271,3 @@ pub fn levinson(r: &[f64], order: usize) -> (Vec<f64>, f64) {
|
||||
}
|
||||
(ks, r[0] / err.max(r[0] * 1e-9))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::aac::ics::WindowSequence;
|
||||
use crate::aac::mdct::WindowShape;
|
||||
|
||||
#[test]
|
||||
fn coef_quant_roundtrip() {
|
||||
for res in [false, true] {
|
||||
let n = if res { 8 } else { 4 };
|
||||
for c in -n..n {
|
||||
let k = dequant_coef(c as i8, res);
|
||||
assert_eq!(quant_coef(k, res), c as i8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoder_decoder_filters_are_inverse() {
|
||||
let info = IcsInfo { window_sequence: WindowSequence::OnlyLong, window_shape: WindowShape::Sine, max_sfb: 49, ..Default::default() };
|
||||
let mut t = TnsData::default();
|
||||
t.windows[0].n_filt = 1;
|
||||
t.windows[0].coef_res = true;
|
||||
t.windows[0].filt[0] = TnsFilter { length: 40, order: 4, direction: true, coef_compress: false, coef: [3, -2, 1, 5, 0, 0, 0, 0, 0, 0, 0, 0] };
|
||||
let orig: Vec<f32> = (0..1024).map(|i| ((i * 37 % 101) as f32 - 50.0) * 0.1).collect();
|
||||
let mut s = orig.clone();
|
||||
apply_encoder(&mut s, &info, 4, &t);
|
||||
assert_ne!(s, orig);
|
||||
apply_decoder(&mut s, &info, 4, &t);
|
||||
for i in 0..1024 {
|
||||
assert!((s[i] - orig[i]).abs() < 1e-3);
|
||||
}
|
||||
let mut bw = BitWriter::new();
|
||||
t.write(&mut bw, &info);
|
||||
assert_eq!(bw.bit_len() as u32, t.bit_count(&info));
|
||||
let d = bw.finish();
|
||||
assert_eq!(TnsData::parse(&mut BitReader::new(&d), &info).unwrap(), t);
|
||||
}
|
||||
}
|
||||
@@ -592,15 +592,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_band_structures() {
|
||||
assert_eq!(DEFAULT_CPLBNDSTRC.iter().filter(|&&b| b).count(), 8);
|
||||
assert!(DEFAULT_CPLBNDSTRC[8] && !DEFAULT_CPLBNDSTRC[9] && !DEFAULT_CPLBNDSTRC[12] && DEFAULT_CPLBNDSTRC[17]);
|
||||
assert_eq!(DEFAULT_SPXBNDSTRC.iter().enumerate().filter(|(_, b)| **b).map(|(i, _)| i).collect::<Vec<_>>(), vec![8, 10, 12, 14, 16]);
|
||||
// every frame-based strategy sends new exponents in block 0
|
||||
assert!(FRAME_EXPSTR.iter().all(|s| s[0] != 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spectral_extension_translation_and_scaling() {
|
||||
// begin at sub-band 2 (bin 49), end at 5 (bin 85), copy from sub-band 0 (bin 25): three
|
||||
|
||||
@@ -1,69 +1,9 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn analysis_synthesis_reconstructs_overlap() {
|
||||
let input: Vec<f32> = (0..1024).map(|n| (n as f32 * 0.071).sin() * 0.4).collect();
|
||||
let mut overlap = [0.0; 256];
|
||||
for offset in (0..768).step_by(256) {
|
||||
let mut block = [0.0; 512];
|
||||
block.copy_from_slice(&input[offset..offset + 512]);
|
||||
let coeffs = transform::analysis(&block, false);
|
||||
let mut decoded = [0.0; 512];
|
||||
super::super::imdct(&coeffs, false, &mut decoded);
|
||||
if offset > 0 {
|
||||
for i in 0..256 {
|
||||
assert!((2.0 * (decoded[i] + overlap[i]) - input[offset + i]).abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
overlap.copy_from_slice(&decoded[256..]);
|
||||
}
|
||||
}
|
||||
|
||||
fn config(codec: Codec, mode: CodingMode, lfe: bool) -> Config {
|
||||
Config { codec, sample_rate: 48_000, bitrate_kbps: 448, mode, lfe }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_tone_headers_crc_and_level() -> Result<(), Box<dyn std::error::Error>> {
|
||||
for codec in [Codec::Ac3, Codec::Eac3] {
|
||||
for (mode, lfe) in [(CodingMode::Mono, false), (CodingMode::Stereo, false), (CodingMode::ThreeFrontTwoSurround, true)] {
|
||||
let cfg = config(codec, mode, lfe);
|
||||
let input: Vec<Vec<f32>> = (0..cfg.channels())
|
||||
.map(|ch| (0..3072).map(|n| (n as f32 * (if lfe && ch == 3 { 0.01 } else { 0.04 + ch as f32 * 0.015 })).sin() * 0.2).collect())
|
||||
.collect();
|
||||
let mut encoder = Encoder::new(cfg)?;
|
||||
let mut packets = encoder.push(&input.iter().map(Vec::as_slice).collect::<Vec<_>>())?;
|
||||
let finish = encoder.finish()?;
|
||||
packets.extend(finish.packets);
|
||||
let mut decoder = super::super::Decoder::new();
|
||||
let mut decoded = vec![Vec::new(); cfg.channels()];
|
||||
for packet in &packets {
|
||||
let header = super::super::parse_header(&packet.data)?;
|
||||
assert_eq!(header.channels(), cfg.channels());
|
||||
assert_eq!(header.samples(), 1536);
|
||||
assert_eq!(bitstream::crc(&packet.data[2..]), 0);
|
||||
if codec == Codec::Ac3 {
|
||||
let words = packet.data.len() / 2;
|
||||
let split = (words / 2 + words / 8) * 2;
|
||||
assert_eq!(bitstream::crc(&packet.data[2..split]), 0);
|
||||
}
|
||||
let frame = decoder.decode(&packet.data)?;
|
||||
for (dst, src) in decoded.iter_mut().zip(frame.channels) {
|
||||
dst.extend(src);
|
||||
}
|
||||
}
|
||||
for ch in 0..cfg.channels() {
|
||||
if lfe && ch == 3 {
|
||||
continue;
|
||||
} // The causal LFE low-pass intentionally changes phase.
|
||||
let mse = input[ch].iter().zip(&decoded[ch][256..]).map(|(&a, &b)| (a - b).powi(2)).sum::<f32>() / input[ch].len() as f32;
|
||||
assert!(mse < 0.0001, "{codec:?} {mode:?} ch{ch}: mse={mse}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_short_transitions_reconstruct_without_gain_or_phase_steps() {
|
||||
let mut seed = 23u32;
|
||||
@@ -113,81 +53,6 @@ fn lfe_lowpass_preserves_bass_and_rejects_full_bandwidth_content() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rates_modes_and_crc_boundaries() -> Result<(), Box<dyn std::error::Error>> {
|
||||
for codec in [Codec::Ac3, Codec::Eac3] {
|
||||
for rate in [32000, 44100, 48000] {
|
||||
for mode in [
|
||||
CodingMode::DualMono,
|
||||
CodingMode::Mono,
|
||||
CodingMode::Stereo,
|
||||
CodingMode::ThreeFront,
|
||||
CodingMode::StereoSurround,
|
||||
CodingMode::ThreeFrontSurround,
|
||||
CodingMode::StereoTwoSurround,
|
||||
CodingMode::ThreeFrontTwoSurround,
|
||||
] {
|
||||
for lfe in [false, true] {
|
||||
let cfg = Config { sample_rate: rate, ..config(codec, mode, lfe) };
|
||||
let mut encoder = Encoder::new(cfg)?;
|
||||
let planes = vec![vec![0.0; 1537]; cfg.channels()];
|
||||
let mut packets = encoder.push(&planes.iter().map(Vec::as_slice).collect::<Vec<_>>())?;
|
||||
let finish = encoder.finish()?;
|
||||
packets.extend(finish.packets);
|
||||
assert_eq!(packets.len(), 2);
|
||||
assert_eq!(finish.padding_samples, 1279);
|
||||
for packet in packets {
|
||||
let h = super::super::parse_header(&packet.data)?;
|
||||
assert_eq!(h.sample_rate, rate);
|
||||
assert_eq!(h.acmod, mode as u8);
|
||||
assert_eq!(h.lfeon, lfe);
|
||||
assert_eq!(h.frame_bytes, packet.data.len());
|
||||
assert_eq!(bitstream::crc(&packet.data[2..]), 0);
|
||||
let decoded = super::super::Decoder::new().decode(&packet.data)?;
|
||||
assert!(decoded.channels.iter().flatten().all(|&v| v == 0.0));
|
||||
if codec == Codec::Ac3 {
|
||||
let words = packet.data.len() / 2;
|
||||
assert_eq!(bitstream::crc(&packet.data[2..(words / 2 + words / 8) * 2]), 0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn input_validation_and_terminal_lifecycle() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let cfg = config(Codec::Ac3, CodingMode::Stereo, false);
|
||||
let mut encoder = Encoder::new(cfg)?;
|
||||
assert!(encoder.push(&[&[0.0]]).is_err());
|
||||
assert!(encoder.push(&[&[0.0], &[]]).is_err());
|
||||
for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 1.01, -1.01] {
|
||||
assert!(encoder.push(&[&[value], &[0.0]]).is_err());
|
||||
}
|
||||
assert_eq!(encoder.input_samples, 0);
|
||||
assert!(encoder.push(&[&[], &[]])?.is_empty());
|
||||
let finish = encoder.finish()?;
|
||||
assert!(finish.packets.is_empty());
|
||||
assert_eq!(finish.priming_samples, 0);
|
||||
assert_eq!(finish.padding_samples, 0);
|
||||
assert_eq!(encoder.push(&[&[], &[]]).err(), Some(Error::Finished));
|
||||
assert_eq!(encoder.finish().err(), Some(Error::Finished));
|
||||
// Force an internal impossible budget to exercise terminal handling without
|
||||
// relying on a public configuration that new() should have rejected.
|
||||
let mut failing = Encoder::new(cfg)?;
|
||||
failing.config.bitrate_kbps = 1;
|
||||
assert_eq!(failing.push(&[&[0.0; 1536], &[0.0; 1536]]).err(), Some(Error::BitBudget));
|
||||
assert_eq!(failing.push(&[&[], &[]]).err(), Some(Error::Finished));
|
||||
assert_eq!(failing.finish().err(), Some(Error::Finished));
|
||||
let mut overflow = Encoder::new(cfg)?;
|
||||
overflow.input_samples = u64::MAX - 2000;
|
||||
assert!(overflow.push(&[&[0.0; 1000], &[0.0; 1000]]).is_err());
|
||||
assert_eq!(overflow.input_samples, u64::MAX - 2000);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chunk_boundaries_and_exact_trim_counts() -> Result<(), Box<dyn std::error::Error>> {
|
||||
for codec in [Codec::Ac3, Codec::Eac3] {
|
||||
@@ -213,18 +78,6 @@ fn chunk_boundaries_and_exact_trim_counts() -> Result<(), Box<dyn std::error::Er
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn configuration_validates_real_frame_bounds_and_explicit_layout() {
|
||||
for rate in [32000, 44100] {
|
||||
assert!(Encoder::new(Config { codec: Codec::Eac3, sample_rate: rate, bitrate_kbps: 1024, mode: CodingMode::Stereo, lfe: false }).is_err());
|
||||
}
|
||||
assert!(Encoder::new(Config { codec: Codec::Eac3, sample_rate: 48000, bitrate_kbps: 1024, mode: CodingMode::Stereo, lfe: false }).is_ok());
|
||||
assert!(Encoder::new(config(Codec::Ac3, CodingMode::Surround71, true)).is_err());
|
||||
assert!(Encoder::new(config(Codec::Eac3, CodingMode::Surround71, false)).is_err());
|
||||
assert_eq!(config(Codec::Eac3, CodingMode::Surround71, true).channel_layout(), ChannelLayout::SURROUND_7_1);
|
||||
assert!(!config(Codec::Ac3, CodingMode::DualMono, false).channel_layout().is_ordered());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dec3_describes_dependent_rear_pair_and_aggregate_rate() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Independently verified against a Dolby-hosted 48k/768k 7.1 sample's
|
||||
@@ -302,24 +155,6 @@ fn actual_decoder_positions_satisfy_all_three_ac3_bit_budgets() -> Result<(), Bo
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lfe_final_nonzero_input_is_chunk_invariant() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let cfg = config(Codec::Eac3, CodingMode::ThreeFrontTwoSurround, true);
|
||||
let mut input = vec![vec![0.0; 1537]; 6];
|
||||
input[3][1536] = 0.75;
|
||||
let mut one = Encoder::new(cfg)?;
|
||||
let mut a = one.push(&input.iter().map(Vec::as_slice).collect::<Vec<_>>())?;
|
||||
a.extend(one.finish()?.packets);
|
||||
let mut two = Encoder::new(cfg)?;
|
||||
let mut b = Vec::new();
|
||||
for range in [0..1, 1..255, 255..1536, 1536..1537] {
|
||||
b.extend(two.push(&input.iter().map(|p| &p[range.clone()]).collect::<Vec<_>>())?);
|
||||
}
|
||||
b.extend(two.finish()?.packets);
|
||||
assert_eq!(a.iter().map(|p| &p.data).collect::<Vec<_>>(), b.iter().map(|p| &p.data).collect::<Vec<_>>());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transient_adjacent_tone_refreshes_exponents_within_the_frame() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Independent QC localized a previous shared-six-block exponent envelope's
|
||||
@@ -379,10 +214,3 @@ fn surround_compatibility_downmix_retains_correlated_signal_headroom() -> Result
|
||||
assert!(left.iter().all(|v| v.abs() < 1.05));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encoder_errors_convert_to_audio_errors() {
|
||||
let bad = Config { codec: Codec::Ac3, sample_rate: 22_050, bitrate_kbps: 192, mode: CodingMode::Stereo, lfe: false };
|
||||
let made: crate::Result<Encoder> = Encoder::new(bad).map_err(Into::into);
|
||||
assert!(matches!(made, Err(crate::AudioError::Encode(m)) if m.contains("sample rate")));
|
||||
}
|
||||
Binary file not shown.
@@ -190,63 +190,6 @@ mod tests {
|
||||
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x39, 0x93,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn seven_one_rejects_valid_independent_prefix_before_audio_decode() -> Result<()> {
|
||||
assert!(validate(&PRIMARY)?.1.is_none());
|
||||
let mut decoder = ProgrammeDecoder::new(ChannelLayout::SURROUND_7_1);
|
||||
assert_eq!(decoder.decode(&PRIMARY).err(), Some(Error::Invalid("programme does not match the expected speaker layout")));
|
||||
assert!(decoder.topology.is_none());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_dependency_order_frame_bounds_and_crc() -> Result<()> {
|
||||
let mut au = PRIMARY.to_vec();
|
||||
au.extend_from_slice(&DEPENDENT);
|
||||
assert!(validate(&au)?.1.is_some());
|
||||
assert!(validate(&DEPENDENT).is_err());
|
||||
assert!(validate(&au[..63]).is_err());
|
||||
au.push(0);
|
||||
assert!(validate(&au).is_err());
|
||||
au.pop();
|
||||
au[55] ^= 1;
|
||||
assert!(validate(&au).is_err());
|
||||
let mut duplicate = PRIMARY.to_vec();
|
||||
duplicate.extend_from_slice(&PRIMARY);
|
||||
assert!(validate(&duplicate).is_err());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn changed_dependent(bit: usize, width: usize, value: u16) -> Vec<u8> {
|
||||
let mut frame = DEPENDENT;
|
||||
for i in 0..width {
|
||||
let at = bit + i;
|
||||
let mask = 1 << (7 - at % 8);
|
||||
frame[at / 8] = (frame[at / 8] & !mask) | if value & (1 << (width - 1 - i)) != 0 { mask } else { 0 };
|
||||
}
|
||||
let crc = crc16(&frame[2..30]);
|
||||
frame[30..].copy_from_slice(&crc.to_be_bytes());
|
||||
let mut au = PRIMARY.to_vec();
|
||||
au.extend_from_slice(&frame);
|
||||
au
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_crc_valid_but_inconsistent_programme_descriptions() {
|
||||
// Fields are normative bit offsets in the independent structural BSI fixture.
|
||||
let wrong_map = changed_dependent(60, 16, 0x1800);
|
||||
assert_eq!(validate(&wrong_map).err(), Some(Error::Unsupported("dependent channel map must be Ls Rs Lrs Rrs".into())));
|
||||
let missing_last_marker = changed_dependent(50, 1, 0);
|
||||
assert_eq!(validate(&missing_last_marker).err(), Some(Error::Invalid("last dependent substream must signal compre")));
|
||||
let wrong_rate = changed_dependent(32, 2, 2);
|
||||
assert_eq!(validate(&wrong_rate).err(), Some(Error::Invalid("dependent rate or block count differs from independent")));
|
||||
let short_frame = changed_dependent(34, 2, 0);
|
||||
assert_eq!(validate(&short_frame).err(), Some(Error::Unsupported("programme decoder requires full-rate six-block E-AC-3 bsid 16".into())));
|
||||
let mut decoder = ProgrammeDecoder::new(ChannelLayout::SURROUND_7_1);
|
||||
decoder.reset();
|
||||
assert_eq!(decoder.expected_layout, ChannelLayout::SURROUND_7_1);
|
||||
}
|
||||
|
||||
#[cfg(feature = "eac3-encode")]
|
||||
#[test]
|
||||
fn explicit_map_overrides_dependent_acmod_speaker_order() -> std::result::Result<(), Box<dyn std::error::Error>> {
|
||||
@@ -287,23 +230,4 @@ mod tests {
|
||||
assert!(matches!(result, Ok(Err(_))), "corrupt bit {bit}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dependent_replaces_downmix_and_labels_rears() -> Result<()> {
|
||||
let primary = (0..6).map(|c| vec![c as f32; 1536]).collect();
|
||||
let dependent = (10..14).map(|c| vec![c as f32; 1536]).collect();
|
||||
let result = assemble_7_1(primary, dependent)?;
|
||||
assert_eq!(result.iter().map(|c| c[0]).collect::<Vec<_>>(), [0., 1., 2., 3., 12., 13., 10., 11.]);
|
||||
assert_eq!(ChannelLayout::SURROUND_7_1.mask(), Some(0x63f));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_programme_never_produces_partial_channels() {
|
||||
assert!(assemble_7_1(vec![vec![0.; 1536]; 6], vec![vec![0.; 1535]; 4]).is_err());
|
||||
let mut decoder = ProgrammeDecoder::new(ChannelLayout::SURROUND_7_1);
|
||||
decoder.topology = Some((48_000, 7, true, true));
|
||||
assert!(decoder.decode(&[0; 8193]).is_err());
|
||||
assert!(decoder.topology.is_none());
|
||||
}
|
||||
}
|
||||
@@ -48,24 +48,3 @@ pub(crate) const HTH: [[u16; 50]; 3] = [
|
||||
880, 864, 848, 832, 816, 800, 784, 768, 752, 752, 752, 768, 784, 816, 848, 960, 1040, 1136, 1184, 1120, 1088, 1104, 1248,
|
||||
],
|
||||
];
|
||||
/// Table 7.33 as printed (5 decimals), for checking the computed window.
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::approx_constant)]
|
||||
pub(crate) const WINDOW_TABLE: [f32; 256] = [
|
||||
0.00014, 0.00024, 0.00037, 0.00051, 0.00067, 0.00086, 0.00107, 0.0013, 0.00157, 0.00187, 0.0022, 0.00256, 0.00297, 0.00341, 0.0039, 0.00443,
|
||||
0.00501, 0.00564, 0.00632, 0.00706, 0.00785, 0.00871, 0.00962, 0.01061, 0.01166, 0.01279, 0.01399, 0.01526, 0.01662, 0.01806, 0.01959, 0.02121,
|
||||
0.02292, 0.02472, 0.02662, 0.02863, 0.03073, 0.03294, 0.03527, 0.0377, 0.04025, 0.04292, 0.04571, 0.04862, 0.05165, 0.05481, 0.0581, 0.06153,
|
||||
0.06508, 0.06878, 0.07261, 0.07658, 0.08069, 0.08495, 0.08935, 0.09389, 0.09859, 0.10343, 0.10842, 0.11356, 0.11885, 0.12429, 0.12988, 0.13563,
|
||||
0.14152, 0.14757, 0.15376, 0.16011, 0.16661, 0.17325, 0.18005, 0.18699, 0.19407, 0.2013, 0.20867, 0.21618, 0.22382, 0.23161, 0.23952, 0.24757,
|
||||
0.25574, 0.26404, 0.27246, 0.281, 0.28965, 0.29841, 0.30729, 0.31626, 0.32533, 0.3345, 0.34376, 0.35311, 0.36253, 0.37204, 0.38161, 0.39126,
|
||||
0.40096, 0.41072, 0.42054, 0.4304, 0.4403, 0.45023, 0.4602, 0.47019, 0.4802, 0.49022, 0.50025, 0.51028, 0.52031, 0.53033, 0.54033, 0.55031,
|
||||
0.56026, 0.57019, 0.58007, 0.58991, 0.5997, 0.60944, 0.61912, 0.62873, 0.63827, 0.64774, 0.65713, 0.66643, 0.67564, 0.68476, 0.69377, 0.70269,
|
||||
0.7115, 0.72019, 0.72877, 0.73723, 0.74557, 0.75378, 0.76186, 0.76981, 0.77762, 0.7853, 0.79283, 0.80022, 0.80747, 0.81457, 0.82151, 0.82831,
|
||||
0.83496, 0.84145, 0.84779, 0.85398, 0.86001, 0.86588, 0.8716, 0.87716, 0.88257, 0.88782, 0.89291, 0.89785, 0.90264, 0.90728, 0.91176, 0.9161,
|
||||
0.92028, 0.92432, 0.92822, 0.93197, 0.93558, 0.93906, 0.9424, 0.9456, 0.94867, 0.95162, 0.95444, 0.95713, 0.95971, 0.96217, 0.96451, 0.96674,
|
||||
0.96887, 0.97089, 0.97281, 0.97463, 0.97635, 0.97799, 0.97953, 0.98099, 0.98236, 0.98366, 0.98488, 0.98602, 0.9871, 0.98811, 0.98905, 0.98994,
|
||||
0.99076, 0.99153, 0.99225, 0.99291, 0.99353, 0.99411, 0.99464, 0.99513, 0.99558, 0.996, 0.99639, 0.99674, 0.99706, 0.99736, 0.99763, 0.99788,
|
||||
0.99811, 0.99831, 0.9985, 0.99867, 0.99882, 0.99895, 0.99908, 0.99919, 0.99929, 0.99938, 0.99946, 0.99953, 0.99959, 0.99965, 0.99969, 0.99974,
|
||||
0.99978, 0.99981, 0.99984, 0.99986, 0.99988, 0.9999, 0.99992, 0.99993, 0.99994, 0.99995, 0.99996, 0.99997, 0.99998, 0.99998, 0.99998, 0.99999,
|
||||
0.99999, 0.99999, 0.99999, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0,
|
||||
];
|
||||
@@ -1,77 +1,5 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn computed_window_matches_table_7_33() {
|
||||
let w = window();
|
||||
for (n, (&a, &b)) in w.iter().zip(tables::WINDOW_TABLE.iter()).enumerate() {
|
||||
assert!((a - b).abs() <= 6e-6, "w[{n}] = {a}, table {b}");
|
||||
}
|
||||
// princen-bradley: w[n]² + w[255-n]²... (the second half mirrors): w[n]² + w[511-n]² = 1
|
||||
for n in 0..256 {
|
||||
let m = w[255 - n];
|
||||
assert!((w[n] * w[n] + m * m - 1.0).abs() < 1e-5);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tables_are_consistent() {
|
||||
// masktab maps every bin of a band to that band
|
||||
for b in 0..50 {
|
||||
for bin in tables::BNDTAB[b] as usize..(tables::BNDTAB[b] + tables::BNDSZ[b]) as usize {
|
||||
if bin < 253 {
|
||||
assert_eq!(tables::MASKTAB[bin] as usize, b, "bin {bin}");
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(tables::BNDTAB[49] as usize + tables::BNDSZ[49] as usize, 253);
|
||||
// latab is non-increasing from 64 to 0
|
||||
assert_eq!(tables::LATAB[0], 64);
|
||||
assert!(tables::LATAB.windows(2).all(|w| w[0] >= w[1]));
|
||||
assert!(tables::BAPTAB.windows(2).all(|w| w[0] <= w[1]));
|
||||
assert_eq!((tables::BAPTAB[0], tables::BAPTAB[63]), (0, 15));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_fft_matches_the_definition() {
|
||||
for n in [64usize, 128] {
|
||||
let re0: Vec<f32> = (0..n).map(|i| ((i * 7 + 3) % 11) as f32 - 5.0).collect();
|
||||
let im0: Vec<f32> = (0..n).map(|i| ((i * 5 + 1) % 13) as f32 - 6.0).collect();
|
||||
let (mut re, mut im) = (re0.clone(), im0.clone());
|
||||
ifft(&mut re, &mut im);
|
||||
for t in 0..n {
|
||||
let (mut sr, mut si) = (0f64, 0f64);
|
||||
for k in 0..n {
|
||||
let a = 2.0 * std::f64::consts::PI * (k * t) as f64 / n as f64;
|
||||
sr += re0[k] as f64 * a.cos() - im0[k] as f64 * a.sin();
|
||||
si += re0[k] as f64 * a.sin() + im0[k] as f64 * a.cos();
|
||||
}
|
||||
assert!((sr - re[t] as f64).abs() < 1e-3 && (si - im[t] as f64).abs() < 1e-3, "n {n} t {t}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers_and_gains() {
|
||||
// 48 kHz, 448 kb/s, 3/2 + LFE: bsid 8, bsmod 0, acmod 7 (cmixlev, surmixlev), lfeon
|
||||
let b = [0x0B, 0x77, 0, 0, 30, 8 << 3, 0b1110_0001, 0b0100_0000];
|
||||
let h = parse_header(&b).unwrap();
|
||||
assert_eq!((h.sample_rate, h.bitrate_kbps, h.frame_bytes, h.acmod, h.lfeon, h.channels()), (48_000, 448, 1792, 7, true, 6));
|
||||
assert_eq!(parse_header(&[0x0B, 0x77, 0, 0, 0, 17 << 3, 0, 0]), Err(Error::Unsupported("bsid 17".into())));
|
||||
assert_eq!(dynrng_gain(0), 1.0);
|
||||
assert!((dynrng_gain(0b1110_0000) - 0.5).abs() < 1e-7);
|
||||
assert!((dynrng_gain(0b0111_1111) - 16.0 * 63.0 / 64.0).abs() < 1e-5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_order() {
|
||||
let ch = |n: usize| (0..n).map(|i| vec![i as f32]).collect::<Vec<_>>();
|
||||
let ids = |v: Vec<Vec<f32>>| v.iter().map(|c| c[0] as usize).collect::<Vec<_>>();
|
||||
// coded L C R Ls Rs LFE → L R C LFE Ls Rs
|
||||
assert_eq!(ids(wav_order(ch(6), 7, true)), vec![0, 2, 1, 5, 3, 4]);
|
||||
assert_eq!(ids(wav_order(ch(3), 2, true)), vec![0, 1, 2]);
|
||||
assert_eq!(ids(wav_order(ch(1), 1, false)), vec![0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_never_panics() {
|
||||
let mut d = Decoder::new();
|
||||
@@ -146,66 +74,6 @@ fn eac3_frame(strmtyp: u32, substreamid: u32, words: u32, numblkscod: u32, acmod
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eac3_headers() {
|
||||
let f = eac3_frame(0, 0, 384, 3, 2, |_| {});
|
||||
let h = parse_header(&f).unwrap();
|
||||
assert_eq!((h.sample_rate, h.blocks, h.samples(), h.frame_bytes, h.bitrate_kbps, h.channels()), (48_000, 6, 1536, 768, 192, 2));
|
||||
assert!(h.is_eac3() && h.is_primary());
|
||||
// one block per syncframe: 256 samples
|
||||
let h = parse_header(&eac3_frame(0, 0, 100, 0, 7, |_| {})).unwrap();
|
||||
assert_eq!((h.blocks, h.samples(), h.channels(), h.bitrate_kbps), (1, 256, 5, 300));
|
||||
// reduced sample rate (fscod 3, fscod2 1): six blocks at 22.05 kHz
|
||||
let mut f = eac3_frame(0, 0, 384, 0, 2, |_| {});
|
||||
f[4] = 0b1101_0100;
|
||||
let h = parse_header(&f).unwrap();
|
||||
assert_eq!((h.sample_rate, h.blocks, h.acmod), (22_050, 6, 2));
|
||||
f[4] = 0b1111_0100;
|
||||
assert_eq!(parse_header(&f), Err(Error::Invalid("reserved fscod2")));
|
||||
// a dependent substream and a second independent program are recognised and skipped
|
||||
let mut d = Decoder::new();
|
||||
for (strmtyp, id) in [(1, 0), (0, 1)] {
|
||||
let f = eac3_frame(strmtyp, id, 64, 3, 2, |_| {});
|
||||
let out = d.decode(&f).unwrap();
|
||||
assert!(!out.header.is_primary() && out.channels.is_empty());
|
||||
}
|
||||
assert_eq!(parse_header(&eac3_frame(3, 0, 64, 3, 2, |_| {})), Err(Error::Unsupported("reserved E-AC-3 stream type 3".into())));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eac3_tools_we_do_not_decode_are_refused() {
|
||||
// mono, six blocks, AHT enabled and used: chexpstr D15 then reuse, so chahtinu is sent
|
||||
let aht = eac3_frame(0, 0, 64, 3, 1, |w| {
|
||||
w.put(1, 1); // expstre
|
||||
w.put(1, 1); // ahte
|
||||
w.put(2, 0); // snroffststr
|
||||
w.put(8, 0); // transproce … spxattene
|
||||
w.put(2, 1); // chexpstr[0] = D15
|
||||
w.put(10, 0); // chexpstr[1..6] = reuse
|
||||
w.put(5, 0); // convexpstr
|
||||
w.put(1, 1); // chahtinu
|
||||
});
|
||||
assert_eq!(Decoder::new().decode(&aht).unwrap_err(), Error::Unsupported("E-AC-3 adaptive hybrid transform".into()));
|
||||
// stereo with coupling in block 0 using enhanced coupling
|
||||
let ecpl = eac3_frame(0, 0, 64, 3, 2, |w| {
|
||||
w.put(1, 1); // expstre
|
||||
w.put(1, 0); // ahte
|
||||
w.put(2, 0); // snroffststr
|
||||
w.put(8, 0);
|
||||
w.put(1, 1); // cplinu[0]
|
||||
w.put(5, 0); // cplstre[1..6]
|
||||
w.put(6, 0b01_01_01); // block 0: cplexpstr, chexpstr × 2
|
||||
w.put(30, 0); // blocks 1-5: reuse
|
||||
w.put(10, 0); // convexpstr
|
||||
w.put(10, 0); // frmcsnroffst, frmfsnroffst
|
||||
w.put(1, 0); // blkstrtinfoe
|
||||
w.put(1, 0); // dynrnge
|
||||
w.put(1, 0); // spxinu
|
||||
w.put(1, 1); // ecplinu
|
||||
});
|
||||
assert_eq!(Decoder::new().decode(&ecpl).unwrap_err(), Error::Unsupported("E-AC-3 enhanced coupling".into()));
|
||||
}
|
||||
|
||||
/// A mono E-AC-3 syncframe of one block (256 samples) that sends exponents (all 10, bandwidth
|
||||
/// code 0) when `new_exps`, else reuses the last ones. Zero SNR offsets allocate no bits: every
|
||||
/// coefficient is dither.
|
||||
@@ -247,53 +115,6 @@ fn eac3_single_block_frames_reuse_exponents_across_syncframes() {
|
||||
assert_eq!(peak(&c.channels[0]), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn eac3_garbage_never_panics() {
|
||||
let mut d = Decoder::new();
|
||||
let mut x = 0x5EEDu32;
|
||||
for len in [8usize, 40, 300, 1500, 4096] {
|
||||
for _ in 0..300 {
|
||||
let mut f: Vec<u8> = (0..len)
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
x as u8
|
||||
})
|
||||
.collect();
|
||||
f[0] = 0x0B;
|
||||
f[1] = 0x77;
|
||||
// independent substream 0, frmsiz within the buffer, bsid 11-16
|
||||
let words = (len / 2).clamp(4, 2048) - 1;
|
||||
f[2] = (words >> 8) as u8 & 7;
|
||||
f[3] = words as u8;
|
||||
f[5] = (f[5] & 7) | ((11 + x % 6) as u8) << 3;
|
||||
let _ = d.decode(&f);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Golden hashes of the decoder output, so that a change of the bit reader cannot change a
|
||||
/// decoded sample or an error. The values were made with the private bit-by-bit reader, before it
|
||||
/// was replaced by the shared one: every frame below is decoded with a
|
||||
/// fresh decoder, and every output sample bit (as `f32::to_bits`, channel after channel) and every
|
||||
/// error (its `Debug` text) goes into an FNV-1a 64 hash. The frames are deterministic: valid
|
||||
/// AC-3 and E-AC-3 syncframe headers (all fscod, frmsizecod, bsid, acmod and lfeon values in
|
||||
/// the tables below) with random, zero-heavy or all-ones payload bits, plus truncated and
|
||||
/// bit-flipped variants of the same frames.
|
||||
struct Fnv(u64);
|
||||
|
||||
impl Fnv {
|
||||
fn new() -> Self {
|
||||
Fnv(0xcbf2_9ce4_8422_2325)
|
||||
}
|
||||
fn bytes(&mut self, b: &[u8]) {
|
||||
for &x in b {
|
||||
self.0 = (self.0 ^ u64::from(x)).wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Rng(u32);
|
||||
|
||||
impl Rng {
|
||||
@@ -315,147 +136,6 @@ fn payload_byte(rng: &mut Rng, flavour: usize) -> u8 {
|
||||
}
|
||||
}
|
||||
|
||||
/// See `synthetic_frames`: 12 syncframes, back to back.
|
||||
const REAL_FRAMES: &[u8] = include_bytes!("golden_frames.bin");
|
||||
|
||||
fn synthetic_frames() -> Vec<Vec<u8>> {
|
||||
let mut rng = Rng(0x00C0_FFEE);
|
||||
let mut frames = Vec::new();
|
||||
// AC-3: bsid 8 and the half / quarter rate variants 9 and 10, every fscod and a spread of
|
||||
// frmsizecod, acmod 0 to 7, lfeon off and on.
|
||||
for n in 0..1200usize {
|
||||
let fscod = n % 3;
|
||||
let frmsizecod = (n * 7 + n / 3) % 38;
|
||||
let bsid = [8u8, 8, 8, 9, 10, 6][n % 6];
|
||||
let acmod = (n / 3) % 8;
|
||||
let lfeon = (n / 24) % 2;
|
||||
let Ok(h) = parse_header(&[0x0B, 0x77, 0, 0, ((fscod << 6) | frmsizecod) as u8, bsid << 3, (acmod as u8) << 5, 0]) else { continue };
|
||||
let mut f = vec![0u8; h.frame_bytes];
|
||||
for b in f.iter_mut() {
|
||||
*b = payload_byte(&mut rng, n);
|
||||
}
|
||||
f[0] = 0x0B;
|
||||
f[1] = 0x77;
|
||||
f[4] = ((fscod << 6) | frmsizecod) as u8;
|
||||
f[5] = bsid << 3;
|
||||
// acmod in the top 3 bits; the mix-level bits that follow depend on acmod and are random
|
||||
f[6] = (f[6] & 0x1F) | ((acmod as u8) << 5);
|
||||
// lfeon follows the optional 2-bit fields (cmixlev, surmixlev, dsurmod)
|
||||
let mut at = 3;
|
||||
if acmod & 1 != 0 && acmod != 1 {
|
||||
at += 2;
|
||||
}
|
||||
if acmod & 4 != 0 {
|
||||
at += 2;
|
||||
}
|
||||
if acmod == 2 {
|
||||
at += 2;
|
||||
}
|
||||
let bit = 48 + at;
|
||||
f[bit / 8] = (f[bit / 8] & !(0x80 >> (bit % 8))) | ((lfeon as u8) * (0x80 >> (bit % 8)));
|
||||
frames.push(f);
|
||||
}
|
||||
// E-AC-3: strmtyp 0 / 1 / 2, fscod 0..=3 (3 = reduced rate), numblkscod, acmod, lfeon
|
||||
for n in 0..800usize {
|
||||
let words = 24 + (n * 13) % 400;
|
||||
let fscod = n % 4;
|
||||
let blk = (n / 4) % 4;
|
||||
let acmod = (n / 16) % 8;
|
||||
let lfeon = (n / 128) % 2;
|
||||
let strmtyp = [0u32, 0, 0, 1, 2][n % 5];
|
||||
let bsid = 11 + (n % 6) as u32;
|
||||
let mut f = vec![0u8; words * 2];
|
||||
for b in f.iter_mut() {
|
||||
*b = payload_byte(&mut rng, n);
|
||||
}
|
||||
let head: u32 = (strmtyp << 30)
|
||||
| (((n % 7) as u32) << 27)
|
||||
| (((words - 1) as u32) << 16)
|
||||
| ((fscod as u32) << 14)
|
||||
| ((if fscod == 3 { (n / 7 % 3) as u32 } else { blk as u32 }) << 12)
|
||||
| ((acmod as u32) << 9)
|
||||
| ((lfeon as u32) << 8)
|
||||
| (bsid << 3)
|
||||
| (f[5] as u32 & 7);
|
||||
f[0] = 0x0B;
|
||||
f[1] = 0x77;
|
||||
f[2..6].copy_from_slice(&head.to_be_bytes());
|
||||
frames.push(f);
|
||||
}
|
||||
// real frames (two of each stream, made with ffmpeg's ac3 / eac3 encoders from tones and noise:
|
||||
// mono 64k 32 kHz, coupled stereo 96k 44.1 kHz, noise stereo 96k, 5.1 192k; E-AC-3 noise
|
||||
// stereo 96k and 5.1 192k) reach exponents, bit allocation and mantissas of every block, which
|
||||
// random payload bits almost never do. Each one is decoded as is, with 60 bit-flipped copies
|
||||
// and cut at every 16th byte.
|
||||
let mut p = 0;
|
||||
while let Ok(h) = parse_header(&REAL_FRAMES[p..]) {
|
||||
let f = &REAL_FRAMES[p..p + h.frame_bytes];
|
||||
p += h.frame_bytes;
|
||||
frames.push(f.to_vec());
|
||||
for _ in 0..60 {
|
||||
let mut m = f.to_vec();
|
||||
for _ in 0..1 + rng.next() % 3 {
|
||||
let bit = 64 + rng.next() as usize % (m.len() * 8 - 64);
|
||||
m[bit / 8] ^= 0x80 >> (bit % 8);
|
||||
}
|
||||
frames.push(m);
|
||||
}
|
||||
for cut in (8..f.len()).step_by(16) {
|
||||
frames.push(f[..cut].to_vec());
|
||||
}
|
||||
}
|
||||
// truncated and bit-flipped variants of every 5th frame
|
||||
let base = frames.clone();
|
||||
for (i, f) in base.iter().enumerate().step_by(5) {
|
||||
let mut t = f.clone();
|
||||
t.truncate(rng.next() as usize % f.len());
|
||||
frames.push(t);
|
||||
let mut m = f.clone();
|
||||
for _ in 0..1 + rng.next() % 6 {
|
||||
let bit = rng.next() as usize % (m.len() * 8);
|
||||
m[bit / 8] ^= 0x80 >> (bit % 8);
|
||||
}
|
||||
frames.push(m);
|
||||
// cut the payload to just a few bytes after the header, so that the reads run past the end
|
||||
let mut s = f.clone();
|
||||
s.truncate((8 + i % 40).min(f.len()));
|
||||
frames.push(s);
|
||||
}
|
||||
frames
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_output_matches_golden_hashes() {
|
||||
let (mut all, mut ok, mut err, mut audio) = (Fnv::new(), 0usize, 0usize, 0usize);
|
||||
for (i, f) in synthetic_frames().iter().enumerate() {
|
||||
let mut dec = Decoder::new();
|
||||
// decode each frame twice with the same decoder: the second pass also covers the
|
||||
// E-AC-3 carry-over and the overlap state
|
||||
for _ in 0..2 {
|
||||
match dec.decode(f) {
|
||||
Ok(d) => {
|
||||
ok += 1;
|
||||
audio += usize::from(!d.channels.is_empty());
|
||||
all.bytes(&[1]);
|
||||
for ch in &d.channels {
|
||||
for s in ch {
|
||||
all.bytes(&s.to_bits().to_le_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
err += 1;
|
||||
all.bytes(format!("{i}:{e:?}").as_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!("golden: ok {ok} ({audio} with audio) err {err} hash {:#018x}", all.0);
|
||||
assert_eq!((ok, err, all.0), GOLDEN);
|
||||
}
|
||||
|
||||
const GOLDEN: (usize, usize, u64) = (2960, 7024, 0x1dc9_31d6_0e89_e8c8);
|
||||
|
||||
/// The private reader this crate used before it moved to the shared `BitReader`, verbatim.
|
||||
struct OldBits<'a> {
|
||||
d: &'a [u8],
|
||||
|
||||
@@ -246,31 +246,6 @@ mod tests {
|
||||
use super::super::bits::{BitReader, BitSink, BitWriter};
|
||||
use super::*;
|
||||
|
||||
fn roundtrip(values: &[i32], bits: u32) {
|
||||
let mut w = BitWriter::new();
|
||||
compress(AgParams::standard(), values, &mut w, bits).unwrap();
|
||||
let len = w.bit_len();
|
||||
let bytes = w.into_bytes();
|
||||
let mut r = BitReader::new(&bytes);
|
||||
let mut out = vec![0; values.len()];
|
||||
decompress(AgParams::standard(), &mut r, &mut out, bits).unwrap();
|
||||
assert_eq!(out, values);
|
||||
assert_eq!(r.position(), len);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn residuals_roundtrip() {
|
||||
roundtrip(&[0, 1, -1, 2, -2, 100, -100, 30000, -32768, 32767], 16);
|
||||
roundtrip(&[0; 300], 16);
|
||||
let mut v = vec![0; 70_000];
|
||||
v[0] = 5;
|
||||
v[69_999] = -3;
|
||||
roundtrip(&v, 16);
|
||||
let wide: Vec<i32> = (0..500).map(|i| ((i * 7919) % 65_536 - 32_768) << 8).collect();
|
||||
roundtrip(&wide, 25);
|
||||
roundtrip(&[i32::MAX >> 1, i32::MIN >> 1, 0, 0, 0, 1], 32);
|
||||
}
|
||||
|
||||
/// The largest escaped magnitude, 0xffffffff, is i32::MIN (the reference wraps it to 0).
|
||||
#[test]
|
||||
fn the_full_width_escape_decodes_to_the_minimum() {
|
||||
@@ -282,15 +257,4 @@ mod tests {
|
||||
decompress(AgParams::standard(), &mut BitReader::new(&bytes), &mut out, 32).unwrap();
|
||||
assert_eq!(out, [i32::MIN]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_stream_is_an_error() {
|
||||
let mut w = BitWriter::new();
|
||||
let values: Vec<i32> = (0..64).map(|i| i * 1000 - 32_000).collect();
|
||||
compress(AgParams::standard(), &values, &mut w, 16).unwrap();
|
||||
let bytes = w.into_bytes();
|
||||
let mut r = BitReader::new(&bytes[..bytes.len() / 2]);
|
||||
let mut out = vec![0; values.len()];
|
||||
assert!(decompress(AgParams::standard(), &mut r, &mut out, 16).is_err());
|
||||
}
|
||||
}
|
||||
@@ -189,44 +189,3 @@ impl BitSink for BitCounter {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn writer_and_reader_agree() {
|
||||
let mut w = BitWriter::new();
|
||||
w.put(0b101, 3);
|
||||
w.put(0xABCD, 16);
|
||||
w.put(0xDEAD_BEEF, 32);
|
||||
w.put(1, 1);
|
||||
assert_eq!(w.bit_len(), 52);
|
||||
let bytes = w.into_bytes();
|
||||
let mut r = BitReader::new(&bytes);
|
||||
assert_eq!(r.read(3), Ok(0b101));
|
||||
assert_eq!(r.read(16), Ok(0xABCD));
|
||||
assert_eq!(r.read(32), Ok(0xDEAD_BEEF));
|
||||
assert_eq!(r.read(1), Ok(1));
|
||||
assert_eq!(r.read(4), Ok(0));
|
||||
assert_eq!(r.read(1), Err(Error::Eof));
|
||||
assert_eq!(r.peek(32), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncate_clears_the_dropped_bits() {
|
||||
let mut w = BitWriter::new();
|
||||
w.put(0xFFFF, 16);
|
||||
w.truncate(5);
|
||||
w.put(0, 3);
|
||||
assert_eq!(w.into_bytes(), vec![0xF8]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sign_extension() {
|
||||
assert_eq!(sign_extend(0xF, 4), -1);
|
||||
assert_eq!(sign_extend(0x7, 4), 7);
|
||||
assert_eq!(sign_extend(0x8000_0000, 32), i32::MIN);
|
||||
assert_eq!(sign_extend(5, 0), 0);
|
||||
}
|
||||
}
|
||||
@@ -282,10 +282,6 @@ pub(crate) fn header_frames(packet: &[u8], frame_length: u64) -> Option<u64> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn stereo16() -> Vec<u8> {
|
||||
SpecificConfig::new(44_100, 2, 16, 4096).to_cookie()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cookies_out_of_range_are_refused() {
|
||||
let ok = SpecificConfig::new(44_100, 2, 16, 4096);
|
||||
@@ -302,24 +298,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_escaped_stereo_frame() {
|
||||
// CPE, instance 0, 12 zero bits, flags: partial + escape, 2 frames, then L R L R.
|
||||
let mut w = super::super::bits::BitWriter::new();
|
||||
use super::super::bits::BitSink;
|
||||
w.put(ID_CPE, 3);
|
||||
w.put(0, 4);
|
||||
w.put(0, 12);
|
||||
w.put(0b1001, 4);
|
||||
w.put(2, 32);
|
||||
for s in [1i32, -1, 32767, -32768] {
|
||||
w.put(s as u32, 16);
|
||||
}
|
||||
w.put(ID_END, 3);
|
||||
let mut dec = Decoder::new(&stereo16()).unwrap();
|
||||
assert_eq!(dec.decode(&w.into_bytes()).unwrap(), vec![vec![1, 32767], vec![-1, -32768]]);
|
||||
}
|
||||
|
||||
/// An escaped mono packet that lost its last byte keeps every sample but not its end tag.
|
||||
#[test]
|
||||
fn a_packet_without_its_end_tag_is_an_error() {
|
||||
@@ -344,27 +322,6 @@ mod tests {
|
||||
assert_eq!(dec.decode(&w.into_bytes()).unwrap(), vec![vec![9]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frames_of_a_packet_come_from_its_header() {
|
||||
use super::super::bits::{BitSink, BitWriter};
|
||||
let dec = Decoder::new(&SpecificConfig::new(44_100, 2, 16, 4096).to_cookie()).unwrap();
|
||||
let header = |flags: u32, frames: Option<u32>| {
|
||||
let mut w = BitWriter::new();
|
||||
for (value, bits) in [(ID_CPE, 3), (0, 4), (0, 12), (flags, 4)] {
|
||||
w.put(value, bits);
|
||||
}
|
||||
if let Some(n) = frames {
|
||||
w.put(n, 32);
|
||||
}
|
||||
w.into_bytes()
|
||||
};
|
||||
assert_eq!(dec.packet_frames(&header(0b1001, Some(300))), Some(300));
|
||||
assert_eq!(dec.packet_frames(&header(0b0001, None)), Some(4096));
|
||||
assert_eq!(dec.packet_frames(&header(0b1001, Some(5000))), None);
|
||||
assert_eq!(dec.packet_frames(&header(0b1001, None)), None);
|
||||
assert_eq!(dec.packet_frames(&[0xE0]), None); // ID_END first
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_packets_fail_or_decode_without_panicking() {
|
||||
let mut dec = Decoder::new(&SpecificConfig::new(48_000, 8, 24, 4096).to_cookie()).unwrap();
|
||||
|
||||
@@ -164,33 +164,3 @@ pub(crate) fn unpc_first_order_in_place(buf: &mut [i32], num: usize, chanbits: u
|
||||
buf[j] = wrap(buf[j].wrapping_add(buf[j - 1]), chanshift);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_predictor_inverts() {
|
||||
let input: Vec<i32> = (0..2000).map(|i: i32| ((i as f64 * 0.05).sin() * 20000.0) as i32 + (i * 31 % 17) - 8).collect();
|
||||
for numactive in [0, 1, 4, 8, 12, FIRST_ORDER] {
|
||||
for num in [0, 1, 3, 9, 2000] {
|
||||
let mut ce = [0i16; 32];
|
||||
init_coefs(&mut ce, DENSHIFT_DEFAULT);
|
||||
let mut cd = ce;
|
||||
let mut pc = vec![0; 2000];
|
||||
let mut out = vec![0; 2000];
|
||||
pc_block(&input, &mut pc, num, &mut ce, numactive, 16, DENSHIFT_DEFAULT);
|
||||
unpc_block(&pc, &mut out, num, &mut cd, numactive, 16, DENSHIFT_DEFAULT);
|
||||
assert_eq!(out[..num], input[..num], "numactive {numactive}, num {num}");
|
||||
assert_eq!(ce, cd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coefficient_start_values() {
|
||||
let mut c = [7i16; 16];
|
||||
init_coefs(&mut c, DENSHIFT_DEFAULT);
|
||||
assert_eq!(&c[..4], &[1216, -928, -64, 0]);
|
||||
}
|
||||
}
|
||||
@@ -563,18 +563,4 @@ mod tests {
|
||||
let mut dec = Decoder::new(&enc.cookie()).unwrap();
|
||||
assert_eq!(dec.decode(&p).unwrap(), vec![noise[..4096].to_vec()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_refused() {
|
||||
assert!(Encoder::new(EncoderConfig::new(44_100, 2, 8)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig::new(44_100, 9, 16)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig::new(44_100, 2, 16).with_frame_length(0)).is_err());
|
||||
let mut enc = Encoder::new(EncoderConfig::new(44_100, 2, 16).with_frame_length(16)).unwrap();
|
||||
assert!(enc.encode(&[&[0; 4]]).is_err());
|
||||
assert!(enc.encode(&[&[0; 4], &[0; 5]]).is_err());
|
||||
assert!(enc.encode(&[&[0; 17], &[0; 17]]).is_err());
|
||||
assert!(enc.encode(&[&[], &[]]).is_err());
|
||||
assert!(enc.encode(&[&[40_000], &[0]]).is_err());
|
||||
assert!(enc.encode(&[&[-32_768], &[32_767]]).is_ok());
|
||||
}
|
||||
}
|
||||
@@ -99,22 +99,3 @@ pub(crate) fn shift_mono(input: &[i32], pred_in: &mut [i32], shift_buf: &mut [u1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn matrixing_inverts() {
|
||||
let l: Vec<i32> = (0..100).map(|i| (i * 977 % 16_000_000) - 8_000_000).collect();
|
||||
let r: Vec<i32> = (0..100).map(|i| (i * 7919 % 16_000_000) - 8_000_000).collect();
|
||||
for (mixres, bytes) in [(0, 0), (1, 0), (2, 1), (4, 1), (3, 0)] {
|
||||
let (mut u, mut v, mut s) = (vec![0; 100], vec![0; 100], vec![0u16; 200]);
|
||||
let m = Mix { bits: 2, res: mixres };
|
||||
mix((&l, &r), (&mut u, &mut v), m, &mut s, bytes);
|
||||
let (mut l2, mut r2) = (vec![0; 100], vec![0; 100]);
|
||||
unmix((&u, &v), (&mut l2, &mut r2), m, &s, bytes, 24);
|
||||
assert_eq!((l2, r2), (l.clone(), r.clone()), "mixres {mixres}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,24 +293,6 @@ impl SpecificConfig {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn cookies_roundtrip() {
|
||||
let mut c = SpecificConfig::new(48_000, 6, 24, 4096);
|
||||
c.max_frame_bytes = 12_345;
|
||||
c.avg_bit_rate = 2_000_000;
|
||||
let bytes = c.to_cookie();
|
||||
assert_eq!(bytes.len(), 48);
|
||||
let mut parsed = SpecificConfig::parse(&bytes).unwrap();
|
||||
assert_eq!(parsed.channel_layout_tag, Some((124 << 16) | 6));
|
||||
assert!(parsed.has_standard_layout());
|
||||
parsed.channel_layout_tag = None;
|
||||
assert_eq!(parsed, c);
|
||||
assert_eq!(c.to_bytes(), bytes[..24]);
|
||||
let stereo = SpecificConfig::new(44_100, 2, 16, 4096).to_cookie();
|
||||
assert_eq!(stereo.len(), 24);
|
||||
assert_eq!(&stereo[..12], &[0, 0, 0x10, 0, 0, 16, 40, 10, 14, 2, 0, 255]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_little_endian_layout_tag_is_read() {
|
||||
// as Apple's reference encoder writes the tag of a 7.1 stream
|
||||
@@ -330,19 +312,4 @@ mod tests {
|
||||
assert!(SpecificConfig::parse(&wrapped[..30]).is_err());
|
||||
assert!(SpecificConfig::parse(&[0; 5]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_orders_are_permutations() {
|
||||
for n in 3..=8u8 {
|
||||
let order = wav_order(n).unwrap();
|
||||
let inverse = alac_order(n).unwrap();
|
||||
assert!((0..usize::from(n)).all(|i| inverse[order[i]] == i && order[inverse[i]] == i), "{n} channels");
|
||||
let mut sorted = order.to_vec();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(sorted, (0..usize::from(n)).collect::<Vec<_>>());
|
||||
assert_eq!(channel_mask(n).count_ones(), u32::from(n));
|
||||
let elements: usize = element_map(usize::from(n)).iter().map(|&e| if e == ID_CPE { 2 } else { 1 }).sum();
|
||||
assert_eq!(elements, usize::from(n));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -282,37 +282,3 @@ pub(crate) fn flac_assumed_mask(channels: usize) -> u32 {
|
||||
n => ChannelLayout::default_for(n as u16).mask().unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn speakers_follow_the_mask_in_wav_order() {
|
||||
assert_eq!(
|
||||
ChannelLayout::SURROUND_5_1_SIDE.speakers(),
|
||||
[Speaker::FrontLeft, Speaker::FrontRight, Speaker::FrontCenter, Speaker::Lfe, Speaker::SideLeft, Speaker::SideRight]
|
||||
);
|
||||
assert_eq!(ChannelLayout::SURROUND_7_1.index_of(Speaker::SideLeft), Some(6));
|
||||
assert_eq!(Speaker::SideRight.mask_bit(), 0x400);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_that_does_not_match_the_channels_is_unordered() {
|
||||
assert_eq!(ChannelLayout::from_mask_and_channels(0x3F, 6), ChannelLayout::SURROUND_5_1);
|
||||
assert!(!ChannelLayout::from_mask_and_channels(0x3, 4).is_ordered());
|
||||
assert!(!ChannelLayout::from_mask_and_channels(0, 4).is_ordered());
|
||||
assert!(!ChannelLayout::from_mask(1 << 20).is_ordered());
|
||||
assert_eq!(ChannelLayout::unordered(4).channels(), 4);
|
||||
assert!(ChannelLayout::unordered(4).speakers().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn defaults_and_names() {
|
||||
assert_eq!(ChannelLayout::default_for(6), ChannelLayout::SURROUND_5_1);
|
||||
assert!(!ChannelLayout::default_for(9).is_ordered());
|
||||
assert_eq!(ChannelLayout::default_for(2).to_string(), "stereo");
|
||||
assert_eq!(ChannelLayout::SURROUND_5_1_SIDE.to_string(), "5.1");
|
||||
assert_eq!(ChannelLayout::unordered(10).to_string(), "10 channels");
|
||||
}
|
||||
}
|
||||
+5
-13
@@ -479,17 +479,9 @@ impl Default for EncodeOptions {
|
||||
}
|
||||
}
|
||||
|
||||
// An encoder refusing its settings is an encode error, not damaged input.
|
||||
#[cfg(all(test, feature = "aac-encode"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[cfg(test)]
|
||||
extern crate self as craft_audio;
|
||||
|
||||
#[test]
|
||||
fn aac_encoder_settings_are_encode_errors() {
|
||||
let e = match aac::Encoder::new(aac::EncoderConfig::cbr(44_000, 2, 128_000)) {
|
||||
Err(e) => AudioError::from(e),
|
||||
Ok(_) => panic!("44 kHz is not an AAC rate"),
|
||||
};
|
||||
assert!(matches!(e, AudioError::Encode(_)), "{e}");
|
||||
}
|
||||
}
|
||||
#[cfg(test)]
|
||||
#[path = "../tests/main.rs"]
|
||||
mod integration;
|
||||
@@ -456,6 +456,3 @@ fn synthesize(v: &mut [f32; 1024], pos: &mut usize, n: &[[f32; 36]; 32], d: &[f3
|
||||
}
|
||||
*out = o;
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -1,250 +0,0 @@
|
||||
use super::*;
|
||||
use tables::window_half;
|
||||
|
||||
/// A frame header: MPEG-1 unless `lsf`, `layer` 1/2, no CRC, `bitrate_index`, `rate_index`
|
||||
/// (0: 44.1 kHz, 1: 48 kHz, 2: 32 kHz), `mode` 0-3 and `mode_extension`.
|
||||
fn header(lsf: bool, layer: u8, bitrate_index: u8, rate_index: u8, mode: u8, ext: u8) -> [u8; 4] {
|
||||
let version = if lsf { 0b10 } else { 0b11 };
|
||||
[0xFF, 0xE0 | version << 3 | (4 - layer) << 1 | 1, bitrate_index << 4 | rate_index << 2, mode << 6 | ext << 4]
|
||||
}
|
||||
|
||||
/// A frame of `header` with all-zero audio data: no subband has an allocation.
|
||||
fn silent(h: [u8; 4]) -> Vec<u8> {
|
||||
let mut f = h.to_vec();
|
||||
f.resize(parse_header(&h).unwrap().frame_bytes, 0);
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn headers() {
|
||||
// Layer II 48 kHz stereo 192 kbit/s: 144 * 192000 / 48000 = 576 bytes
|
||||
let h = parse_header(&header(false, 2, 10, 1, 0, 0)).unwrap();
|
||||
assert_eq!(
|
||||
(h.version, h.layer, h.bitrate_kbps, h.sample_rate, h.frame_bytes, h.channels(), h.samples()),
|
||||
(Version::Mpeg1, 2, 192, 48_000, 576, 2, 1152)
|
||||
);
|
||||
// ffmpeg's default for mono: Layer II 384 kbit/s, which ISO/IEC 11172-3 does not allow
|
||||
let h = parse_header(&header(false, 2, 14, 1, 3, 0)).unwrap();
|
||||
assert_eq!((h.bitrate_kbps, h.frame_bytes, h.mode, h.channels()), (384, 1152, Mode::Mono, 1));
|
||||
// Layer I 44.1 kHz 384 kbit/s with padding: (12 * 384000 / 44100 + 1) * 4 = 420
|
||||
let mut b = header(false, 1, 12, 0, 1, 2);
|
||||
b[2] |= 2;
|
||||
let h = parse_header(&b).unwrap();
|
||||
assert_eq!((h.layer, h.frame_bytes, h.samples(), h.mode, h.mode_extension, h.bound()), (1, 420, 384, Mode::JointStereo, 2, 12));
|
||||
// MPEG-2 Layer II 24 kHz 160 kbit/s: 144 * 160000 / 24000 = 960; Layer I 22.05 kHz 256 kbit/s
|
||||
let h = parse_header(&header(true, 2, 14, 1, 0, 0)).unwrap();
|
||||
assert_eq!((h.version, h.sample_rate, h.frame_bytes), (Version::Mpeg2, 24_000, 960));
|
||||
let h = parse_header(&header(true, 1, 14, 0, 0, 0)).unwrap();
|
||||
assert_eq!((h.sample_rate, h.bitrate_kbps, h.frame_bytes), (22_050, 256, 4 * (12 * 256_000 / 22_050)));
|
||||
// MPEG-2.5 and Layer III headers parse too
|
||||
assert_eq!(parse_header(&[0xFF, 0xE5, 0x10, 0xC0]).unwrap().sample_rate, 11_025);
|
||||
let h = parse_header(&[0xFF, 0xFB, 0x90, 0x44]).unwrap();
|
||||
assert_eq!((h.layer, h.frame_bytes), (3, 417));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_headers_are_errors() {
|
||||
assert_eq!(parse_header(&[]), Err(Error::Invalid("truncated header")));
|
||||
assert_eq!(parse_header(&[0xFF, 0xFD]), Err(Error::Invalid("truncated header")));
|
||||
assert_eq!(parse_header(&[0x00, 0xFD, 0x90, 0x00]), Err(Error::NoSync));
|
||||
assert_eq!(parse_header(&[0xFF, 0x1D, 0x90, 0x00]), Err(Error::NoSync));
|
||||
assert_eq!(parse_header(&[0xFF, 0xED, 0x90, 0x00]), Err(Error::Invalid("reserved version")));
|
||||
assert_eq!(parse_header(&[0xFF, 0xF9, 0x90, 0x00]), Err(Error::Invalid("reserved layer")));
|
||||
assert_eq!(parse_header(&[0xFF, 0xFD, 0xF0, 0x00]), Err(Error::Invalid("forbidden bit rate index")));
|
||||
assert_eq!(parse_header(&[0xFF, 0xFD, 0x9C, 0x00]), Err(Error::Invalid("reserved sampling frequency")));
|
||||
let mut d = Decoder::new();
|
||||
assert_eq!(d.decode(&[0xFF, 0xFB, 0x90, 0x44]).unwrap_err(), Error::Unsupported("Layer III"));
|
||||
assert_eq!(d.decode(&[0xFF, 0xFD, 0x04, 0x00, 0, 0]).unwrap_err(), Error::Unsupported("free-format bit rate"));
|
||||
assert_eq!(d.decode(&silent(header(false, 2, 10, 1, 0, 0))[..100]).unwrap_err(), Error::Invalid("truncated frame"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn silent_frames_decode_to_silence() {
|
||||
let mut d = Decoder::new();
|
||||
for (h, ch, n) in [
|
||||
(header(false, 2, 14, 1, 3, 0), 1, 1152),
|
||||
(header(false, 2, 1, 2, 0, 0), 2, 1152),
|
||||
(header(true, 2, 8, 0, 1, 3), 2, 1152),
|
||||
(header(false, 1, 6, 0, 2, 0), 2, 384),
|
||||
(header(false, 1, 4, 1, 3, 0), 1, 384),
|
||||
] {
|
||||
let f = d.decode(&silent(h)).unwrap();
|
||||
assert_eq!(f.channels.len(), ch, "{h:?}");
|
||||
assert!(f.channels.iter().all(|c| c.len() == n && c.iter().all(|&s| s == 0.0)), "{h:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Table 3-B.3 as typed in must be the smooth prototype filter: with every other block of 64
|
||||
/// negated back, its third differences stay within the rounding of the 2⁻¹⁶ units (a mistyped
|
||||
/// coefficient shows up as a spike of hundreds).
|
||||
#[test]
|
||||
fn synthesis_window_is_the_smooth_prototype() {
|
||||
let h: Vec<f64> = (0..=256).map(|i| window_half(i).unwrap() as f64 * if (i / 64) % 2 == 1 { -1.0 } else { 1.0 }).collect();
|
||||
let d1: Vec<f64> = h.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
let d2: Vec<f64> = d1.windows(2).map(|w| w[1] - w[0]).collect();
|
||||
let worst = d2.windows(2).map(|w| (w[1] - w[0]).abs()).fold(0.0, f64::max);
|
||||
assert!(worst <= 8.0, "{worst}");
|
||||
assert_eq!(window_half(257), None);
|
||||
let w = tables::window();
|
||||
// symmetry of the full window and the table's endpoints
|
||||
assert_eq!((w[0], w[256], w[511], w[448]), (0.0, 75_038.0 / 65_536.0, 1.0 / 65_536.0, w[64]));
|
||||
assert_eq!(w[300], -w[212]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layer2_allocation_tables() {
|
||||
use tables::AllocTable as T;
|
||||
for t in [T::A, T::B, T::C, T::D, T::Lsf] {
|
||||
for sb in 0..t.sblimit() {
|
||||
let row = t.row(sb);
|
||||
assert!(row.len().is_power_of_two() && row[0] == 0, "{t:?} {sb}");
|
||||
}
|
||||
}
|
||||
// the allowed combinations (Table 3-B.2) and the ones encoders write anyway
|
||||
assert_eq!(T::select(false, 48_000, 192), T::A);
|
||||
assert_eq!(T::select(false, 44_100, 64), T::A);
|
||||
assert_eq!(T::select(false, 44_100, 96), T::B);
|
||||
assert_eq!(T::select(false, 32_000, 192), T::B);
|
||||
assert_eq!(T::select(false, 48_000, 32), T::C);
|
||||
assert_eq!(T::select(false, 44_100, 48), T::C);
|
||||
assert_eq!(T::select(false, 32_000, 48), T::D);
|
||||
assert_eq!(T::select(false, 48_000, 384), T::A);
|
||||
assert_eq!(T::select(false, 44_100, 384), T::B);
|
||||
assert_eq!(T::select(false, 32_000, 16), T::D);
|
||||
assert_eq!(T::select(true, 24_000, 160), T::Lsf);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requantization_is_symmetric() {
|
||||
assert_eq!([0, 1, 2].map(|v| requantize(v, 3)), [-2.0 / 3.0, 0.0, 2.0 / 3.0]);
|
||||
assert_eq!(requantize(4, 9), 0.0);
|
||||
assert_eq!(requantize(0, 65_535), -65_534.0 / 65_535.0);
|
||||
}
|
||||
|
||||
/// Random audio data behind valid headers, and damaged headers: errors or noise, never a panic.
|
||||
#[test]
|
||||
fn random_frames_never_panic() {
|
||||
let mut x = 0x1234_5678u32;
|
||||
let mut rnd = move || {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
x
|
||||
};
|
||||
let mut d = Decoder::new();
|
||||
for k in 0..4000 {
|
||||
let mut h = header(k % 3 == 0, 1 + (k % 2) as u8, 1 + (rnd() % 14) as u8, (rnd() % 3) as u8, (rnd() % 4) as u8, (rnd() % 4) as u8);
|
||||
if k % 5 == 0 {
|
||||
h[1] &= 0xFE; // CRC present
|
||||
}
|
||||
if k % 7 == 0 {
|
||||
h[2] ^= rnd() as u8;
|
||||
h[3] ^= rnd() as u8;
|
||||
}
|
||||
let len = parse_header(&h).map(|p| p.frame_bytes).unwrap_or(64);
|
||||
let mut f = h.to_vec();
|
||||
f.extend((0..len.saturating_sub(4) + (rnd() % 8) as usize).map(|_| rnd() as u8));
|
||||
if k % 11 == 0 {
|
||||
f.truncate(rnd() as usize % f.len());
|
||||
}
|
||||
if let Ok(fr) = d.decode(&f) {
|
||||
assert!(fr.channels.iter().flatten().all(|s| s.is_finite()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Output of the decoder, bit for bit, on deterministic synthetic streams.
|
||||
///
|
||||
/// Each stream is a run of valid headers (mono, stereo, joint stereo at several bounds and dual
|
||||
/// channel; Layer I and II; MPEG-1 and MPEG-2; several bit rates and sampling frequencies)
|
||||
/// followed by xorshift noise, decoded by one `Decoder` so that the synthesis filter's history
|
||||
/// carries from frame to frame. Frames the decoder rejects are counted and skipped. The hash is
|
||||
/// FNV-1a over the bits of every decoded sample.
|
||||
///
|
||||
/// The golden values were captured from the decoder before the synthesis filterbank was
|
||||
/// rewritten (`synthesize` with the shifting `V` buffer and the 64-row matrix): check out that
|
||||
/// commit, run `cargo test -p filmcraft-mpa decoded_samples_are_bit_exact -- --nocapture`, and
|
||||
/// copy the printed `(ok, hash)` pairs. A change of the filter's arithmetic (summation order,
|
||||
/// grouping, fused multiply-add) shows up here; a legitimate one needs new goldens and a reason.
|
||||
#[test]
|
||||
fn decoded_samples_are_bit_exact() {
|
||||
// (lsf, layer, bitrate_index, rate_index, mode, mode_extension)
|
||||
const STREAMS: &[(bool, u8, u8, u8, u8, u8)] = &[
|
||||
(false, 2, 10, 1, 0, 0),
|
||||
(false, 2, 14, 1, 3, 0),
|
||||
(false, 2, 6, 0, 1, 0),
|
||||
(false, 2, 9, 0, 1, 3),
|
||||
(false, 2, 5, 2, 2, 0),
|
||||
(false, 2, 2, 1, 0, 0),
|
||||
(true, 2, 8, 0, 1, 2),
|
||||
(true, 2, 4, 2, 3, 0),
|
||||
(false, 1, 12, 0, 1, 2),
|
||||
(false, 1, 14, 1, 0, 0),
|
||||
(false, 1, 8, 2, 3, 0),
|
||||
(true, 1, 10, 0, 2, 0),
|
||||
];
|
||||
let mut got = vec![];
|
||||
for (n, &(lsf, layer, br, rate, mode, ext)) in STREAMS.iter().enumerate() {
|
||||
let mut x = 0x9E37_79B9u32 ^ (n as u32).wrapping_mul(0x85EB_CA6B);
|
||||
let mut rnd = move || {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
x
|
||||
};
|
||||
let mut d = Decoder::new();
|
||||
let (mut ok, mut hash) = (0u32, 0xCBF2_9CE4_8422_2325u64);
|
||||
for _ in 0..60 {
|
||||
let h = header(lsf, layer, br, rate, mode, ext);
|
||||
let len = parse_header(&h).map_or(0, |p| p.frame_bytes);
|
||||
let mut f = h.to_vec();
|
||||
// sparse noise: most allocations are zero, so many frames are valid and quiet
|
||||
f.extend((0..len.saturating_sub(4)).map(|_| (rnd() & rnd() & rnd()) as u8));
|
||||
if let Ok(fr) = d.decode(&f) {
|
||||
ok += 1;
|
||||
for s in fr.channels.iter().flatten() {
|
||||
hash = (hash ^ u64::from(s.to_bits())).wrapping_mul(0x0000_0100_0000_01B3);
|
||||
}
|
||||
}
|
||||
}
|
||||
got.push((ok, hash));
|
||||
}
|
||||
println!("{got:?}");
|
||||
const GOLDEN: &[(u32, u64)] = &[
|
||||
(59, 0xea8448e85fe3df1b),
|
||||
(60, 0xc6ecc7f674c186d4),
|
||||
(60, 0xb38a4d7cba7bfbde),
|
||||
(59, 0xf37f8a5abff50363),
|
||||
(60, 0x1e489c563c40c852),
|
||||
(49, 0x52ab5c8f9db13cc1),
|
||||
(60, 0x401b8039ec831783),
|
||||
(60, 0x3555c5d49d12ecca),
|
||||
(59, 0xb063c5f8c79edaef),
|
||||
(58, 0xcedb49aa85eb2e29),
|
||||
(58, 0x3ee32a2c6b9da56b),
|
||||
(57, 0xbb913530021557b1),
|
||||
];
|
||||
assert_eq!(got, GOLDEN);
|
||||
}
|
||||
|
||||
/// `reset` forgets the filter history, including where the ring buffer of `V` starts.
|
||||
#[test]
|
||||
fn reset_matches_a_fresh_decoder() {
|
||||
let mut x = 0x2545_F491u32;
|
||||
let mut f = header(false, 2, 10, 1, 0, 0).to_vec();
|
||||
f.extend((0..572).map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
(x & (x >> 7) & (x >> 13)) as u8
|
||||
}));
|
||||
let first = Decoder::new().decode(&f).unwrap();
|
||||
let mut d = Decoder::new();
|
||||
for _ in 0..3 {
|
||||
d.decode(&f).unwrap();
|
||||
}
|
||||
d.reset();
|
||||
let again = d.decode(&f).unwrap();
|
||||
assert!(first.channels.iter().flatten().any(|&s| s != 0.0));
|
||||
assert_eq!(first.channels, again.channels);
|
||||
}
|
||||
@@ -995,78 +995,3 @@ pub fn denormalise_bands(input: DenormaliseBandsInput<'_>) {
|
||||
freq[from..n].fill(0.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn bitexact_trig_endpoints() {
|
||||
assert_eq!(bitexact_cos(0), 32768);
|
||||
|
||||
let mid = bitexact_cos(8192);
|
||||
assert!((mid - 23170).abs() < 20, "{mid}");
|
||||
assert_eq!(bitexact_log2tan(16384, 16384), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn isqrt_exact() {
|
||||
for v in [0u32, 1, 2, 3, 4, 15, 16, 17, 99, 100, 1 << 20, u32::MAX] {
|
||||
let r = isqrt32(v) as u64;
|
||||
assert!(r * r <= v as u64 && (r + 1) * (r + 1) > v as u64);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pvq_table_matches_reference_counts() {
|
||||
let table = pvq_table();
|
||||
for n in 0..=PVQ_MAX_N {
|
||||
for k in 0..=PVQ_MAX_K {
|
||||
let want = super::super::rate::pvq_v(n, k).min(u32::MAX as u128) as u32;
|
||||
// V(0, k > 0) = 0 and V(n, 0) = 1 in both.
|
||||
assert_eq!(table[n * PVQ_W + k], want, "n={n} k={k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pvq_roundtrip_all_codewords_small() {
|
||||
use crate::opus::decode::range::enc::RangeEncoder;
|
||||
// Enumerate every index for small N,K, decode, and check uniqueness + sum |y| == K.
|
||||
for n in 1..6usize {
|
||||
for k in 1..5usize {
|
||||
let total = super::super::rate::pvq_v(n, k) as u32;
|
||||
let mut seen = std::collections::HashSet::new();
|
||||
for idx in 0..total {
|
||||
let mut e = RangeEncoder::new(16);
|
||||
e.uint(idx, total);
|
||||
let buf = e.done();
|
||||
let mut d = RangeDecoder::new(&buf);
|
||||
let mut y = vec![0i32; n];
|
||||
let ryy = decode_pulses(&mut y, n, k, &mut d);
|
||||
assert_eq!(y.iter().map(|v| v.unsigned_abs() as usize).sum::<usize>(), k);
|
||||
assert_eq!(ryy as i32, y.iter().map(|v| v * v).sum::<i32>());
|
||||
assert!(seen.insert(y.clone()), "duplicate codeword n={n} k={k} idx={idx}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn haar_is_involution() {
|
||||
let mut x: Vec<f32> = (0..16).map(|i| i as f32).collect();
|
||||
let orig = x.clone();
|
||||
haar1(&mut x, 16, 1);
|
||||
haar1(&mut x, 16, 1);
|
||||
for (a, b) in x.iter().zip(&orig) {
|
||||
assert!((a - b).abs() < 1e-4);
|
||||
}
|
||||
let mut tmp = Vec::new();
|
||||
for &h in &[false, true] {
|
||||
let mut y = orig.clone();
|
||||
deinterleave_hadamard(&mut y, 4, 4, h, &mut tmp);
|
||||
interleave_hadamard(&mut y, 4, 4, h, &mut tmp);
|
||||
assert_eq!(y, orig);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -117,56 +117,3 @@ pub fn unquant_energy_finalise(input: EnergyFinalise<'_, '_>) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::opus::decode::range::enc::RangeEncoder;
|
||||
|
||||
fn laplace_encode(e: &mut RangeEncoder, value: i32, mut fs: u32, decay: u32) {
|
||||
let mut fl = 0u32;
|
||||
let mut val = value;
|
||||
if val != 0 {
|
||||
let s: i32 = if val < 0 { -1 } else { 0 };
|
||||
val = val.abs();
|
||||
fl = fs;
|
||||
fs = laplace_get_freq1(fs, decay);
|
||||
let mut i = 1;
|
||||
while fs > 0 && i < val {
|
||||
fs *= 2;
|
||||
fl += fs + 2 * LAPLACE_MINP;
|
||||
fs = (fs * decay) >> 15;
|
||||
i += 1;
|
||||
}
|
||||
if fs == 0 {
|
||||
let ndi_max = (32768 - fl + LAPLACE_MINP - 1) as i32;
|
||||
let ndi_max = (ndi_max - s) >> 1;
|
||||
let di = (val - i).min(ndi_max - 1);
|
||||
fl = (fl as i32 + (2 * di + 1 + s) * LAPLACE_MINP as i32) as u32;
|
||||
fs = LAPLACE_MINP.min(32768 - fl);
|
||||
} else {
|
||||
fs += LAPLACE_MINP;
|
||||
if s == 0 {
|
||||
fl += fs;
|
||||
}
|
||||
}
|
||||
}
|
||||
e.encode(fl, fl + fs, 32768);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn laplace_roundtrip() {
|
||||
for &(fs, decay) in &[(72u32 << 7, 127u32 << 6), (24 << 7, 179 << 6), (177 << 7, 11 << 6)] {
|
||||
let vals: Vec<i32> = (-12..=12).collect();
|
||||
let mut e = RangeEncoder::new(400);
|
||||
for &v in &vals {
|
||||
laplace_encode(&mut e, v, fs, decay);
|
||||
}
|
||||
let buf = e.done();
|
||||
let mut d = RangeDecoder::new(&buf);
|
||||
for &v in &vals {
|
||||
assert_eq!(laplace_decode(&mut d, fs, decay), v, "fs={fs} v={v}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -207,111 +207,3 @@ pub struct ImdctScratch {
|
||||
z: Vec<Cpx>,
|
||||
scratch: Vec<Cpx>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn fft_matches_dft() {
|
||||
for &n in &[15usize, 30, 60, 120, 240, 480, 960] {
|
||||
let fft = Fft::new(n);
|
||||
let x: Vec<Cpx> = (0..n).map(|i| Cpx { re: ((i * 7) % 13) as f32 - 6.0, im: ((i * 3) % 5) as f32 - 2.0 }).collect();
|
||||
let mut y = x.clone();
|
||||
fft.process(&mut y, &mut Vec::new());
|
||||
for k in [0, 1, 7, n / 2, n - 1] {
|
||||
let mut acc = (0f64, 0f64);
|
||||
for (i, v) in x.iter().enumerate() {
|
||||
let ph = -2.0 * std::f64::consts::PI * (i * k) as f64 / n as f64;
|
||||
acc.0 += v.re as f64 * ph.cos() - v.im as f64 * ph.sin();
|
||||
acc.1 += v.re as f64 * ph.sin() + v.im as f64 * ph.cos();
|
||||
}
|
||||
assert!((acc.0 - y[k].re as f64).abs() < 1e-2 && (acc.1 - y[k].im as f64).abs() < 1e-2, "n={n} k={k}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The previous generic implementation (every butterfly multiplies by every DFT root), kept
|
||||
/// to measure how far the specialised kernels move the output.
|
||||
fn reference_fft(n: usize, data: &mut [Cpx]) {
|
||||
let fft = Fft::new(n);
|
||||
let inp = data.to_vec();
|
||||
rec_ref(&fft, data, &inp, 1, n, 0, 1);
|
||||
}
|
||||
|
||||
fn rec_ref(f: &Fft, out: &mut [Cpx], inp: &[Cpx], in_stride: usize, n: usize, fi: usize, tw_stride: usize) {
|
||||
let p = f.factors[fi];
|
||||
let m = n / p;
|
||||
if m == 1 {
|
||||
for (i, o) in out.iter_mut().enumerate().take(p) {
|
||||
*o = inp[i * in_stride];
|
||||
}
|
||||
} else {
|
||||
for q in 0..p {
|
||||
rec_ref(f, &mut out[q * m..(q + 1) * m], &inp[q * in_stride..], in_stride * p, m, fi + 1, tw_stride * p);
|
||||
}
|
||||
}
|
||||
let big = f.n;
|
||||
let mut t = [Cpx::default(); 5];
|
||||
for k in 0..m {
|
||||
for q in 0..p {
|
||||
let w = f.twiddle[(q * k * tw_stride) % big];
|
||||
t[q] = out[q * m + k].mul(w);
|
||||
}
|
||||
for q2 in 0..p {
|
||||
let mut acc = Cpx::default();
|
||||
for (q, tq) in t.iter().enumerate().take(p) {
|
||||
let w = f.twiddle[((q * q2) % p) * (big / p)];
|
||||
acc = acc.add(tq.mul(w));
|
||||
}
|
||||
out[q2 * m + k] = acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Every size the CELT frame sizes use (N/4 for N = 2 * {120, 240, 480, 960}, plus the
|
||||
/// short-block sizes) agrees with the previous implementation to f32 rounding.
|
||||
#[test]
|
||||
fn fft_matches_reference_implementation() {
|
||||
for &n in &[15usize, 30, 60, 120, 240, 480, 960] {
|
||||
let fft = Fft::new(n);
|
||||
let x: Vec<Cpx> = (0..n)
|
||||
.map(|i| Cpx { re: (((i * 7919) % 2003) as f32 - 1000.0) / 500.0, im: (((i * 104729) % 1009) as f32 - 500.0) / 250.0 })
|
||||
.collect();
|
||||
let mut new = x.clone();
|
||||
fft.process(&mut new, &mut Vec::new());
|
||||
let mut old = x.clone();
|
||||
reference_fft(n, &mut old);
|
||||
let peak = old.iter().map(|c| c.re.abs().max(c.im.abs())).fold(0f32, f32::max);
|
||||
let max_diff = new.iter().zip(&old).map(|(a, b)| (a.re - b.re).abs().max((a.im - b.im).abs())).fold(0f32, f32::max);
|
||||
assert!(max_diff <= 1e-5 * peak, "n={n} max_diff={max_diff} peak={peak}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The folded output must equal the direct IMDCT formula folded by TDAC symmetry.
|
||||
#[test]
|
||||
fn imdct_matches_direct_formula() {
|
||||
let n = 240;
|
||||
let n2 = n / 2;
|
||||
let im = Imdct::new(n);
|
||||
let x: Vec<f32> = (0..n2).map(|k| ((k * 37 % 11) as f32 - 5.0) / 5.0).collect();
|
||||
let overlap = 0;
|
||||
let mut out = vec![0f32; n2];
|
||||
im.backward(&x, 1, &mut out, &[], overlap, &mut ImdctScratch::default());
|
||||
// Direct IMDCT y[t] = sum X[k] cos(2pi/N (t + 1/2 + N/4)(k + 1/2)), t in 0..N.
|
||||
let y: Vec<f64> = (0..n)
|
||||
.map(|t| {
|
||||
(0..n2)
|
||||
.map(|k| x[k] as f64 * (2.0 * std::f64::consts::PI / n as f64 * (t as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos())
|
||||
.sum()
|
||||
})
|
||||
.collect();
|
||||
// The folded half: out[i] relates to y in the middle half; check proportionality.
|
||||
let mid: Vec<f64> = (0..n2).map(|i| y[n / 4 + i]).collect();
|
||||
let dot: f64 = mid.iter().zip(&out).map(|(a, b)| a * *b as f64).sum();
|
||||
let ea: f64 = mid.iter().map(|a| a * a).sum();
|
||||
let eb: f64 = out.iter().map(|b| (*b as f64).powi(2)).sum();
|
||||
let corr = dot.abs() / (ea.sqrt() * eb.sqrt());
|
||||
assert!(corr > 0.999, "corr {corr}");
|
||||
}
|
||||
}
|
||||
@@ -579,42 +579,3 @@ fn interp_bits2pulses(input: InterpPulsesInput<'_, '_>) -> Allocation {
|
||||
}
|
||||
Allocation { coded_bands, intensity, dual_stereo, balance, pulses: bits, fine_quant: ebits, fine_priority }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn log2_frac_values() {
|
||||
assert_eq!(log2_frac(1, 3), 0);
|
||||
assert_eq!(log2_frac(2, 3), 8);
|
||||
assert_eq!(log2_frac(4, 3), 16);
|
||||
assert_eq!(log2_frac(6, 3), 21);
|
||||
assert_eq!(log2_frac(18, 3), 34);
|
||||
assert_eq!(log2_frac(22, 3), 36);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pvq_counts() {
|
||||
// V(N,1) = 2N, V(1,K) = 2 (K>0), V(2,K) = 4K.
|
||||
assert_eq!(pvq_v(5, 1), 10);
|
||||
assert_eq!(pvq_v(1, 7), 2);
|
||||
assert_eq!(pvq_v(2, 9), 36);
|
||||
assert_eq!(pvq_v(3, 2), 18);
|
||||
assert_eq!(pvq_v(0, 0), 1);
|
||||
assert_eq!(pvq_v(0, 3), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caps_match_reference_shape() {
|
||||
let m = Mode::new();
|
||||
// 1-bin bands at LM=0 (mono and stereo) are capped at 224.
|
||||
assert!(m.caps[..8].iter().all(|&c| c == 224));
|
||||
assert!(m.caps[21..29].iter().all(|&c| c == 224));
|
||||
let first_rows: [u8; 42] = [
|
||||
224, 224, 224, 224, 224, 224, 224, 224, 160, 160, 160, 160, 185, 185, 185, 178, 178, 168, 134, 61, 37, 224, 224, 224, 224, 224, 224, 224,
|
||||
224, 240, 240, 240, 240, 207, 207, 207, 198, 198, 183, 144, 66, 40,
|
||||
];
|
||||
assert_eq!(&m.caps[..42], &first_rows[..]);
|
||||
}
|
||||
}
|
||||
@@ -173,50 +173,6 @@ impl OpusHead {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parse_family0_and_roundtrip() {
|
||||
let mut h = b"OpusHead".to_vec();
|
||||
h.extend([1, 2, 0x38, 0x01, 0x80, 0xBB, 0, 0, 0x00, 0x01, 0]);
|
||||
let head = OpusHead::parse(&h).unwrap();
|
||||
assert_eq!(head.channels, 2);
|
||||
assert_eq!(head.pre_skip, 312);
|
||||
assert_eq!(head.input_sample_rate, 48000);
|
||||
assert_eq!(head.output_gain, 256);
|
||||
assert_eq!((head.streams, head.coupled_streams), (1, 1));
|
||||
assert_eq!(head.to_bytes(), h);
|
||||
assert!((head.gain_linear() - 1.122).abs() < 1e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_family1_51() {
|
||||
let mut h = b"OpusHead".to_vec();
|
||||
h.extend([1, 6, 0x38, 0x01, 0x80, 0xBB, 0, 0, 0, 0, 1, 4, 2, 0, 4, 1, 2, 3, 5]);
|
||||
let head = OpusHead::parse(&h).unwrap();
|
||||
assert_eq!((head.channels, head.streams, head.coupled_streams), (6, 4, 2));
|
||||
assert_eq!(head.mapping, vec![0, 4, 1, 2, 3, 5]);
|
||||
assert_eq!(OpusHead::parse(&head.to_bytes()).unwrap(), head);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_garbage() {
|
||||
assert!(OpusHead::parse(b"OpusHea").is_err());
|
||||
assert!(OpusHead::parse(b"OpusTags...........").is_err());
|
||||
let mut h = b"OpusHead".to_vec();
|
||||
h.extend([1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
|
||||
assert!(OpusHead::parse(&h).is_err());
|
||||
let mut h = b"OpusHead".to_vec();
|
||||
h.extend([1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 5]);
|
||||
assert!(OpusHead::parse(&h).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dops() {
|
||||
let d = [0u8, 2, 0x01, 0x38, 0, 0, 0xBB, 0x80, 0, 0, 0];
|
||||
let head = OpusHead::from_dops(&d).unwrap();
|
||||
assert_eq!(head.pre_skip, 312);
|
||||
assert_eq!(head.channels, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn directly_constructed_headers_are_checked_before_decoder_allocation() {
|
||||
let head = OpusHead {
|
||||
|
||||
@@ -268,21 +268,6 @@ pub fn packet_samples_48k(data: &[u8]) -> Result<usize, Error> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn toc_configs() {
|
||||
for cfg in 0u8..32 {
|
||||
let t = Toc::parse(cfg << 3);
|
||||
let ms10 = t.frame_samples(48000) * 10 / 48; // tenths of ms
|
||||
let expect = match cfg {
|
||||
0..=11 => [100, 200, 400, 600][cfg as usize & 3],
|
||||
12..=15 => [100, 200][cfg as usize & 1],
|
||||
_ => [25, 50, 100, 200][cfg as usize & 3],
|
||||
};
|
||||
assert_eq!(ms10, expect, "config {cfg}");
|
||||
}
|
||||
assert!(Toc::parse(0x04).stereo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frame_codes() {
|
||||
// code 0
|
||||
@@ -309,30 +294,4 @@ mod tests {
|
||||
assert!(Packet::parse(&[0x03, 0x00]).is_err());
|
||||
assert!(Packet::parse(&[]).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_byte_sizes() {
|
||||
let mut pkt = vec![0x02u8, 252, 1];
|
||||
pkt.extend(std::iter::repeat_n(7u8, 256));
|
||||
pkt.extend([1, 2]);
|
||||
let p = Packet::parse(&pkt).unwrap();
|
||||
assert_eq!(p.frames[0].len(), 256);
|
||||
assert_eq!(p.frames[1], &[1, 2]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_delimited() {
|
||||
// code 0 with explicit size, followed by trailing data of the next stream.
|
||||
let (p, used) = Packet::parse_self_delimited(&[0x00, 2, 5, 6, 0xAA, 0xBB]).unwrap();
|
||||
assert_eq!(p.frames, vec![&[5u8, 6][..]]);
|
||||
assert_eq!(used, 4);
|
||||
// code 1: one size for both frames.
|
||||
let (p, used) = Packet::parse_self_delimited(&[0x01, 1, 5, 6, 9]).unwrap();
|
||||
assert_eq!(p.frames, vec![&[5u8][..], &[6u8][..]]);
|
||||
assert_eq!(used, 4);
|
||||
// code 3 VBR, 2 frames: size of frame 0, then size of last frame.
|
||||
let (p, used) = Packet::parse_self_delimited(&[0x03, 0x82, 1, 2, 7, 8, 9, 0xFF]).unwrap();
|
||||
assert_eq!(p.frames, vec![&[7u8][..], &[8u8, 9][..]]);
|
||||
assert_eq!(used, 7);
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,6 @@
|
||||
const SYM_BITS: u32 = 8;
|
||||
const CODE_BITS: u32 = 32;
|
||||
const SYM_MAX: u32 = (1 << SYM_BITS) - 1;
|
||||
#[cfg(test)]
|
||||
const CODE_SHIFT: u32 = CODE_BITS - SYM_BITS - 1;
|
||||
const CODE_TOP: u32 = 1 << (CODE_BITS - 1);
|
||||
const CODE_BOT: u32 = CODE_TOP >> SYM_BITS;
|
||||
const CODE_EXTRA: u32 = (CODE_BITS - 2) % SYM_BITS + 1;
|
||||
@@ -260,238 +258,3 @@ impl<'a> RangeDecoder<'a> {
|
||||
nbits.wrapping_sub(l)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod enc {
|
||||
//! Minimal range encoder (RFC 6716 §5.1), used only to build test streams.
|
||||
use super::*;
|
||||
|
||||
pub struct RangeEncoder {
|
||||
out: Vec<u8>,
|
||||
end: Vec<u8>,
|
||||
end_window: u32,
|
||||
nend_bits: i32,
|
||||
rng: u32,
|
||||
low: u32,
|
||||
rem: i32,
|
||||
ext: u32,
|
||||
size: usize,
|
||||
}
|
||||
|
||||
impl RangeEncoder {
|
||||
pub fn new(size: usize) -> Self {
|
||||
RangeEncoder { out: Vec::new(), end: Vec::new(), end_window: 0, nend_bits: 0, rng: CODE_TOP, low: 0, rem: -1, ext: 0, size }
|
||||
}
|
||||
fn carry_out(&mut self, c: u32) {
|
||||
if c != SYM_MAX {
|
||||
let carry = c >> SYM_BITS;
|
||||
if self.rem >= 0 {
|
||||
self.out.push((self.rem as u32 + carry) as u8);
|
||||
}
|
||||
if self.ext > 0 {
|
||||
let sym = (SYM_MAX + carry) & SYM_MAX;
|
||||
for _ in 0..self.ext {
|
||||
self.out.push(sym as u8);
|
||||
}
|
||||
self.ext = 0;
|
||||
}
|
||||
self.rem = (c & SYM_MAX) as i32;
|
||||
} else {
|
||||
self.ext += 1;
|
||||
}
|
||||
}
|
||||
fn normalize(&mut self) {
|
||||
while self.rng <= CODE_BOT {
|
||||
self.carry_out(self.low >> CODE_SHIFT);
|
||||
self.low = (self.low << SYM_BITS) & (CODE_TOP - 1);
|
||||
self.rng <<= SYM_BITS;
|
||||
}
|
||||
}
|
||||
pub fn encode(&mut self, fl: u32, fh: u32, ft: u32) {
|
||||
let r = self.rng / ft;
|
||||
if fl > 0 {
|
||||
self.low += self.rng - r * (ft - fl);
|
||||
self.rng = r * (fh - fl);
|
||||
} else {
|
||||
self.rng -= r * (ft - fh);
|
||||
}
|
||||
self.normalize();
|
||||
}
|
||||
pub fn bit_logp(&mut self, val: bool, logp: u32) {
|
||||
let r = self.rng;
|
||||
let s = r >> logp;
|
||||
let r2 = r - s;
|
||||
if val {
|
||||
self.low += r2;
|
||||
self.rng = s;
|
||||
} else {
|
||||
self.rng = r2;
|
||||
}
|
||||
self.normalize();
|
||||
}
|
||||
pub fn icdf(&mut self, s: usize, icdf: &[u8], ftb: u32) {
|
||||
let r = self.rng >> ftb;
|
||||
if s > 0 {
|
||||
self.low += self.rng - r * icdf[s - 1] as u32;
|
||||
self.rng = r * (icdf[s - 1] as u32 - icdf[s] as u32);
|
||||
} else {
|
||||
self.rng -= r * icdf[s] as u32;
|
||||
}
|
||||
self.normalize();
|
||||
}
|
||||
pub fn uint(&mut self, fl: u32, ft: u32) {
|
||||
let ft1 = ft - 1;
|
||||
let ftb = ilog(ft1);
|
||||
if ftb > 8 {
|
||||
let ftb = (ftb - 8) as u32;
|
||||
let top = (ft1 >> ftb) + 1;
|
||||
let v = fl >> ftb;
|
||||
self.encode(v, v + 1, top);
|
||||
self.bits(fl & ((1 << ftb) - 1), ftb);
|
||||
} else {
|
||||
self.encode(fl, fl + 1, ft);
|
||||
}
|
||||
}
|
||||
pub fn bits(&mut self, val: u32, bits: u32) {
|
||||
let mut window = self.end_window;
|
||||
let mut used = self.nend_bits;
|
||||
if used as u32 + bits > CODE_BITS {
|
||||
while used >= SYM_BITS as i32 {
|
||||
self.end.push((window & SYM_MAX) as u8);
|
||||
window >>= SYM_BITS;
|
||||
used -= SYM_BITS as i32;
|
||||
}
|
||||
}
|
||||
window |= val << used;
|
||||
used += bits as i32;
|
||||
self.end_window = window;
|
||||
self.nend_bits = used;
|
||||
}
|
||||
/// Finalises and returns a buffer of exactly `size` bytes.
|
||||
pub fn done(mut self) -> Vec<u8> {
|
||||
let mut l = CODE_BITS as i32 - ilog(self.rng);
|
||||
let mut msk = (CODE_TOP - 1) >> l;
|
||||
let mut end = (self.low + msk) & !msk;
|
||||
if (end | msk) >= self.low + self.rng {
|
||||
l += 1;
|
||||
msk >>= 1;
|
||||
end = (self.low + msk) & !msk;
|
||||
}
|
||||
while l > 0 {
|
||||
self.carry_out(end >> CODE_SHIFT);
|
||||
end = (end << SYM_BITS) & (CODE_TOP - 1);
|
||||
l -= SYM_BITS as i32;
|
||||
}
|
||||
if self.rem >= 0 || self.ext > 0 {
|
||||
self.carry_out(0);
|
||||
}
|
||||
let mut window = self.end_window;
|
||||
let mut used = self.nend_bits;
|
||||
while used > 0 {
|
||||
self.end.push((window & SYM_MAX) as u8);
|
||||
window >>= SYM_BITS;
|
||||
used -= SYM_BITS as i32;
|
||||
}
|
||||
assert!(self.out.len() + self.end.len() <= self.size, "range encoder overflow");
|
||||
let mut buf = self.out;
|
||||
buf.resize(self.size - self.end.len(), 0);
|
||||
for &b in self.end.iter().rev() {
|
||||
buf.push(b);
|
||||
}
|
||||
buf
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::enc::RangeEncoder;
|
||||
use super::*;
|
||||
|
||||
struct Lcg(u32);
|
||||
impl Lcg {
|
||||
fn next(&mut self) -> u32 {
|
||||
self.0 = self.0.wrapping_mul(1664525).wrapping_add(1013904223);
|
||||
self.0 >> 8
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn roundtrip_mixed_symbols() {
|
||||
let mut rng = Lcg(1);
|
||||
for trial in 0..200 {
|
||||
let n = 1 + (rng.next() % 300) as usize;
|
||||
let mut ops = Vec::new();
|
||||
for _ in 0..n {
|
||||
match rng.next() % 5 {
|
||||
0 => {
|
||||
let ft = 2 + rng.next() % 1000;
|
||||
let v = rng.next() % ft;
|
||||
ops.push((0u8, v, ft));
|
||||
}
|
||||
1 => {
|
||||
let logp = 1 + rng.next() % 15;
|
||||
ops.push((1, rng.next().is_multiple_of(7) as u32, logp));
|
||||
}
|
||||
2 => {
|
||||
let bits = 1 + rng.next() % 24;
|
||||
ops.push((2, rng.next() & ((1 << bits) - 1), bits));
|
||||
}
|
||||
3 => {
|
||||
let ft = 2 + rng.next() % 100_000_000;
|
||||
ops.push((3, rng.next() % ft, ft));
|
||||
}
|
||||
_ => ops.push((4, rng.next() % 4, 0)),
|
||||
}
|
||||
}
|
||||
let icdf: [u8; 4] = [200, 120, 30, 0];
|
||||
let mut e = RangeEncoder::new(8 * n + 16);
|
||||
for &(k, v, p) in &ops {
|
||||
match k {
|
||||
0 => e.encode(v, v + 1, p),
|
||||
1 => e.bit_logp(v != 0, p),
|
||||
2 => e.bits(v, p),
|
||||
3 => e.uint(v, p),
|
||||
_ => e.icdf(v as usize, &icdf, 8),
|
||||
}
|
||||
}
|
||||
let buf = e.done();
|
||||
let mut d = RangeDecoder::new(&buf);
|
||||
for (i, &(k, v, p)) in ops.iter().enumerate() {
|
||||
let got = match k {
|
||||
0 => {
|
||||
let s = d.decode(p);
|
||||
d.update(s, s + 1, p);
|
||||
s
|
||||
}
|
||||
1 => d.bit_logp(p) as u32,
|
||||
2 => d.bits(p),
|
||||
3 => d.uint(p),
|
||||
_ => d.icdf(&icdf, 8) as u32,
|
||||
};
|
||||
assert_eq!(got, v, "trial {trial} op {i} kind {k}");
|
||||
}
|
||||
assert!(!d.error);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tell_starts_at_one_bit() {
|
||||
let buf = [0u8; 8];
|
||||
let d = RangeDecoder::new(&buf);
|
||||
assert_eq!(d.tell(), 1);
|
||||
assert_eq!(d.tell_frac(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_and_garbage_never_panic() {
|
||||
let mut d = RangeDecoder::new(&[]);
|
||||
for i in 0..100 {
|
||||
d.bits(1 + i % 20);
|
||||
d.uint(3 + i * 77);
|
||||
d.icdf(&[250, 100, 0], 8);
|
||||
d.bit_logp(1 + i % 15);
|
||||
}
|
||||
let _ = d.tell_frac();
|
||||
}
|
||||
}
|
||||
@@ -337,41 +337,3 @@ pub fn nlsf2a(nlsf: &[i32]) -> [i32; MAX_LPC_ORDER] {
|
||||
}
|
||||
a_q12
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn flat_nlsf_gives_small_lpc() {
|
||||
// Uniformly spaced NLSFs correspond to an (almost) flat spectrum.
|
||||
let nlsf: Vec<i32> = (1..=16).map(|k| k * 32768 / 17).collect();
|
||||
let a = nlsf2a(&nlsf);
|
||||
assert!(a.iter().all(|v| v.abs() < 600), "{a:?}");
|
||||
let nlsf: Vec<i32> = (1..=10).map(|k| k * 32768 / 11).collect();
|
||||
let a = nlsf2a(&nlsf);
|
||||
assert!(a[..10].iter().all(|v| v.abs() < 600), "{a:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stabilize_enforces_spacing() {
|
||||
let mut v = [100, 90, 80, 30000, 30001, 30002, 31000, 32000, 32700, 32760];
|
||||
nlsf_stabilize(&mut v, &NLSF_MIN_SPACING_NBMB);
|
||||
assert!(v[0] >= NLSF_MIN_SPACING_NBMB[0]);
|
||||
for i in 1..10 {
|
||||
assert!(v[i] - v[i - 1] >= NLSF_MIN_SPACING_NBMB[i], "{v:?}");
|
||||
}
|
||||
assert!(32768 - v[9] >= NLSF_MIN_SPACING_NBMB[10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inverse_approximations() {
|
||||
for &b in &[65536, 100_000, 1 << 20, 81920, 1_686_110_208] {
|
||||
let inv = inverse32_varq(b, 47) as f64;
|
||||
let exact = 2f64.powi(47) / b as f64;
|
||||
assert!((inv - exact).abs() / exact < 1e-3, "{b}");
|
||||
}
|
||||
let q = div32_varq(65536, 131072, 16) as f64;
|
||||
assert!((q - 32768.0).abs() < 2.0);
|
||||
}
|
||||
}
|
||||
@@ -202,49 +202,3 @@ impl Resampler {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn upsample_sine_and_delay() {
|
||||
for &(fin, fout) in &[(16000u32, 48000u32), (8000, 48000), (12000, 48000), (16000, 24000), (16000, 8000), (12000, 16000)] {
|
||||
let mut r = Resampler::new(fin, fout);
|
||||
let f = 440.0;
|
||||
let n = fin as usize / 10;
|
||||
let x: Vec<i16> = (0..n).map(|i| ((2.0 * std::f64::consts::PI * f * i as f64 / fin as f64).sin() * 10000.0) as i16).collect();
|
||||
let mut y = Vec::new();
|
||||
for c in x.chunks(fin as usize / 50) {
|
||||
r.process(c, &mut y);
|
||||
}
|
||||
assert_eq!(y.len(), n * fout as usize / fin as usize);
|
||||
// Compare against the ideal delayed sine.
|
||||
let delay_ms = match fin {
|
||||
8000 => 0.538,
|
||||
12000 => 0.692,
|
||||
_ => 0.706,
|
||||
};
|
||||
let mut err = 0f64;
|
||||
let mut sig = 0f64;
|
||||
for (j, &v) in y.iter().enumerate().skip(fout as usize / 100) {
|
||||
let t = j as f64 / fout as f64 - delay_ms / 1000.0;
|
||||
let ideal = (2.0 * std::f64::consts::PI * f * t).sin() * 10000.0;
|
||||
err += (v as f64 - ideal).powi(2);
|
||||
sig += ideal * ideal;
|
||||
}
|
||||
let snr = 10.0 * (sig / err).log10();
|
||||
assert!(snr > 35.0, "{fin}->{fout}: {snr} dB");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dot8_matches_sequential_sum() {
|
||||
for len in [1usize, 7, 8, 9, 35, 36, 71] {
|
||||
let a: Vec<f32> = (0..len).map(|i| ((i * 37 % 19) as f32 - 9.0) * 1000.0).collect();
|
||||
let b: Vec<f32> = (0..len).map(|i| ((i * 11 % 7) as f32 - 3.0) / 7.0).collect();
|
||||
let seq: f64 = a.iter().zip(&b).map(|(&x, &y)| x as f64 * y as f64).sum();
|
||||
assert!((dot8(&a, &b) as f64 - seq).abs() < 1e-2, "len {len}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -185,101 +185,4 @@ mod tests {
|
||||
assert_eq!(p.minmax(&x, a, b), brute(&x, a, b), "range {a}..{b}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn degenerate_inputs() {
|
||||
let p = Peaks::build(&[]);
|
||||
assert_eq!(p.len_samples(), 0);
|
||||
assert_eq!(p.minmax(&[], 0, 10), (0.0, 0.0));
|
||||
assert_eq!(p.spans(&[], 0.0, 1.0, 0.0, 4), vec![None; 4]);
|
||||
let x = [0.5, -0.25];
|
||||
let p = Peaks::build(&x);
|
||||
assert_eq!(p.minmax(&x, 0, 2), (-0.25, 0.5));
|
||||
assert_eq!(p.minmax(&x, 5, 3), (0.0, 0.0));
|
||||
assert_eq!(p.minmax(&x, 0, usize::MAX), (-0.25, 0.5));
|
||||
assert_eq!(p.minmax(&x[..1], 0, 2), (0.5, 0.5));
|
||||
for (start, step, overlap) in [
|
||||
(f64::NAN, 1.0, 0.0),
|
||||
(0.0, 0.0, 0.0),
|
||||
(0.0, -1.0, 0.0),
|
||||
(0.0, f64::INFINITY, 0.0),
|
||||
(f64::NEG_INFINITY, 1.0, 0.0),
|
||||
(0.0, 1.0, -0.5),
|
||||
(0.0, 1.0, f64::NAN),
|
||||
] {
|
||||
assert_eq!(p.spans(&x, start, step, overlap, 3), vec![None; 3]);
|
||||
}
|
||||
assert_eq!(p.spans(&x, 0.0, 1.0, 0.0, 0).len(), 0);
|
||||
assert_eq!(p.spans(&x, 0.0, 1.0, 0.0, usize::MAX).len(), MAX_COLUMNS);
|
||||
let x = [f32::NAN, 1.0];
|
||||
let p = Peaks::build(&x);
|
||||
assert_eq!(p.minmax(&x, 0, 2), (1.0, 1.0));
|
||||
assert_eq!(p.spans(&x, 0.0, 1.0, 0.0, 1), vec![Some((1.0, 1.0))]);
|
||||
assert!(p.rms_spans(&x, 0.0, 1.0, 0.0, 1)[0].is_some_and(f32::is_finite));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loud_finite_samples_give_a_finite_rms() {
|
||||
let x = [1e20f32, -1e20, 3e38, 0.5];
|
||||
let p = Peaks::build(&x);
|
||||
let rms = p.rms_spans(&x, 0.0, 4.0, 0.0, 1)[0].unwrap();
|
||||
let want = (x.iter().map(|&v| f64::from(v) * f64::from(v)).sum::<f64>() / 4.0).sqrt() as f32;
|
||||
assert!(rms.is_finite() && (rms / want - 1.0).abs() < 1e-6, "{rms} vs {want}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rms_spans_match_the_samples() {
|
||||
let x = signal(20_000);
|
||||
let p = Peaks::build(&x);
|
||||
let rms = |s: usize, e: usize| (x[s..e].iter().map(|&v| f64::from(v) * f64::from(v)).sum::<f64>() / (e - s) as f64).sqrt() as f32;
|
||||
for (step, overlap) in [(1.5, 0.0), (37.0, 37.0), (1000.0, 0.0), (4096.0, 512.0)] {
|
||||
let cols = ((19_999.0 - overlap) / step) as usize;
|
||||
for (c, got) in p.rms_spans(&x, 0.0, step, overlap, cols).into_iter().enumerate() {
|
||||
let (a, b) = (c as f64 * step, ((c + 1) as f64 * step + overlap).min(19_999.0));
|
||||
let (got, want) = (got.unwrap(), rms(a.floor() as usize, (b.ceil() as usize + 1).min(20_000)));
|
||||
assert!((got - want).abs() <= want * 1e-4 + 1e-6, "span {c} at step {step}: {got} vs {want}");
|
||||
}
|
||||
}
|
||||
let sine: Vec<f32> = (0..48_000).map(|i| (i as f32 * 0.01).sin()).collect();
|
||||
let p = Peaks::build(&sine);
|
||||
let r = p.rms_spans(&sine, 0.0, 47_000.0, 0.0, 1)[0].unwrap();
|
||||
assert!((r - std::f32::consts::FRAC_1_SQRT_2).abs() < 1e-3, "{r}");
|
||||
assert_eq!(p.rms_spans(&sine, f64::NAN, 1.0, 0.0, 2), vec![None, None]);
|
||||
assert_eq!(p.rms_spans(&sine, 50_000.0, 1.0, 0.0, 1), vec![None]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spans_cover_their_samples_and_touch_their_neighbours() {
|
||||
let x = signal(10_000);
|
||||
let p = Peaks::build(&x);
|
||||
for step in [0.3, 1.0, 7.5, 100.0, 333.3] {
|
||||
let cols = (9_999.0 / step) as usize;
|
||||
let spans = p.spans(&x, 0.0, step, 0.0, cols);
|
||||
for (c, s) in spans.iter().enumerate() {
|
||||
let (lo, hi) = s.unwrap_or_else(|| panic!("span {c} at step {step}"));
|
||||
let (a, b) = ((c as f64 * step).ceil() as usize, ((c + 1) as f64 * step).floor() as usize);
|
||||
if a <= b {
|
||||
let truth = brute(&x, a, b + 1);
|
||||
assert!(lo <= truth.0 && hi >= truth.1, "span {c} at step {step}");
|
||||
}
|
||||
if let Some(Some((nlo, nhi))) = spans.get(c + 1) {
|
||||
assert!(*nlo <= hi && *nhi >= lo, "spans {c} and {} at step {step} don't touch", c + 1);
|
||||
}
|
||||
}
|
||||
let all = spans.iter().flatten().fold((f32::INFINITY, f32::NEG_INFINITY), |a, s| (a.0.min(s.0), a.1.max(s.1)));
|
||||
assert_eq!(all, brute(&x, 0, ((cols as f64 * step).floor() as usize + 1).min(10_000)), "step {step}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spans_follow_the_line_between_samples() {
|
||||
let x = [0.0, 1.0, -1.0, 0.5];
|
||||
let p = Peaks::build(&x);
|
||||
assert_eq!(p.spans(&x, 0.0, 0.25, 0.0, 4), vec![Some((0.0, 0.25)), Some((0.25, 0.5)), Some((0.5, 0.75)), Some((0.75, 1.0))]);
|
||||
assert_eq!(p.spans(&x, 0.5, 1.0, 0.0, 1), vec![Some((0.0, 1.0))]);
|
||||
let spans = vec![None, Some((0.0, 0.0)), Some((0.0, 1.0)), Some((-1.0, 1.0)), Some((-1.0, 0.5)), Some((0.5, 0.5)), None];
|
||||
assert_eq!(p.spans(&x, -2.0, 1.0, 0.0, 7), spans);
|
||||
assert_eq!(p.spans(&x, 0.0, 1.0, 1.0, 3), vec![Some((-1.0, 1.0)), Some((-1.0, 1.0)), Some((-1.0, 0.5))]);
|
||||
assert_eq!(p.spans(&x, 0.0, 1.0, 0.5, 3), vec![Some((0.0, 1.0)), Some((-1.0, 1.0)), Some((-1.0, 0.5))]);
|
||||
}
|
||||
}
|
||||
@@ -85,13 +85,3 @@ fn varint(b: &[u8], at: usize) -> Option<(u64, usize)> {
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn rejects_cookie_size_above_signed_range() {
|
||||
let mut bytes = b"caff\0\x01\0\0kuki".to_vec();
|
||||
bytes.extend_from_slice(&(1u64 << 63).to_be_bytes());
|
||||
assert!(super::check(&bytes, 0).is_err());
|
||||
}
|
||||
}
|
||||
@@ -180,42 +180,3 @@ fn overruns(b: &[u8], mut at: usize, end: usize, read: fn(&[u8], usize) -> Optio
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::comments_mask;
|
||||
|
||||
fn block(comments: &[&str]) -> Vec<u8> {
|
||||
let mut b = 3u32.to_le_bytes().to_vec();
|
||||
b.extend_from_slice(b"abc");
|
||||
b.extend_from_slice(&(comments.len() as u32).to_le_bytes());
|
||||
for c in comments {
|
||||
b.extend_from_slice(&(c.len() as u32).to_le_bytes());
|
||||
b.extend_from_slice(c.as_bytes());
|
||||
}
|
||||
b
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_channel_mask_comment_is_found_in_any_case() {
|
||||
assert_eq!(comments_mask(&block(&["TITLE=x", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"])), Some(0x107));
|
||||
assert_eq!(comments_mask(&block(&["waveformatextensible_channel_mask=0X3f"])), Some(0x3F));
|
||||
assert_eq!(comments_mask(&block(&["TITLE=x"])), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_channel_mask_comment_is_ignored() {
|
||||
for value in ["63", "0x", "0xZZ", "0x1FFFFFFFF"] {
|
||||
assert_eq!(comments_mask(&block(&[&format!("WAVEFORMATEXTENSIBLE_CHANNEL_MASK={value}")])), None, "{value}");
|
||||
}
|
||||
assert_eq!(comments_mask(&block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=bad", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"])), Some(3));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_truncated_comment_block_has_no_mask() {
|
||||
let whole = block(&["WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x3"]);
|
||||
for cut in 0..whole.len() {
|
||||
assert_eq!(comments_mask(&whole[..cut]), None, "{cut}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -558,75 +558,3 @@ fn not_built(src: &Src<'_>) -> AudioError {
|
||||
None => AudioError::Unsupported("not a recognized audio format".into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, not(feature = "symphonia")))]
|
||||
mod native_only_tests {
|
||||
use super::*;
|
||||
|
||||
/// Without symphonia, a format with no native decoder is unsupported, not malformed.
|
||||
#[test]
|
||||
fn formats_left_to_symphonia_are_unsupported() {
|
||||
let flac_header = [&b"fLaC"[..], &[0x80, 0, 0, 34], &[0; 34]].concat();
|
||||
assert!(matches!(decode(&flac_header, None), Err(AudioError::Unsupported(m)) if m.contains("FLAC")));
|
||||
assert!(matches!(probe(&flac_header, None), Err(AudioError::Unsupported(_))));
|
||||
// A track list says the same instead of listing nothing.
|
||||
assert!(matches!(tracks(&flac_header, None), Err(AudioError::Unsupported(m)) if m.contains("FLAC")));
|
||||
// Bytes that name no format are not blamed on the build.
|
||||
assert!(matches!(tracks(&[7u8; 64], None), Err(AudioError::Unsupported(m)) if m.contains("not a recognized")));
|
||||
}
|
||||
|
||||
/// A source that cannot be read is an I/O error, not an unrecognized format.
|
||||
#[test]
|
||||
fn a_failed_header_read_is_an_io_error() {
|
||||
struct Failing;
|
||||
impl craft_media::ByteSource for Failing {
|
||||
fn len(&self) -> u64 {
|
||||
1000
|
||||
}
|
||||
fn read_at(&self, _: u64, _: &mut [u8]) -> std::io::Result<()> {
|
||||
Err(std::io::Error::other("disk gone"))
|
||||
}
|
||||
}
|
||||
assert!(matches!(tracks_of(Failing, None), Err(AudioError::Io(_))));
|
||||
assert!(matches!(Decoder::open(Failing, None, &DecodeOptions::default()), Err(AudioError::Io(_))));
|
||||
}
|
||||
|
||||
/// A damaged file in a container the native path reads is malformed, not left to a decoder
|
||||
/// this build lacks.
|
||||
#[test]
|
||||
fn a_damaged_mp4_is_malformed() {
|
||||
// an `ftyp` box and nothing after it: no `moov`
|
||||
let mp4 = [&16u32.to_be_bytes()[..], b"ftypisom", &[0, 0, 2, 0]].concat();
|
||||
assert!(matches!(decode(&mp4, None), Err(AudioError::Malformed(_))));
|
||||
assert!(matches!(tracks(&mp4, None), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
|
||||
/// A source that fails past its first 64 KiB fails inside the demuxer: still an I/O error.
|
||||
#[test]
|
||||
fn a_failed_read_inside_the_demuxer_is_an_io_error() {
|
||||
use craft_media::matroska::{LacingMode, MkvWriter, MuxOptions, TrackKind, TrackSpec};
|
||||
struct FailsLate(Vec<u8>);
|
||||
impl craft_media::ByteSource for FailsLate {
|
||||
fn len(&self) -> u64 {
|
||||
self.0.len() as u64
|
||||
}
|
||||
fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
|
||||
if offset + buf.len() as u64 > 64 * 1024 {
|
||||
return Err(std::io::Error::other("disk gone"));
|
||||
}
|
||||
self.0.read_at(offset, buf)
|
||||
}
|
||||
}
|
||||
// a Matroska PCM file of about 400 KB, whose cues and later clusters lie past 64 KiB
|
||||
let mut spec = TrackSpec::new(TrackKind::Audio, "A_PCM/FLOAT/IEEE");
|
||||
spec.audio = Some((48_000.0, 1, Some(32)));
|
||||
let opts = MuxOptions { lacing: LacingMode::None, ..MuxOptions::default() };
|
||||
let mut w = MkvWriter::new(std::io::Cursor::new(Vec::new()), vec![spec], opts).unwrap();
|
||||
for k in 0..100i64 {
|
||||
w.write_frame(0, k * 20_000_000, true, &[0; 960 * 4], Some(20_000_000)).unwrap();
|
||||
}
|
||||
let file = w.finish().unwrap().into_inner();
|
||||
assert!(matches!(tracks_of(FailsLate(file.clone()), None), Err(AudioError::Io(_))));
|
||||
assert!(matches!(Decoder::open(FailsLate(file), None, &DecodeOptions::default()), Err(AudioError::Io(_))));
|
||||
}
|
||||
}
|
||||
@@ -1383,32 +1383,6 @@ mod adts_tests {
|
||||
w.finish()
|
||||
}
|
||||
|
||||
/// ALAC in MP4 decodes natively (without symphonia this is the only path): every sample,
|
||||
/// the short last packet included, and a seek lands on the exact frame.
|
||||
#[test]
|
||||
fn alac_in_mp4_decodes_and_seeks_natively() {
|
||||
use craft_media::isobmff::{Brand, CodecConfig, FourCc, Mp4Writer, SampleEntry, TrackConfig, WriteSample, WriterOptions};
|
||||
// Escaped (uncompressed) stereo 16-bit packets of 4 frames, the last one of 2.
|
||||
let frames: Vec<[i16; 2]> = (0..10).map(|i| [i * 100 - 300, -(i * 77)]).collect();
|
||||
let packet = |chunk: &[[i16; 2]]| alac_escaped_stereo(chunk, 4);
|
||||
let cookie = crate::alac::SpecificConfig::new(48_000, 2, 16, 4).to_bytes();
|
||||
let entry = SampleEntry::audio(FourCc(*b"alac"), CodecConfig::Alac { cookie }, 2, 48_000.0, 16);
|
||||
let mut w = Mp4Writer::new(std::io::Cursor::new(Vec::new()), WriterOptions::new(Brand::Mp4)).unwrap();
|
||||
let track = w.add_track(TrackConfig::new(entry, 48_000)).unwrap();
|
||||
for chunk in frames.chunks(4) {
|
||||
w.write_sample(track, WriteSample { data: &packet(chunk), duration: chunk.len() as u32, composition_offset: 0, is_sync: true }).unwrap();
|
||||
}
|
||||
let file = w.finish().unwrap().into_inner();
|
||||
let (info, buf) = decode(&file, None).unwrap();
|
||||
assert_eq!((info.codec, info.sample_format, info.sample_rate, info.frames), (crate::CodecId::Alac, crate::SampleFormat::Int16, 48_000, 10));
|
||||
let ints: Vec<[i16; 2]> = (0..buf.frames()).map(|i| [0, 1].map(|c| (buf.channels[c][i] * 32768.0) as i16)).collect();
|
||||
assert_eq!(ints, frames);
|
||||
let mut d = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap();
|
||||
d.seek(5).unwrap();
|
||||
let block = d.next_block().unwrap().unwrap();
|
||||
assert_eq!((block.channels[0][0] * 32768.0) as i16, frames[5][0]);
|
||||
}
|
||||
|
||||
/// ALAC in Matroska seeks to the exact frame: packet starts come from the frame length, not
|
||||
/// from the millisecond timestamps (packet 1 starts at frame 4096, stored as 85 ms = 4080).
|
||||
#[test]
|
||||
|
||||
+10
-562
@@ -4,24 +4,18 @@ use std::borrow::Cow;
|
||||
use std::io::{Cursor, Seek, SeekFrom};
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
|
||||
use symphonia::core::audio::Channels;
|
||||
use symphonia::core::codecs::audio::AudioDecoder;
|
||||
use symphonia::core::codecs::audio::well_known::{
|
||||
CODEC_ID_AAC, CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS,
|
||||
CODEC_ID_ALAC, CODEC_ID_FLAC, CODEC_ID_MP1, CODEC_ID_MP2, CODEC_ID_MP3, CODEC_ID_OPUS, CODEC_ID_PCM_ALAW, CODEC_ID_PCM_F32BE, CODEC_ID_PCM_F32LE,
|
||||
CODEC_ID_PCM_F64BE, CODEC_ID_PCM_F64BE_PLANAR, CODEC_ID_PCM_F64LE, CODEC_ID_PCM_MULAW, CODEC_ID_PCM_S32LE, CODEC_ID_VORBIS,
|
||||
};
|
||||
use symphonia::core::codecs::audio::{AudioCodecId, AudioCodecParameters, AudioDecoderOptions, CODEC_ID_NULL_AUDIO};
|
||||
use symphonia::core::codecs::audio::AudioDecoderOptions;
|
||||
use symphonia::core::codecs::audio::well_known::CODEC_ID_ALAC;
|
||||
use symphonia::core::errors::Error as SymError;
|
||||
use symphonia::core::formats::probe::{Hint, ProbeOptions, ProbeableFormat, Score, Scoreable};
|
||||
use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo, Track};
|
||||
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions, ScopedStream};
|
||||
use symphonia::core::formats::probe::Hint;
|
||||
use symphonia::core::formats::{FormatOptions, FormatReader, SeekMode, SeekTo};
|
||||
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions};
|
||||
use symphonia::core::meta::MetadataOptions;
|
||||
use symphonia::core::units::{TimeBase, Timestamp};
|
||||
|
||||
use super::id3v2_len;
|
||||
use crate::pcm::{MAX_DECODE_SAMPLES, be_u32};
|
||||
use crate::{AudioBuffer, AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result, SampleFormat};
|
||||
use crate::{AudioBuffer, AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result};
|
||||
|
||||
/// The most frames a packet may declare: decoders allocate a packet's frames up front, and ALAC
|
||||
/// takes its frame length from the file (encoders use 4096).
|
||||
@@ -36,45 +30,6 @@ const GAP_BLOCK_FRAMES: u64 = 1 << 16;
|
||||
/// otherwise claim gigabytes before a sample is decoded (64 MiB of `f32`). Ports soundcraft #1332.
|
||||
const MAX_PACKET_SAMPLES: u64 = 1 << 24;
|
||||
|
||||
/// How far [`first_marker`] looks for the first format marker: the same 1 MiB a default symphonia
|
||||
/// probe scans.
|
||||
const MAX_PREFIX_SCAN: usize = 1 << 20;
|
||||
|
||||
/// How many MPEG/ADTS candidates [`first_marker`] may hand to the readers' expensive `Scoreable`
|
||||
/// implementations. A crafted 1 MiB prefix of repeated sync markers otherwise asks for hundreds
|
||||
/// of thousands of scores, each allowed up to symphonia's 16 KiB score depth. Once the budget is
|
||||
/// spent, the scan stops at the next audio candidate: a container-like byte string later in an
|
||||
/// unscored audio payload must not become authoritative. A container marker reached first is still
|
||||
/// checked; an unchecked one the probe selects is refused after probing.
|
||||
const MAX_AUDIO_SCORE_ATTEMPTS: usize = 256;
|
||||
|
||||
/// A per-scan budget for `Scoreable::score` calls. Taking a slot consumes it even when the score
|
||||
/// rejects the candidate, so a stream of false syncs cannot multiply the work.
|
||||
struct ScoreBudget {
|
||||
used: usize,
|
||||
}
|
||||
|
||||
impl ScoreBudget {
|
||||
/// Start a scan with no expensive score attempts spent.
|
||||
fn new() -> Self {
|
||||
Self { used: 0 }
|
||||
}
|
||||
|
||||
/// Spend one score attempt, returning false once the per-scan budget is exhausted.
|
||||
fn take(&mut self) -> bool {
|
||||
if self.exhausted() {
|
||||
return false;
|
||||
}
|
||||
self.used = self.used.saturating_add(1);
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether no attempt is left for this scan.
|
||||
fn exhausted(&self) -> bool {
|
||||
self.used >= MAX_AUDIO_SCORE_ATTEMPTS
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a symphonia error into the audio layer's error, keeping "unsupported" and "too large"
|
||||
/// distinct from a malformed file.
|
||||
fn map_err(e: SymError) -> AudioError {
|
||||
@@ -115,261 +70,10 @@ fn decoder_options() -> AudioDecoderOptions {
|
||||
AudioDecoderOptions::default().gapless(true)
|
||||
}
|
||||
|
||||
/// The first byte after any ID3v2 tags at the start of `b`. Symphonia's tag reader allocates
|
||||
/// whatever a frame claims, so the tags are skipped, not read: they are not used here.
|
||||
fn skip_id3v2(b: &[u8]) -> usize {
|
||||
let mut at = 0usize;
|
||||
loop {
|
||||
match b.get(at..).and_then(id3v2_len) {
|
||||
Some(n) if n > 0 => at = at.saturating_add(n),
|
||||
_ => return at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first format marker the probe can reach from `start`, within its 1 MiB scan limit.
|
||||
#[derive(Clone, Copy)]
|
||||
enum FirstMarker {
|
||||
Flac(usize),
|
||||
Caf(usize),
|
||||
Mp4(usize),
|
||||
Wav(usize),
|
||||
/// MPEG audio, Ogg, Matroska or AIFF: formats with no separate container size check.
|
||||
Audio,
|
||||
}
|
||||
|
||||
/// What the preflight container checks covered before the probe built a reader.
|
||||
enum Precheck {
|
||||
/// A zero-frame FLAC: returned without a reader, because Symphonia 0.6's reader needs a first
|
||||
/// audio frame to resynchronize to.
|
||||
Empty(AudioInfo),
|
||||
/// The size checks ran for the container the probe reports under this short name.
|
||||
Checked(&'static str),
|
||||
/// As `Checked`, for a FLAC stream with this layout, which symphonia's reader does not parse.
|
||||
Flac(&'static str, Option<ChannelLayout>),
|
||||
/// No container size check was needed.
|
||||
Unchecked,
|
||||
}
|
||||
|
||||
/// Probe short names whose demuxer allocates from sizes in the file, so the matching container
|
||||
/// check has to run before the stream is decoded.
|
||||
const SIZE_CHECKED_PROBE_FORMATS: &[&str] = &["caf", "flac", "isomp4", "wave"];
|
||||
|
||||
/// The container markers to check for the family `detected` names. `None` is a raw audio stream
|
||||
/// (MP3, Ogg, AIFF), whose payload may contain container-like bytes: the unrestricted scan below
|
||||
/// finds a container only when one starts the stream, before any audio marker.
|
||||
fn container_markers(detected: Option<Container>) -> Option<&'static [&'static [u8; 4]]> {
|
||||
match detected {
|
||||
// RF64 and BW64 are the >4 GiB RIFF forms.
|
||||
Some(Container::Wav) => Some(&[b"RIFF", b"RF64", b"BW64"]),
|
||||
Some(Container::Flac) => Some(&[b"fLaC"]),
|
||||
Some(Container::Caf) => Some(&[b"caff"]),
|
||||
// MP4/M4A put `ftyp` after the first atom's size field (an `.aac` name may hide one).
|
||||
Some(Container::Mp4 | Container::QuickTime | Container::Adts) => Some(&[b"ftyp"]),
|
||||
Some(Container::Aiff | Container::MpegAudio | Container::Ogg) => None,
|
||||
// Unknown files may carry junk before the container; symphonia's probe scans for markers.
|
||||
_ => Some(&[b"caff", b"ftyp", b"fLaC", b"RIFF"]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe short name a container marker stands for.
|
||||
fn expected_probe_format(marker: &[u8; 4]) -> &'static str {
|
||||
match marker {
|
||||
b"caff" => "caf",
|
||||
// The isomp4 reader reads the `ftyp` atom.
|
||||
b"ftyp" => "isomp4",
|
||||
b"fLaC" => "flac",
|
||||
// RIFF, RF64 and BW64.
|
||||
_ => "wave",
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the first marker of `markers` at or after `at`, within symphonia's probe depth. A RIFF
|
||||
/// form other than WAVE is skipped, as the probe skips it and reads a WAVE behind it.
|
||||
fn find_container_marker<'a>(bytes: &[u8], at: usize, markers: &'a [&'static [u8; 4]]) -> Option<(usize, &'a [u8; 4])> {
|
||||
let end = bytes.len().min(at.saturating_add(MAX_PREFIX_SCAN));
|
||||
for pos in at..end.saturating_sub(3) {
|
||||
let window = bytes.get(pos..pos + 4)?;
|
||||
if let Some(marker) = markers.iter().find(|marker| window == marker.as_slice()) {
|
||||
if matches!(*marker, b"RIFF" | b"RF64" | b"BW64") && bytes.get(pos + 8..pos + 12) != Some(&b"WAVE"[..]) {
|
||||
continue;
|
||||
}
|
||||
return Some((pos, *marker));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The scan variant for a marker found by [`find_container_marker`], with the probe short name its
|
||||
/// size check stands for. `ftyp` sits four bytes into its atom, so the MP4 check starts there.
|
||||
fn marker_kind(at: usize, marker: &[u8; 4]) -> (FirstMarker, &'static str) {
|
||||
match marker {
|
||||
b"fLaC" => (FirstMarker::Flac(at), expected_probe_format(marker)),
|
||||
b"caff" => (FirstMarker::Caf(at), expected_probe_format(marker)),
|
||||
b"ftyp" => (FirstMarker::Mp4(at.saturating_sub(4)), expected_probe_format(marker)),
|
||||
_ => (FirstMarker::Wav(at), expected_probe_format(marker)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe short name a container scan variant stands for.
|
||||
fn marker_name(marker: FirstMarker) -> &'static str {
|
||||
match marker {
|
||||
FirstMarker::Flac(_) => "flac",
|
||||
FirstMarker::Caf(_) => "caf",
|
||||
FirstMarker::Mp4(_) => "isomp4",
|
||||
FirstMarker::Wav(_) => "wave",
|
||||
FirstMarker::Audio => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `rest` starts with one of `R`'s exact registered probe markers.
|
||||
fn has_probe_marker<R: ProbeableFormat<'static>>(rest: &[u8]) -> bool {
|
||||
R::probe_data().iter().any(|data| data.spec.markers.iter().any(|marker| rest.starts_with(marker)))
|
||||
}
|
||||
|
||||
/// Score `R` at `at` exactly as symphonia's private probe does: `Supported` wins, EOF and every
|
||||
/// other scoring error mean "not this format", while a real I/O error aborts the probe.
|
||||
fn scores_supported<R: Scoreable>(stream: &mut MediaSourceStream<'_>, at: usize, depth: u16) -> Result<bool> {
|
||||
stream.seek(SeekFrom::Start(u64::try_from(at).unwrap_or(u64::MAX)))?;
|
||||
match R::score(ScopedStream::new(stream, u64::from(depth))) {
|
||||
Ok(Score::Supported(_)) => Ok(true),
|
||||
Err(SymError::IoError(e)) if e.kind() != std::io::ErrorKind::UnexpectedEof => Err(AudioError::Malformed(e.to_string())),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `b[at..]` is an MPEG/ADTS candidate the probe would actually select: an exact
|
||||
/// `probe_data()` marker and a `Supported` score from the same reader. A loose `0xFFEx` pair is
|
||||
/// not enough: `0xFFE0` is neither a registered marker nor a valid frame, so it must not stop the
|
||||
/// scan before a later FLAC/CAF/MP4 candidate.
|
||||
fn audio_sync_at<'a>(b: &'a [u8], at: usize, stream: &mut Option<MediaSourceStream<'a>>, budget: &mut ScoreBudget) -> Result<bool> {
|
||||
let rest = b.get(at..).unwrap_or_default();
|
||||
let adts = has_probe_marker::<symphonia::default::formats::AdtsReader<'static>>(rest);
|
||||
let mpa = has_probe_marker::<symphonia::default::formats::MpaReader<'static>>(rest);
|
||||
if !adts && !mpa {
|
||||
return Ok(false);
|
||||
}
|
||||
if stream.is_none() {
|
||||
*stream = Some(MediaSourceStream::new(Box::new(Cursor::new(b)), MediaSourceStreamOptions::default()));
|
||||
}
|
||||
let Some(mss) = stream.as_mut() else { return Ok(false) };
|
||||
let depth = ProbeOptions::default().max_score_depth;
|
||||
if adts && budget.take() && scores_supported::<symphonia::default::formats::AdtsReader<'static>>(mss, at, depth)? {
|
||||
return Ok(true);
|
||||
}
|
||||
if mpa && budget.take() && scores_supported::<symphonia::default::formats::MpaReader<'static>>(mss, at, depth)? {
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Find the first marker that can start a container or audio stream. Symphonia's `Probe::probe`
|
||||
/// constructs the reader itself and exposes no pre-construction hook, while checking every magic
|
||||
/// in the scan window would validate bytes the probe never reaches (for example a valid MP3's
|
||||
/// audio payload). Stopping at the first marker avoids that: it is the candidate the probe selects
|
||||
/// for FLAC, CAF, MP4, Ogg and Matroska, and for WAV/AIFF once their full form is verified below.
|
||||
/// MPEG/ADTS candidates are checked with the readers' own `probe_data()`/`Scoreable` APIs, so a
|
||||
/// false sync byte pair cannot stop the scan. If that scoring budget runs out, the scan stops at
|
||||
/// the next audio candidate instead of trusting a container-like byte string later in the unscored
|
||||
/// audio payload. A container marker reached before any such candidate is still preflighted; if
|
||||
/// the probe selects a size-checked container the scan did not check, `open` refuses it.
|
||||
///
|
||||
/// WAV candidates include RF64/BW64 so `check_info` can run, although symphonia 0.6 registers only
|
||||
/// the RIFF marker. Native PCM RF64/BW64 is parsed by `wav::parse` before this path; a foreign
|
||||
/// RF64/BW64 stream therefore remains unsupported by the probe rather than misdetected.
|
||||
fn first_marker(b: &[u8], start: usize) -> Result<Option<FirstMarker>> {
|
||||
first_marker_with_budget(b, start, &mut ScoreBudget::new())
|
||||
}
|
||||
|
||||
/// [`first_marker`] with an explicit score budget, so a test can prove a prefix crowded with
|
||||
/// false sync markers performs only the bounded number of reader scores.
|
||||
fn first_marker_with_budget(b: &[u8], start: usize, budget: &mut ScoreBudget) -> Result<Option<FirstMarker>> {
|
||||
let end = b.len().min(start.saturating_add(MAX_PREFIX_SCAN));
|
||||
let mut at = start;
|
||||
let mut audio_probe = None;
|
||||
while at.saturating_add(4) <= end {
|
||||
let rest = b.get(at..).unwrap_or_default();
|
||||
if rest.get(..4) == Some(b"fLaC".as_slice()) {
|
||||
return Ok(Some(FirstMarker::Flac(at)));
|
||||
}
|
||||
if rest.get(..4) == Some(b"caff".as_slice()) {
|
||||
return Ok(Some(FirstMarker::Caf(at)));
|
||||
}
|
||||
if rest.get(..4) == Some(b"OggS".as_slice()) || rest.get(..4) == Some(b"\x1A\x45\xDF\xA3".as_slice()) || super::aiff::is_aiff(rest) {
|
||||
return Ok(Some(FirstMarker::Audio));
|
||||
}
|
||||
if super::wav::is_wav(rest) {
|
||||
return Ok(Some(FirstMarker::Wav(at)));
|
||||
}
|
||||
if let (Some(&b0), Some(&b1)) = (b.get(at), b.get(at + 1))
|
||||
&& b0 == 0xFF
|
||||
&& b1 & 0xE0 == 0xE0
|
||||
{
|
||||
// A candidate after the cap cannot be scored. Stop rather than let a container-like
|
||||
// byte string later in an unscored audio payload become preflight-authoritative; the
|
||||
// probe will select the reader, and `open` refuses an unchecked size-checked one.
|
||||
if budget.exhausted() {
|
||||
return Ok(None);
|
||||
}
|
||||
if audio_sync_at(b, at, &mut audio_probe, budget)? {
|
||||
return Ok(Some(FirstMarker::Audio));
|
||||
}
|
||||
}
|
||||
if rest.get(4..8) == Some(b"ftyp".as_slice()) {
|
||||
return Ok(Some(FirstMarker::Mp4(at)));
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Run the early size checks on the container the probe can select. `start` is the first byte
|
||||
/// after leading ID3v2 tags. A zero-frame FLAC is returned as an empty stream because Symphonia
|
||||
/// 0.6's reader requires a first audio frame to resynchronize to.
|
||||
fn precheck(b: &[u8], start: usize, detected: Option<Container>) -> Result<Precheck> {
|
||||
let any_marker = |b: &[u8], start: usize| -> Result<Option<(FirstMarker, &'static str)>> {
|
||||
Ok(match first_marker(b, start)? {
|
||||
// Stop at the first marker of any kind, so container magic incidental to an audio
|
||||
// payload is not mistaken for the stream's container.
|
||||
Some(FirstMarker::Audio) | None => None,
|
||||
Some(marker) => Some((marker, marker_name(marker))),
|
||||
})
|
||||
};
|
||||
let found = match container_markers(detected) {
|
||||
// Follow the detection: check the first marker of the family it names, so a misleading
|
||||
// marker cannot let a differently sized container reach the probe unchecked. A detection
|
||||
// is only a hint, though: when the stream holds none of its markers (a FLAC behind a
|
||||
// `.mp3` name), the probe can still select another container, which is checked here.
|
||||
Some(markers) => match find_container_marker(b, start, markers) {
|
||||
Some((at, marker)) => Some(marker_kind(at, marker)),
|
||||
None => any_marker(b, start)?,
|
||||
},
|
||||
None => any_marker(b, start)?,
|
||||
};
|
||||
let Some((marker, expected)) = found else { return Ok(Precheck::Unchecked) };
|
||||
match marker {
|
||||
FirstMarker::Flac(at) => {
|
||||
super::flac::check_metadata(b, at)?;
|
||||
if let Some(info) = super::flac::empty_stream_info(b, at) {
|
||||
return Ok(Precheck::Empty(info));
|
||||
}
|
||||
Ok(Precheck::Flac(expected, super::flac::layout(b, at)))
|
||||
}
|
||||
FirstMarker::Caf(at) => {
|
||||
super::caf::check(b, at)?;
|
||||
Ok(Precheck::Checked(expected))
|
||||
}
|
||||
FirstMarker::Mp4(at) => {
|
||||
super::mp4::check(b, at)?;
|
||||
Ok(Precheck::Checked(expected))
|
||||
}
|
||||
FirstMarker::Wav(at) => {
|
||||
super::wav::check_info(b, at)?;
|
||||
Ok(Precheck::Checked(expected))
|
||||
}
|
||||
FirstMarker::Audio => Ok(Precheck::Unchecked),
|
||||
}
|
||||
}
|
||||
mod map;
|
||||
mod precheck;
|
||||
use map::{audio_params, audio_tracks, codec_id_of, info_of};
|
||||
use precheck::{MAX_PREFIX_SCAN, Precheck, SIZE_CHECKED_PROBE_FORMATS, precheck, skip_id3v2};
|
||||
|
||||
/// `block` without the frames still to drop after a seek landed before its target; `None` when
|
||||
/// that is all of it.
|
||||
@@ -433,133 +137,6 @@ fn open(bytes: Cow<'_, [u8]>, detected: Option<Container>) -> Result<Opened> {
|
||||
Ok(Opened::Reader(reader, preread))
|
||||
}
|
||||
|
||||
/// The codec symphonia reports, as a [`CodecId`].
|
||||
fn codec_id_of(c: AudioCodecId) -> CodecId {
|
||||
match c {
|
||||
c if (CODEC_ID_PCM_S32LE..=CODEC_ID_PCM_F64BE_PLANAR).contains(&c) => CodecId::Pcm,
|
||||
c if c == CODEC_ID_PCM_ALAW => CodecId::ALaw,
|
||||
c if c == CODEC_ID_PCM_MULAW => CodecId::MuLaw,
|
||||
c if [CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS]
|
||||
.contains(&c) =>
|
||||
{
|
||||
CodecId::Adpcm
|
||||
}
|
||||
c if c == CODEC_ID_FLAC => CodecId::Flac,
|
||||
c if c == CODEC_ID_ALAC => CodecId::Alac,
|
||||
c if c == CODEC_ID_AAC => CodecId::Aac,
|
||||
c if c == CODEC_ID_MP1 => CodecId::Mp1,
|
||||
c if c == CODEC_ID_MP2 => CodecId::Mp2,
|
||||
c if c == CODEC_ID_MP3 => CodecId::Mp3,
|
||||
c if c == CODEC_ID_OPUS => CodecId::Opus,
|
||||
c if c == CODEC_ID_VORBIS => CodecId::Vorbis,
|
||||
_ => CodecId::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// The container a symphonia reader stands for, refined by the detection (which tells MP4 from
|
||||
/// QuickTime and Matroska from WebM).
|
||||
fn container_of(short_name: &str, detected: Option<Container>) -> Container {
|
||||
match short_name {
|
||||
"wave" => Container::Wav,
|
||||
"aiff" => Container::Aiff,
|
||||
"flac" => Container::Flac,
|
||||
"caf" => Container::Caf,
|
||||
"ogg" => Container::Ogg,
|
||||
"isomp4" if detected == Some(Container::QuickTime) => Container::QuickTime,
|
||||
"isomp4" => Container::Mp4,
|
||||
"matroska" if detected == Some(Container::WebM) => Container::WebM,
|
||||
"matroska" => Container::Matroska,
|
||||
"mp1" | "mp2" | "mp3" => Container::MpegAudio,
|
||||
"aac" | "adts" => Container::Adts,
|
||||
_ => detected.unwrap_or(Container::MpegAudio),
|
||||
}
|
||||
}
|
||||
|
||||
/// The speakers of symphonia's channel description; its first 18 position bits are the WAV mask
|
||||
/// bits, and its decoded planes follow them.
|
||||
fn layout_of(channels: Option<&Channels>) -> ChannelLayout {
|
||||
match channels {
|
||||
Some(Channels::Positioned(p)) => {
|
||||
let bits = p.bits();
|
||||
match u32::try_from(bits) {
|
||||
Ok(mask) if mask != 0 => ChannelLayout::from_mask(mask),
|
||||
_ => ChannelLayout::unordered(bits.count_ones() as u16),
|
||||
}
|
||||
}
|
||||
Some(c) => ChannelLayout::unordered(crate::layout::count(c.count())),
|
||||
None => ChannelLayout::unordered(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored sample format, using the codec and its declared bit depth. Lossy and unusual
|
||||
/// codecs decode to `Compressed`.
|
||||
fn sample_format_of(p: &AudioCodecParameters) -> SampleFormat {
|
||||
let c = p.codec;
|
||||
if c == CODEC_ID_PCM_F32LE || c == CODEC_ID_PCM_F32BE {
|
||||
return SampleFormat::Float32;
|
||||
}
|
||||
if c == CODEC_ID_PCM_F64LE || c == CODEC_ID_PCM_F64BE {
|
||||
return SampleFormat::Float64;
|
||||
}
|
||||
let lossy = [
|
||||
CODEC_ID_MP1,
|
||||
CODEC_ID_MP2,
|
||||
CODEC_ID_MP3,
|
||||
CODEC_ID_AAC,
|
||||
CODEC_ID_VORBIS,
|
||||
CODEC_ID_OPUS,
|
||||
CODEC_ID_ADPCM_MS,
|
||||
CODEC_ID_ADPCM_IMA_WAV,
|
||||
CODEC_ID_ADPCM_IMA_QT,
|
||||
CODEC_ID_ADPCM_G722,
|
||||
CODEC_ID_ADPCM_G726,
|
||||
CODEC_ID_ADPCM_G726LE,
|
||||
CODEC_ID_PCM_ALAW,
|
||||
CODEC_ID_PCM_MULAW,
|
||||
];
|
||||
let lossless = !lossy.contains(&c);
|
||||
match (lossless, p.bits_per_sample) {
|
||||
(true, Some(1..=8)) => SampleFormat::Int8,
|
||||
(true, Some(9..=16)) => SampleFormat::Int16,
|
||||
(true, Some(17..=24)) => SampleFormat::Int24,
|
||||
(true, Some(25..=32)) => SampleFormat::Int32,
|
||||
_ => SampleFormat::Compressed,
|
||||
}
|
||||
}
|
||||
|
||||
/// The audio parameters of `track`, if it carries any.
|
||||
fn audio_params(track: &Track) -> Option<&AudioCodecParameters> {
|
||||
track.codec_params.as_ref()?.audio()
|
||||
}
|
||||
|
||||
/// The audio tracks with a decodable codec.
|
||||
fn audio_tracks(reader: &dyn FormatReader) -> impl Iterator<Item = &Track> {
|
||||
reader.tracks().iter().filter(|t| audio_params(t).is_some_and(|p| p.codec != CODEC_ID_NULL_AUDIO))
|
||||
}
|
||||
|
||||
/// The `n`-th audio track (the first when `None`), counting an Ogg file's `streams` in file order
|
||||
/// when they are known. With no `n`, the first stream symphonia has a track for: it has none for
|
||||
/// some of the codecs `tracks` lists.
|
||||
fn pick_track<'a>(reader: &'a dyn FormatReader, streams: &[(u32, Option<u32>)], n: Option<usize>) -> Option<&'a Track> {
|
||||
let with_serial = |serial: u32| audio_tracks(reader).find(|t| t.id == serial);
|
||||
match n {
|
||||
_ if streams.is_empty() => audio_tracks(reader).nth(n.unwrap_or(0)),
|
||||
Some(n) => with_serial(streams.get(n)?.0),
|
||||
None => streams.iter().find_map(|s| with_serial(s.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `n`-th audio track (see [`pick_track`]), with the stream information the UI shows.
|
||||
fn info_of(reader: &dyn FormatReader, detected: Option<Container>, ogg_streams: &[(u32, Option<u32>)], n: Option<usize>) -> Result<(u32, AudioInfo)> {
|
||||
let container = container_of(reader.format_info().short_name, detected);
|
||||
let track = pick_track(reader, ogg_streams, n).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?;
|
||||
let p = audio_params(track).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?;
|
||||
let sample_rate = p.sample_rate.filter(|&r| r > 0).ok_or_else(|| AudioError::Malformed("unknown sample rate".into()))?;
|
||||
let layout = layout_of(p.channels.as_ref());
|
||||
let frames = track.num_frames.unwrap_or(0);
|
||||
Ok((track.id, AudioInfo::new(container, codec_id_of(p.codec), sample_format_of(p), sample_rate, layout, frames)))
|
||||
}
|
||||
|
||||
/// A demux error ends the decode; it is only an error when nothing was decoded yet.
|
||||
fn demux_failure(frames: u64, e: SymError) -> Result<()> {
|
||||
if frames == 0 {
|
||||
@@ -886,132 +463,3 @@ pub(crate) fn tracks(bytes: Cow<'_, [u8]>, detected: Option<Container>) -> Resul
|
||||
.collect())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use symphonia::core::codecs::audio::well_known::{
|
||||
CODEC_ID_AAC, CODEC_ID_ADPCM_MS, CODEC_ID_ALAC, CODEC_ID_FLAC, CODEC_ID_MP3, CODEC_ID_PCM_F32LE, CODEC_ID_PCM_F64LE, CODEC_ID_PCM_S16LE,
|
||||
CODEC_ID_VORBIS,
|
||||
};
|
||||
|
||||
/// Build codec parameters for a test, optionally declaring a bit depth.
|
||||
fn params(codec: AudioCodecId, bits_per_sample: Option<u32>) -> AudioCodecParameters {
|
||||
let mut params = AudioCodecParameters::new();
|
||||
params.for_codec(codec);
|
||||
if let Some(bits) = bits_per_sample {
|
||||
params.with_bits_per_sample(bits);
|
||||
}
|
||||
params
|
||||
}
|
||||
|
||||
/// symphonia's codec ids map to ours, PCM by its id range.
|
||||
#[test]
|
||||
fn codecs_map_to_codec_ids() {
|
||||
assert_eq!(codec_id_of(CODEC_ID_FLAC), CodecId::Flac);
|
||||
assert_eq!(codec_id_of(CODEC_ID_MP3), CodecId::Mp3);
|
||||
assert_eq!(codec_id_of(CODEC_ID_ALAC), CodecId::Alac);
|
||||
assert_eq!(codec_id_of(CODEC_ID_VORBIS), CodecId::Vorbis);
|
||||
assert_eq!(codec_id_of(CODEC_ID_PCM_S16LE), CodecId::Pcm);
|
||||
assert_eq!(codec_id_of(CODEC_ID_PCM_F64LE), CodecId::Pcm);
|
||||
assert_eq!(codec_id_of(CODEC_ID_ADPCM_MS), CodecId::Adpcm);
|
||||
assert_eq!(codec_id_of(CODEC_ID_PCM_ALAW), CodecId::ALaw);
|
||||
}
|
||||
|
||||
/// The reader names the container; the detection refines MP4 into QuickTime and Matroska into WebM.
|
||||
#[test]
|
||||
fn readers_map_to_containers() {
|
||||
assert_eq!(container_of("isomp4", None), Container::Mp4);
|
||||
assert_eq!(container_of("isomp4", Some(Container::QuickTime)), Container::QuickTime);
|
||||
assert_eq!(container_of("matroska", Some(Container::WebM)), Container::WebM);
|
||||
assert_eq!(container_of("mp3", None), Container::MpegAudio);
|
||||
assert_eq!(container_of("wave", Some(Container::Wav)), Container::Wav);
|
||||
}
|
||||
|
||||
/// PCM and FLAC keep their declared bit depth; lossy codecs report `Compressed` regardless of their decoded
|
||||
/// width.
|
||||
#[test]
|
||||
fn sample_formats_keep_their_depth_and_lossy_marker() {
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_PCM_S16LE, Some(16))), SampleFormat::Int16);
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_FLAC, Some(24))), SampleFormat::Int24);
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_FLAC, Some(8))), SampleFormat::Int8);
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_FLAC, Some(32))), SampleFormat::Int32);
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_PCM_F32LE, Some(32))), SampleFormat::Float32);
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_PCM_F64LE, Some(64))), SampleFormat::Float64);
|
||||
// Lossy codecs report no fixed bit depth, whatever their decoded sample format is.
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_AAC, Some(16))), SampleFormat::Compressed);
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_ADPCM_MS, Some(4))), SampleFormat::Compressed);
|
||||
assert_eq!(sample_format_of(¶ms(CODEC_ID_ALAC, None)), SampleFormat::Compressed);
|
||||
}
|
||||
|
||||
/// Decoder options keep gapless trimming enabled so the encoder delay and padding reported by the demuxer are
|
||||
/// removed.
|
||||
#[test]
|
||||
fn gapless_decoding_stays_enabled() {
|
||||
assert!(decoder_options().gapless);
|
||||
}
|
||||
|
||||
/// A complete MPEG frame header is a candidate; loose or unregistered sync pairs are rejected before scoring,
|
||||
/// while a registered but truncated header is rejected by the reader's score after consuming a budget slot.
|
||||
#[test]
|
||||
fn only_the_readers_own_audio_markers_are_candidates() {
|
||||
/// Whether the preflight would score `b` as an audio candidate at offset 0.
|
||||
fn candidate(b: &[u8]) -> bool {
|
||||
let mut stream = None;
|
||||
let mut budget = ScoreBudget::new();
|
||||
matches!(audio_sync_at(b, 0, &mut stream, &mut budget), Ok(true))
|
||||
}
|
||||
let mut mp3_frame = vec![0u8; 417];
|
||||
mp3_frame[..4].copy_from_slice(&[0xFF, 0xFB, 0x90, 0x00]); // MPEG-1 Layer III, 128 kbps, 44.1 kHz
|
||||
assert!(candidate(&[&mp3_frame[..], &mp3_frame].concat()));
|
||||
for false_sync in [vec![0xFF, 0xE0, 0x00], vec![0xFF, 0xF0, 0x00], vec![0xFF, 0xFB, 0xF0, 0x00]] {
|
||||
assert!(!candidate(&false_sync), "{false_sync:?} is not a probe candidate");
|
||||
}
|
||||
}
|
||||
|
||||
/// A prefix made of false MPEG sync markers must not ask the readers to score every byte
|
||||
/// position: the per-scan budget caps the expensive work. A cheap container marker reached
|
||||
/// before the next audio candidate is still found, but once the cap is spent an audio
|
||||
/// candidate stops the scan so later payload magic cannot be preflight-authoritative.
|
||||
#[test]
|
||||
fn a_prefix_crowded_with_sync_markers_scores_only_the_budget() {
|
||||
let mut crowded = vec![0u8; 1 << 16];
|
||||
for pair in crowded.as_chunks_mut::<2>().0 {
|
||||
pair.copy_from_slice(&[0xFF, 0xE2]);
|
||||
}
|
||||
let mut budget = ScoreBudget::new();
|
||||
assert!(matches!(first_marker_with_budget(&crowded, 0, &mut budget), Ok(None)));
|
||||
assert_eq!(budget.used, MAX_AUDIO_SCORE_ATTEMPTS, "no candidate after the cap is scored");
|
||||
|
||||
// At the cap boundary, with no later audio candidate, the cheap marker is still found.
|
||||
let mut at_cap: Vec<u8> = (0..MAX_AUDIO_SCORE_ATTEMPTS).flat_map(|_| [0xFFu8, 0xE2]).collect();
|
||||
at_cap.extend_from_slice(b"fLaC");
|
||||
let mut budget = ScoreBudget::new();
|
||||
assert!(
|
||||
matches!(first_marker_with_budget(&at_cap, 0, &mut budget), Ok(Some(FirstMarker::Flac(_)))),
|
||||
"a container marker reached before the next audio candidate is still found"
|
||||
);
|
||||
assert_eq!(budget.used, MAX_AUDIO_SCORE_ATTEMPTS);
|
||||
|
||||
// One more false candidate between the cap and the magic makes the scan stop unchecked:
|
||||
// the same magic could instead sit in a valid audio payload.
|
||||
let mut after_candidate = at_cap[..2 * MAX_AUDIO_SCORE_ATTEMPTS].to_vec();
|
||||
after_candidate.extend_from_slice(&[0xFF, 0xE2]);
|
||||
after_candidate.extend_from_slice(b"fLaC");
|
||||
let mut budget = ScoreBudget::new();
|
||||
assert!(matches!(first_marker_with_budget(&after_candidate, 0, &mut budget), Ok(None)), "an audio candidate after the cap stops the scan");
|
||||
assert_eq!(budget.used, MAX_AUDIO_SCORE_ATTEMPTS);
|
||||
}
|
||||
|
||||
/// ID3v2 sizes are read in their 7-bit syncsafe form; consecutive tags are skipped by their declared sizes, and
|
||||
/// the v2.3 reserved footer bit does not extend a tag.
|
||||
#[test]
|
||||
fn leading_id3_tags_are_skipped_by_their_declared_size() {
|
||||
let tag = [&b"ID3\x04\0\0\0\0\0\x05"[..], b"hello"].concat();
|
||||
assert_eq!(skip_id3v2(&[&tag[..], &tag[..]].concat()), 30);
|
||||
assert_eq!(skip_id3v2(b"fLaC"), 0);
|
||||
// The 10-byte footer flag exists only in v2.4; the same bit in v2.3 is reserved.
|
||||
assert_eq!(id3v2_len(b"ID3\x03\0\x10\0\0\0\0"), Some(10));
|
||||
assert_eq!(id3v2_len(b"ID3\x04\0\x10\0\0\0\0"), Some(20));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
//! Mapping from symphonia codec, layout and track types to the crate's own.
|
||||
|
||||
use crate::{AudioError, AudioInfo, ChannelLayout, CodecId, Container, Result, SampleFormat};
|
||||
use symphonia::core::audio::Channels;
|
||||
use symphonia::core::codecs::audio::well_known::{
|
||||
CODEC_ID_AAC, CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS,
|
||||
CODEC_ID_ALAC, CODEC_ID_FLAC, CODEC_ID_MP1, CODEC_ID_MP2, CODEC_ID_MP3, CODEC_ID_OPUS, CODEC_ID_PCM_ALAW, CODEC_ID_PCM_F32BE, CODEC_ID_PCM_F32LE,
|
||||
CODEC_ID_PCM_F64BE, CODEC_ID_PCM_F64BE_PLANAR, CODEC_ID_PCM_F64LE, CODEC_ID_PCM_MULAW, CODEC_ID_PCM_S32LE, CODEC_ID_VORBIS,
|
||||
};
|
||||
use symphonia::core::codecs::audio::{AudioCodecId, AudioCodecParameters, CODEC_ID_NULL_AUDIO};
|
||||
use symphonia::core::formats::{FormatReader, Track};
|
||||
|
||||
/// The codec symphonia reports, as a [`CodecId`].
|
||||
pub(super) fn codec_id_of(c: AudioCodecId) -> CodecId {
|
||||
match c {
|
||||
c if (CODEC_ID_PCM_S32LE..=CODEC_ID_PCM_F64BE_PLANAR).contains(&c) => CodecId::Pcm,
|
||||
c if c == CODEC_ID_PCM_ALAW => CodecId::ALaw,
|
||||
c if c == CODEC_ID_PCM_MULAW => CodecId::MuLaw,
|
||||
c if [CODEC_ID_ADPCM_G722, CODEC_ID_ADPCM_G726, CODEC_ID_ADPCM_G726LE, CODEC_ID_ADPCM_IMA_QT, CODEC_ID_ADPCM_IMA_WAV, CODEC_ID_ADPCM_MS]
|
||||
.contains(&c) =>
|
||||
{
|
||||
CodecId::Adpcm
|
||||
}
|
||||
c if c == CODEC_ID_FLAC => CodecId::Flac,
|
||||
c if c == CODEC_ID_ALAC => CodecId::Alac,
|
||||
c if c == CODEC_ID_AAC => CodecId::Aac,
|
||||
c if c == CODEC_ID_MP1 => CodecId::Mp1,
|
||||
c if c == CODEC_ID_MP2 => CodecId::Mp2,
|
||||
c if c == CODEC_ID_MP3 => CodecId::Mp3,
|
||||
c if c == CODEC_ID_OPUS => CodecId::Opus,
|
||||
c if c == CODEC_ID_VORBIS => CodecId::Vorbis,
|
||||
_ => CodecId::Unknown,
|
||||
}
|
||||
}
|
||||
|
||||
/// The container a symphonia reader stands for, refined by the detection (which tells MP4 from
|
||||
/// QuickTime and Matroska from WebM).
|
||||
pub(super) fn container_of(short_name: &str, detected: Option<Container>) -> Container {
|
||||
match short_name {
|
||||
"wave" => Container::Wav,
|
||||
"aiff" => Container::Aiff,
|
||||
"flac" => Container::Flac,
|
||||
"caf" => Container::Caf,
|
||||
"ogg" => Container::Ogg,
|
||||
"isomp4" if detected == Some(Container::QuickTime) => Container::QuickTime,
|
||||
"isomp4" => Container::Mp4,
|
||||
"matroska" if detected == Some(Container::WebM) => Container::WebM,
|
||||
"matroska" => Container::Matroska,
|
||||
"mp1" | "mp2" | "mp3" => Container::MpegAudio,
|
||||
"aac" | "adts" => Container::Adts,
|
||||
_ => detected.unwrap_or(Container::MpegAudio),
|
||||
}
|
||||
}
|
||||
|
||||
/// The speakers of symphonia's channel description; its first 18 position bits are the WAV mask
|
||||
/// bits, and its decoded planes follow them.
|
||||
fn layout_of(channels: Option<&Channels>) -> ChannelLayout {
|
||||
match channels {
|
||||
Some(Channels::Positioned(p)) => {
|
||||
let bits = p.bits();
|
||||
match u32::try_from(bits) {
|
||||
Ok(mask) if mask != 0 => ChannelLayout::from_mask(mask),
|
||||
_ => ChannelLayout::unordered(bits.count_ones() as u16),
|
||||
}
|
||||
}
|
||||
Some(c) => ChannelLayout::unordered(crate::layout::count(c.count())),
|
||||
None => ChannelLayout::unordered(0),
|
||||
}
|
||||
}
|
||||
|
||||
/// The stored sample format, using the codec and its declared bit depth. Lossy and unusual
|
||||
/// codecs decode to `Compressed`.
|
||||
pub(super) fn sample_format_of(p: &AudioCodecParameters) -> SampleFormat {
|
||||
let c = p.codec;
|
||||
if c == CODEC_ID_PCM_F32LE || c == CODEC_ID_PCM_F32BE {
|
||||
return SampleFormat::Float32;
|
||||
}
|
||||
if c == CODEC_ID_PCM_F64LE || c == CODEC_ID_PCM_F64BE {
|
||||
return SampleFormat::Float64;
|
||||
}
|
||||
let lossy = [
|
||||
CODEC_ID_MP1,
|
||||
CODEC_ID_MP2,
|
||||
CODEC_ID_MP3,
|
||||
CODEC_ID_AAC,
|
||||
CODEC_ID_VORBIS,
|
||||
CODEC_ID_OPUS,
|
||||
CODEC_ID_ADPCM_MS,
|
||||
CODEC_ID_ADPCM_IMA_WAV,
|
||||
CODEC_ID_ADPCM_IMA_QT,
|
||||
CODEC_ID_ADPCM_G722,
|
||||
CODEC_ID_ADPCM_G726,
|
||||
CODEC_ID_ADPCM_G726LE,
|
||||
CODEC_ID_PCM_ALAW,
|
||||
CODEC_ID_PCM_MULAW,
|
||||
];
|
||||
let lossless = !lossy.contains(&c);
|
||||
match (lossless, p.bits_per_sample) {
|
||||
(true, Some(1..=8)) => SampleFormat::Int8,
|
||||
(true, Some(9..=16)) => SampleFormat::Int16,
|
||||
(true, Some(17..=24)) => SampleFormat::Int24,
|
||||
(true, Some(25..=32)) => SampleFormat::Int32,
|
||||
_ => SampleFormat::Compressed,
|
||||
}
|
||||
}
|
||||
|
||||
/// The audio parameters of `track`, if it carries any.
|
||||
pub(super) fn audio_params(track: &Track) -> Option<&AudioCodecParameters> {
|
||||
track.codec_params.as_ref()?.audio()
|
||||
}
|
||||
|
||||
/// The audio tracks with a decodable codec.
|
||||
pub(super) fn audio_tracks(reader: &dyn FormatReader) -> impl Iterator<Item = &Track> {
|
||||
reader.tracks().iter().filter(|t| audio_params(t).is_some_and(|p| p.codec != CODEC_ID_NULL_AUDIO))
|
||||
}
|
||||
|
||||
/// The `n`-th audio track (the first when `None`), counting an Ogg file's `streams` in file order
|
||||
/// when they are known. With no `n`, the first stream symphonia has a track for: it has none for
|
||||
/// some of the codecs `tracks` lists.
|
||||
fn pick_track<'a>(reader: &'a dyn FormatReader, streams: &[(u32, Option<u32>)], n: Option<usize>) -> Option<&'a Track> {
|
||||
let with_serial = |serial: u32| audio_tracks(reader).find(|t| t.id == serial);
|
||||
match n {
|
||||
_ if streams.is_empty() => audio_tracks(reader).nth(n.unwrap_or(0)),
|
||||
Some(n) => with_serial(streams.get(n)?.0),
|
||||
None => streams.iter().find_map(|s| with_serial(s.0)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The `n`-th audio track (see [`pick_track`]), with the stream information the UI shows.
|
||||
pub(super) fn info_of(
|
||||
reader: &dyn FormatReader,
|
||||
detected: Option<Container>,
|
||||
ogg_streams: &[(u32, Option<u32>)],
|
||||
n: Option<usize>,
|
||||
) -> Result<(u32, AudioInfo)> {
|
||||
let container = container_of(reader.format_info().short_name, detected);
|
||||
let track = pick_track(reader, ogg_streams, n).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?;
|
||||
let p = audio_params(track).ok_or_else(|| AudioError::Unsupported("no decodable audio track".into()))?;
|
||||
let sample_rate = p.sample_rate.filter(|&r| r > 0).ok_or_else(|| AudioError::Malformed("unknown sample rate".into()))?;
|
||||
let layout = layout_of(p.channels.as_ref());
|
||||
let frames = track.num_frames.unwrap_or(0);
|
||||
Ok((track.id, AudioInfo::new(container, codec_id_of(p.codec), sample_format_of(p), sample_rate, layout, frames)))
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
//! Container preflight: ID3v2 skipping, the budgeted marker scan and the size checks that run before probing.
|
||||
|
||||
use super::super::id3v2_len;
|
||||
use crate::{AudioError, AudioInfo, ChannelLayout, Container, Result};
|
||||
use std::io::{Cursor, Seek, SeekFrom};
|
||||
use symphonia::core::errors::Error as SymError;
|
||||
use symphonia::core::formats::probe::{ProbeOptions, ProbeableFormat, Score, Scoreable};
|
||||
use symphonia::core::io::{MediaSourceStream, MediaSourceStreamOptions, ScopedStream};
|
||||
|
||||
/// How far [`first_marker`] looks for the first format marker: the same 1 MiB a default symphonia
|
||||
/// probe scans.
|
||||
pub(super) const MAX_PREFIX_SCAN: usize = 1 << 20;
|
||||
|
||||
/// How many MPEG/ADTS candidates [`first_marker`] may hand to the readers' expensive `Scoreable`
|
||||
/// implementations. A crafted 1 MiB prefix of repeated sync markers otherwise asks for hundreds
|
||||
/// of thousands of scores, each allowed up to symphonia's 16 KiB score depth. Once the budget is
|
||||
/// spent, the scan stops at the next audio candidate: a container-like byte string later in an
|
||||
/// unscored audio payload must not become authoritative. A container marker reached first is still
|
||||
/// checked; an unchecked one the probe selects is refused after probing.
|
||||
pub(super) const MAX_AUDIO_SCORE_ATTEMPTS: usize = 256;
|
||||
|
||||
/// A per-scan budget for `Scoreable::score` calls. Taking a slot consumes it even when the score
|
||||
/// rejects the candidate, so a stream of false syncs cannot multiply the work.
|
||||
pub(super) struct ScoreBudget {
|
||||
pub(super) used: usize,
|
||||
}
|
||||
|
||||
impl ScoreBudget {
|
||||
/// Start a scan with no expensive score attempts spent.
|
||||
pub(super) fn new() -> Self {
|
||||
Self { used: 0 }
|
||||
}
|
||||
|
||||
/// Spend one score attempt, returning false once the per-scan budget is exhausted.
|
||||
pub(super) fn take(&mut self) -> bool {
|
||||
if self.exhausted() {
|
||||
return false;
|
||||
}
|
||||
self.used = self.used.saturating_add(1);
|
||||
true
|
||||
}
|
||||
|
||||
/// Whether no attempt is left for this scan.
|
||||
pub(super) fn exhausted(&self) -> bool {
|
||||
self.used >= MAX_AUDIO_SCORE_ATTEMPTS
|
||||
}
|
||||
}
|
||||
|
||||
/// The first byte after any ID3v2 tags at the start of `b`. Symphonia's tag reader allocates
|
||||
/// whatever a frame claims, so the tags are skipped, not read: they are not used here.
|
||||
pub(super) fn skip_id3v2(b: &[u8]) -> usize {
|
||||
let mut at = 0usize;
|
||||
loop {
|
||||
match b.get(at..).and_then(id3v2_len) {
|
||||
Some(n) if n > 0 => at = at.saturating_add(n),
|
||||
_ => return at,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The first format marker the probe can reach from `start`, within its 1 MiB scan limit.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum FirstMarker {
|
||||
Flac(usize),
|
||||
Caf(usize),
|
||||
Mp4(usize),
|
||||
Wav(usize),
|
||||
/// MPEG audio, Ogg, Matroska or AIFF: formats with no separate container size check.
|
||||
Audio,
|
||||
}
|
||||
|
||||
/// What the preflight container checks covered before the probe built a reader.
|
||||
pub(super) enum Precheck {
|
||||
/// A zero-frame FLAC: returned without a reader, because Symphonia 0.6's reader needs a first
|
||||
/// audio frame to resynchronize to.
|
||||
Empty(AudioInfo),
|
||||
/// The size checks ran for the container the probe reports under this short name.
|
||||
Checked(&'static str),
|
||||
/// As `Checked`, for a FLAC stream with this layout, which symphonia's reader does not parse.
|
||||
Flac(&'static str, Option<ChannelLayout>),
|
||||
/// No container size check was needed.
|
||||
Unchecked,
|
||||
}
|
||||
|
||||
/// Probe short names whose demuxer allocates from sizes in the file, so the matching container
|
||||
/// check has to run before the stream is decoded.
|
||||
pub(super) const SIZE_CHECKED_PROBE_FORMATS: &[&str] = &["caf", "flac", "isomp4", "wave"];
|
||||
|
||||
/// The container markers to check for the family `detected` names. `None` is a raw audio stream
|
||||
/// (MP3, Ogg, AIFF), whose payload may contain container-like bytes: the unrestricted scan below
|
||||
/// finds a container only when one starts the stream, before any audio marker.
|
||||
fn container_markers(detected: Option<Container>) -> Option<&'static [&'static [u8; 4]]> {
|
||||
match detected {
|
||||
// RF64 and BW64 are the >4 GiB RIFF forms.
|
||||
Some(Container::Wav) => Some(&[b"RIFF", b"RF64", b"BW64"]),
|
||||
Some(Container::Flac) => Some(&[b"fLaC"]),
|
||||
Some(Container::Caf) => Some(&[b"caff"]),
|
||||
// MP4/M4A put `ftyp` after the first atom's size field (an `.aac` name may hide one).
|
||||
Some(Container::Mp4 | Container::QuickTime | Container::Adts) => Some(&[b"ftyp"]),
|
||||
Some(Container::Aiff | Container::MpegAudio | Container::Ogg) => None,
|
||||
// Unknown files may carry junk before the container; symphonia's probe scans for markers.
|
||||
_ => Some(&[b"caff", b"ftyp", b"fLaC", b"RIFF"]),
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe short name a container marker stands for.
|
||||
fn expected_probe_format(marker: &[u8; 4]) -> &'static str {
|
||||
match marker {
|
||||
b"caff" => "caf",
|
||||
// The isomp4 reader reads the `ftyp` atom.
|
||||
b"ftyp" => "isomp4",
|
||||
b"fLaC" => "flac",
|
||||
// RIFF, RF64 and BW64.
|
||||
_ => "wave",
|
||||
}
|
||||
}
|
||||
|
||||
/// Find the first marker of `markers` at or after `at`, within symphonia's probe depth. A RIFF
|
||||
/// form other than WAVE is skipped, as the probe skips it and reads a WAVE behind it.
|
||||
fn find_container_marker<'a>(bytes: &[u8], at: usize, markers: &'a [&'static [u8; 4]]) -> Option<(usize, &'a [u8; 4])> {
|
||||
let end = bytes.len().min(at.saturating_add(MAX_PREFIX_SCAN));
|
||||
for pos in at..end.saturating_sub(3) {
|
||||
let window = bytes.get(pos..pos + 4)?;
|
||||
if let Some(marker) = markers.iter().find(|marker| window == marker.as_slice()) {
|
||||
if matches!(*marker, b"RIFF" | b"RF64" | b"BW64") && bytes.get(pos + 8..pos + 12) != Some(&b"WAVE"[..]) {
|
||||
continue;
|
||||
}
|
||||
return Some((pos, *marker));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The scan variant for a marker found by [`find_container_marker`], with the probe short name its
|
||||
/// size check stands for. `ftyp` sits four bytes into its atom, so the MP4 check starts there.
|
||||
fn marker_kind(at: usize, marker: &[u8; 4]) -> (FirstMarker, &'static str) {
|
||||
match marker {
|
||||
b"fLaC" => (FirstMarker::Flac(at), expected_probe_format(marker)),
|
||||
b"caff" => (FirstMarker::Caf(at), expected_probe_format(marker)),
|
||||
b"ftyp" => (FirstMarker::Mp4(at.saturating_sub(4)), expected_probe_format(marker)),
|
||||
_ => (FirstMarker::Wav(at), expected_probe_format(marker)),
|
||||
}
|
||||
}
|
||||
|
||||
/// The probe short name a container scan variant stands for.
|
||||
fn marker_name(marker: FirstMarker) -> &'static str {
|
||||
match marker {
|
||||
FirstMarker::Flac(_) => "flac",
|
||||
FirstMarker::Caf(_) => "caf",
|
||||
FirstMarker::Mp4(_) => "isomp4",
|
||||
FirstMarker::Wav(_) => "wave",
|
||||
FirstMarker::Audio => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `rest` starts with one of `R`'s exact registered probe markers.
|
||||
fn has_probe_marker<R: ProbeableFormat<'static>>(rest: &[u8]) -> bool {
|
||||
R::probe_data().iter().any(|data| data.spec.markers.iter().any(|marker| rest.starts_with(marker)))
|
||||
}
|
||||
|
||||
/// Score `R` at `at` exactly as symphonia's private probe does: `Supported` wins, EOF and every
|
||||
/// other scoring error mean "not this format", while a real I/O error aborts the probe.
|
||||
fn scores_supported<R: Scoreable>(stream: &mut MediaSourceStream<'_>, at: usize, depth: u16) -> Result<bool> {
|
||||
stream.seek(SeekFrom::Start(u64::try_from(at).unwrap_or(u64::MAX)))?;
|
||||
match R::score(ScopedStream::new(stream, u64::from(depth))) {
|
||||
Ok(Score::Supported(_)) => Ok(true),
|
||||
Err(SymError::IoError(e)) if e.kind() != std::io::ErrorKind::UnexpectedEof => Err(AudioError::Malformed(e.to_string())),
|
||||
_ => Ok(false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `b[at..]` is an MPEG/ADTS candidate the probe would actually select: an exact
|
||||
/// `probe_data()` marker and a `Supported` score from the same reader. A loose `0xFFEx` pair is
|
||||
/// not enough: `0xFFE0` is neither a registered marker nor a valid frame, so it must not stop the
|
||||
/// scan before a later FLAC/CAF/MP4 candidate.
|
||||
pub(super) fn audio_sync_at<'a>(b: &'a [u8], at: usize, stream: &mut Option<MediaSourceStream<'a>>, budget: &mut ScoreBudget) -> Result<bool> {
|
||||
let rest = b.get(at..).unwrap_or_default();
|
||||
let adts = has_probe_marker::<symphonia::default::formats::AdtsReader<'static>>(rest);
|
||||
let mpa = has_probe_marker::<symphonia::default::formats::MpaReader<'static>>(rest);
|
||||
if !adts && !mpa {
|
||||
return Ok(false);
|
||||
}
|
||||
if stream.is_none() {
|
||||
*stream = Some(MediaSourceStream::new(Box::new(Cursor::new(b)), MediaSourceStreamOptions::default()));
|
||||
}
|
||||
let Some(mss) = stream.as_mut() else { return Ok(false) };
|
||||
let depth = ProbeOptions::default().max_score_depth;
|
||||
if adts && budget.take() && scores_supported::<symphonia::default::formats::AdtsReader<'static>>(mss, at, depth)? {
|
||||
return Ok(true);
|
||||
}
|
||||
if mpa && budget.take() && scores_supported::<symphonia::default::formats::MpaReader<'static>>(mss, at, depth)? {
|
||||
return Ok(true);
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Find the first marker that can start a container or audio stream. Symphonia's `Probe::probe`
|
||||
/// constructs the reader itself and exposes no pre-construction hook, while checking every magic
|
||||
/// in the scan window would validate bytes the probe never reaches (for example a valid MP3's
|
||||
/// audio payload). Stopping at the first marker avoids that: it is the candidate the probe selects
|
||||
/// for FLAC, CAF, MP4, Ogg and Matroska, and for WAV/AIFF once their full form is verified below.
|
||||
/// MPEG/ADTS candidates are checked with the readers' own `probe_data()`/`Scoreable` APIs, so a
|
||||
/// false sync byte pair cannot stop the scan. If that scoring budget runs out, the scan stops at
|
||||
/// the next audio candidate instead of trusting a container-like byte string later in the unscored
|
||||
/// audio payload. A container marker reached before any such candidate is still preflighted; if
|
||||
/// the probe selects a size-checked container the scan did not check, `open` refuses it.
|
||||
///
|
||||
/// WAV candidates include RF64/BW64 so `check_info` can run, although symphonia 0.6 registers only
|
||||
/// the RIFF marker. Native PCM RF64/BW64 is parsed by `wav::parse` before this path; a foreign
|
||||
/// RF64/BW64 stream therefore remains unsupported by the probe rather than misdetected.
|
||||
fn first_marker(b: &[u8], start: usize) -> Result<Option<FirstMarker>> {
|
||||
first_marker_with_budget(b, start, &mut ScoreBudget::new())
|
||||
}
|
||||
|
||||
/// [`first_marker`] with an explicit score budget, so a test can prove a prefix crowded with
|
||||
/// false sync markers performs only the bounded number of reader scores.
|
||||
pub(super) fn first_marker_with_budget(b: &[u8], start: usize, budget: &mut ScoreBudget) -> Result<Option<FirstMarker>> {
|
||||
let end = b.len().min(start.saturating_add(MAX_PREFIX_SCAN));
|
||||
let mut at = start;
|
||||
let mut audio_probe = None;
|
||||
while at.saturating_add(4) <= end {
|
||||
let rest = b.get(at..).unwrap_or_default();
|
||||
if rest.get(..4) == Some(b"fLaC".as_slice()) {
|
||||
return Ok(Some(FirstMarker::Flac(at)));
|
||||
}
|
||||
if rest.get(..4) == Some(b"caff".as_slice()) {
|
||||
return Ok(Some(FirstMarker::Caf(at)));
|
||||
}
|
||||
if rest.get(..4) == Some(b"OggS".as_slice()) || rest.get(..4) == Some(b"\x1A\x45\xDF\xA3".as_slice()) || super::super::aiff::is_aiff(rest) {
|
||||
return Ok(Some(FirstMarker::Audio));
|
||||
}
|
||||
if super::super::wav::is_wav(rest) {
|
||||
return Ok(Some(FirstMarker::Wav(at)));
|
||||
}
|
||||
if let (Some(&b0), Some(&b1)) = (b.get(at), b.get(at + 1))
|
||||
&& b0 == 0xFF
|
||||
&& b1 & 0xE0 == 0xE0
|
||||
{
|
||||
// A candidate after the cap cannot be scored. Stop rather than let a container-like
|
||||
// byte string later in an unscored audio payload become preflight-authoritative; the
|
||||
// probe will select the reader, and `open` refuses an unchecked size-checked one.
|
||||
if budget.exhausted() {
|
||||
return Ok(None);
|
||||
}
|
||||
if audio_sync_at(b, at, &mut audio_probe, budget)? {
|
||||
return Ok(Some(FirstMarker::Audio));
|
||||
}
|
||||
}
|
||||
if rest.get(4..8) == Some(b"ftyp".as_slice()) {
|
||||
return Ok(Some(FirstMarker::Mp4(at)));
|
||||
}
|
||||
at += 1;
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// Run the early size checks on the container the probe can select. `start` is the first byte
|
||||
/// after leading ID3v2 tags. A zero-frame FLAC is returned as an empty stream because Symphonia
|
||||
/// 0.6's reader requires a first audio frame to resynchronize to.
|
||||
pub(super) fn precheck(b: &[u8], start: usize, detected: Option<Container>) -> Result<Precheck> {
|
||||
let any_marker = |b: &[u8], start: usize| -> Result<Option<(FirstMarker, &'static str)>> {
|
||||
Ok(match first_marker(b, start)? {
|
||||
// Stop at the first marker of any kind, so container magic incidental to an audio
|
||||
// payload is not mistaken for the stream's container.
|
||||
Some(FirstMarker::Audio) | None => None,
|
||||
Some(marker) => Some((marker, marker_name(marker))),
|
||||
})
|
||||
};
|
||||
let found = match container_markers(detected) {
|
||||
// Follow the detection: check the first marker of the family it names, so a misleading
|
||||
// marker cannot let a differently sized container reach the probe unchecked. A detection
|
||||
// is only a hint, though: when the stream holds none of its markers (a FLAC behind a
|
||||
// `.mp3` name), the probe can still select another container, which is checked here.
|
||||
Some(markers) => match find_container_marker(b, start, markers) {
|
||||
Some((at, marker)) => Some(marker_kind(at, marker)),
|
||||
None => any_marker(b, start)?,
|
||||
},
|
||||
None => any_marker(b, start)?,
|
||||
};
|
||||
let Some((marker, expected)) = found else { return Ok(Precheck::Unchecked) };
|
||||
match marker {
|
||||
FirstMarker::Flac(at) => {
|
||||
super::super::flac::check_metadata(b, at)?;
|
||||
if let Some(info) = super::super::flac::empty_stream_info(b, at) {
|
||||
return Ok(Precheck::Empty(info));
|
||||
}
|
||||
Ok(Precheck::Flac(expected, super::super::flac::layout(b, at)))
|
||||
}
|
||||
FirstMarker::Caf(at) => {
|
||||
super::super::caf::check(b, at)?;
|
||||
Ok(Precheck::Checked(expected))
|
||||
}
|
||||
FirstMarker::Mp4(at) => {
|
||||
super::super::mp4::check(b, at)?;
|
||||
Ok(Precheck::Checked(expected))
|
||||
}
|
||||
FirstMarker::Wav(at) => {
|
||||
super::super::wav::check_info(b, at)?;
|
||||
Ok(Precheck::Checked(expected))
|
||||
}
|
||||
FirstMarker::Audio => Ok(Precheck::Unchecked),
|
||||
}
|
||||
}
|
||||
@@ -779,23 +779,6 @@ pub(crate) fn opus_layout(head: &opus::OpusHead) -> ChannelLayout {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::PcmFormat;
|
||||
|
||||
#[test]
|
||||
fn pcm_tracks_decode_in_wav_order() {
|
||||
let params = CodecParams::new(CodecId::Pcm).with_sample_rate(48_000).with_channels(2).with_pcm(PcmFormat::int(16, true, false));
|
||||
let mut dec = TrackDecoder::new(¶ms, &[]).unwrap();
|
||||
assert_eq!((dec.codec(), dec.sample_rate(), dec.layout()), (CodecId::Pcm, 48_000, ChannelLayout::STEREO));
|
||||
let block = dec.decode(&[0x00, 0x40, 0x00, 0xC0]).unwrap();
|
||||
assert_eq!(block.channels, vec![vec![0.5], vec![-0.5]]);
|
||||
assert_eq!(dec.conceal(None).unwrap().frames(), 1);
|
||||
// a reset forgets the last packet's length
|
||||
dec.reset();
|
||||
assert_eq!(dec.conceal(None).unwrap().frames(), 0);
|
||||
// silence past the decode limit is an error, not shorter silence
|
||||
dec.last_frames = usize::try_from(crate::pcm::MAX_DECODE_SAMPLES / 2 + 1).unwrap();
|
||||
assert!(matches!(dec.conceal(None), Err(AudioError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[cfg(feature = "opus-decode")]
|
||||
#[test]
|
||||
@@ -889,81 +872,6 @@ mod tests {
|
||||
assert_eq!(dec.conceal(None).unwrap().frames(), 2048);
|
||||
}
|
||||
|
||||
/// A signalled output rate that is not twice the core's is not upsampled to: the core plays.
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
fn an_sbr_rate_other_than_twice_the_core_plays_the_core() {
|
||||
// AOT 5, 24 kHz, mono, extension 44.1 kHz, core AOT 2
|
||||
let asc = {
|
||||
use craft_media::bitstream::BitWriter;
|
||||
let mut bw = BitWriter::new();
|
||||
for (value, bits) in [(5, 5), (6, 4), (1, 4), (4, 4), (2, 5), (0, 3)] {
|
||||
bw.write_bits(value, bits);
|
||||
}
|
||||
bw.finish()
|
||||
};
|
||||
let dec = TrackDecoder::new(&aac_params().with_extradata(asc), &[]).unwrap();
|
||||
assert_eq!((dec.codec(), dec.sample_rate(), dec.frames_per_packet()), (CodecId::Aac, 24_000, Some(1024)));
|
||||
}
|
||||
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
fn adts_frames_of_another_format_or_several_blocks_conceal_at_their_length() {
|
||||
let frame = adts_frame(2);
|
||||
let mut dec = TrackDecoder::new(&aac_params(), &[&frame]).unwrap();
|
||||
// sampling frequency index 4 where the stream has 3
|
||||
let mut other = frame.clone();
|
||||
other[2] = (other[2] & 0xC3) | (4 << 2);
|
||||
assert!(matches!(dec.decode(&other), Err(AudioError::Malformed(_))));
|
||||
assert_eq!(dec.conceal(Some(&other)).unwrap().frames(), 1024);
|
||||
let mut blocks = frame.clone();
|
||||
blocks[6] |= 2; // three raw data blocks
|
||||
assert!(matches!(dec.decode(&blocks), Err(AudioError::Unsupported(_))));
|
||||
assert_eq!(dec.conceal(Some(&blocks)).unwrap().frames(), 3072);
|
||||
// the profile and the channel configuration are part of the format too
|
||||
let mut main = frame.clone();
|
||||
main[2] &= 0x3F; // profile 0: Main
|
||||
assert!(matches!(dec.decode(&main), Err(AudioError::Malformed(_))));
|
||||
let mut mono = frame.clone();
|
||||
mono[3] = (mono[3] & 0x3F) | (1 << 6);
|
||||
assert!(matches!(dec.decode(&mono), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
|
||||
/// With extradata, a header's differing fields are not a format change (ADTS in MP4 with a
|
||||
/// program config element in its AudioSpecificConfig, or channel configuration 0 in its headers).
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
fn extradata_decides_the_format_of_adts_packets() {
|
||||
let frame = adts_frame(0);
|
||||
let mut stereo = adts_frame(2);
|
||||
let params = aac_params().with_extradata(aac::AudioSpecificConfig::lc(3, 2).to_bytes().unwrap());
|
||||
let mut dec = TrackDecoder::new(¶ms, &[]).unwrap();
|
||||
assert_eq!(dec.decode(&stereo).unwrap().channels.len(), 2);
|
||||
stereo[3] &= 0x3F; // channel configuration 0 in the header
|
||||
stereo[2] &= 0xFE;
|
||||
assert_eq!(dec.decode(&stereo).unwrap().channels.len(), 2);
|
||||
assert!(dec.decode(&frame).is_err(), "elements the configuration does not have");
|
||||
}
|
||||
|
||||
/// One damaged header at the start of a stream does not decide its format.
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
fn the_adts_format_is_the_one_most_of_the_lookahead_shares() {
|
||||
let good = adts_frame(2);
|
||||
let mut damaged = good.clone();
|
||||
damaged[2] = (damaged[2] & 0xC3) | (4 << 2); // sampling frequency index 4 where the rest have 3
|
||||
let lookahead: [&[u8]; 4] = [&damaged, &good, &good, &good];
|
||||
let mut dec = TrackDecoder::new(&aac_params(), &lookahead).unwrap();
|
||||
assert_eq!(dec.sample_rate(), 48_000);
|
||||
assert!(dec.decode(&damaged).is_err());
|
||||
assert_eq!(dec.decode(&good).unwrap().frames(), 1024);
|
||||
// on a tie, the earlier one
|
||||
let tied: [&[u8]; 2] = [&good, &damaged];
|
||||
assert_eq!(TrackDecoder::new(&aac_params(), &tied).unwrap().sample_rate(), 48_000);
|
||||
#[cfg(feature = "decode-native")]
|
||||
assert_eq!((adts_frame_count(&good), adts_frame_count(&good.repeat(2)), adts_frame_count(&[0; 8])), (1, 2, 0));
|
||||
}
|
||||
|
||||
/// `au` as a stereo ADTS frame at 48 kHz (channel configuration `channel_config`).
|
||||
#[cfg(feature = "aac-decode")]
|
||||
fn adts_of(au: &[u8], channel_config: u8) -> Vec<u8> {
|
||||
@@ -998,31 +906,6 @@ mod tests {
|
||||
aac::ProgramConfig { front: vec![(true, 0)], ..Default::default() }
|
||||
}
|
||||
|
||||
/// HE-AAC whose SBR data first appears in a later frame of a lookahead packet is found.
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
fn sbr_in_a_later_adts_frame_of_a_packet_is_found() {
|
||||
use craft_media::bitstream::BitWriter;
|
||||
let unit = |sbr: bool| {
|
||||
let mut bw = BitWriter::new();
|
||||
bw.write_bits(0, 7); // ID_SCE, tag 0
|
||||
bw.write_bits(0, 22);
|
||||
if sbr {
|
||||
bw.write_bits(6, 3); // ID_FIL
|
||||
bw.write_bits(1, 4);
|
||||
bw.write_bits(13, 4); // EXT_SBR_DATA
|
||||
bw.write_bits(0, 4);
|
||||
}
|
||||
bw.write_bits(7, 3);
|
||||
bw.finish()
|
||||
};
|
||||
let frame = |au: &[u8]| [&aac::AdtsHeader::write(2, 7, 1, au.len(), 0x7FF).unwrap()[..], au].concat();
|
||||
let packet = [frame(&unit(false)), frame(&unit(true))].concat();
|
||||
let params = aac_params().with_extradata(vec![0x13, 0x88]);
|
||||
let dec = TrackDecoder::new(¶ms, &[&packet]).unwrap();
|
||||
assert_eq!((dec.codec(), dec.sample_rate()), (CodecId::HeAac, 44_100));
|
||||
}
|
||||
|
||||
/// A packet whose later frame fails leaves the decoder as a failed single frame does.
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
@@ -1039,17 +922,6 @@ mod tests {
|
||||
assert_eq!(dec.decode(&plain).unwrap().channels.len(), 3);
|
||||
}
|
||||
|
||||
/// Frames of one packet with different channel counts are an error, not a short packet.
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
fn a_channel_count_change_inside_a_packet_is_an_error() {
|
||||
let first = adts_frame(0);
|
||||
let mut dec = TrackDecoder::new(&aac_params(), &[&first]).unwrap();
|
||||
let change = adts_of(&au_of(Some(&stereo_pce()), &[(1, 0)]), 0);
|
||||
assert!(matches!(dec.decode(&[first.clone(), change.clone()].concat()), Err(AudioError::Malformed(_))));
|
||||
assert_eq!(dec.conceal(Some(&[first, change].concat())).unwrap().frames(), 2048);
|
||||
}
|
||||
|
||||
/// Whole frames before a damaged or truncated end of a packet still decode.
|
||||
#[cfg(feature = "aac-decode")]
|
||||
#[test]
|
||||
@@ -1088,26 +960,6 @@ mod tests {
|
||||
assert!(matches!(TrackDecoder::new(&aac_params(), &[&bare]), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
|
||||
#[cfg(feature = "ac3-decode")]
|
||||
#[test]
|
||||
fn e_ac3_packets_are_as_long_as_all_their_syncframes() {
|
||||
use crate::ac3::tests::single_block_eac3;
|
||||
let params = CodecParams::new(CodecId::Eac3);
|
||||
// One block per packet: 256 frames, known before any packet is decoded.
|
||||
let one = single_block_eac3(true);
|
||||
let dec = TrackDecoder::new(¶ms, &[&one]).unwrap();
|
||||
assert_eq!((dec.codec(), dec.frames_per_packet()), (CodecId::Eac3, Some(256)));
|
||||
// Six one-block syncframes to a packet (as MP4 groups them): 1536.
|
||||
let six = [one.clone(), (0..5).flat_map(|_| single_block_eac3(false)).collect()].concat();
|
||||
let mut dec = TrackDecoder::new(¶ms, &[&six]).unwrap();
|
||||
assert_eq!(dec.frames_per_packet(), Some(1536));
|
||||
assert_eq!(dec.decode(&six).unwrap().channels[0].len(), 1536);
|
||||
// A damaged packet conceals at the length of all its syncframes.
|
||||
dec.reset();
|
||||
assert_eq!(dec.conceal(Some(&six)).unwrap().channels[0].len(), 1536);
|
||||
assert_eq!(dec.conceal(Some(&one)).unwrap().channels[0].len(), 256);
|
||||
}
|
||||
|
||||
#[cfg(feature = "ac3-decode")]
|
||||
#[test]
|
||||
fn a_packet_decoded_in_part_keeps_the_length_lost_packets_are_concealed_at() {
|
||||
@@ -1124,58 +976,6 @@ mod tests {
|
||||
assert_eq!(dec.frames_per_packet(), Some(1536), "a damaged packet does not make the packets' lengths differ");
|
||||
}
|
||||
|
||||
#[cfg(feature = "ac3-decode")]
|
||||
#[test]
|
||||
fn e_ac3_packets_of_different_lengths_or_short_syncframes_are_not_indexed() {
|
||||
use crate::ac3::tests::single_block_eac3;
|
||||
let params = CodecParams::new(CodecId::Eac3);
|
||||
let one = single_block_eac3(true);
|
||||
let two = [single_block_eac3(true), single_block_eac3(false)].concat();
|
||||
// Packets of 256 and 512 frames: a packet's index does not give its position.
|
||||
let dec = TrackDecoder::new(¶ms, &[&one, &one, &two]).unwrap();
|
||||
assert_eq!(dec.frames_per_packet(), None);
|
||||
// Known only once decoded: from then on too.
|
||||
let mut dec = TrackDecoder::new(¶ms, &[&one]).unwrap();
|
||||
assert_eq!(dec.frames_per_packet(), Some(256));
|
||||
dec.decode(&two).unwrap();
|
||||
assert_eq!(dec.frames_per_packet(), None);
|
||||
// One-block syncframes may reuse exponents from any syncframe before them.
|
||||
assert_eq!(TrackDecoder::new(¶ms, &[&one]).unwrap().preroll(), usize::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs_without_a_packet_decoder_are_unsupported() {
|
||||
for codec in [CodecId::Flac, CodecId::Vorbis, CodecId::Mp3, CodecId::H264] {
|
||||
assert!(matches!(TrackDecoder::new(&CodecParams::new(codec), &[]), Err(AudioError::Unsupported(_))), "{codec:?}");
|
||||
}
|
||||
// A codec whose feature is off names the feature.
|
||||
#[cfg(not(feature = "aac-decode"))]
|
||||
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Aac), &[]), Err(AudioError::Unsupported(m)) if m.contains("aac-decode")));
|
||||
#[cfg(not(feature = "alac-decode"))]
|
||||
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Alac), &[]), Err(AudioError::Unsupported(m)) if m.contains("alac-decode")));
|
||||
#[cfg(not(feature = "opus-decode"))]
|
||||
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Opus), &[]), Err(AudioError::Unsupported(m)) if m.contains("opus-decode")));
|
||||
// PCM needs its sample format.
|
||||
assert!(TrackDecoder::new(&CodecParams::new(CodecId::Pcm).with_channels(2).with_sample_rate(48_000), &[]).is_err());
|
||||
}
|
||||
|
||||
#[cfg(feature = "alac-decode")]
|
||||
#[test]
|
||||
fn alac_needs_a_sample_rate() {
|
||||
let cookie = alac::SpecificConfig::new(0, 2, 16, 4096).to_bytes();
|
||||
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Alac).with_extradata(cookie.clone()), &[]), Err(AudioError::Malformed(_))));
|
||||
let dec = TrackDecoder::new(&CodecParams::new(CodecId::Alac).with_extradata(cookie).with_sample_rate(32_000), &[]).unwrap();
|
||||
assert_eq!(dec.sample_rate(), 32_000);
|
||||
}
|
||||
|
||||
#[cfg(feature = "alac-decode")]
|
||||
#[test]
|
||||
fn alac_needs_its_cookie() {
|
||||
assert!(matches!(TrackDecoder::new(&CodecParams::new(CodecId::Alac), &[]), Err(AudioError::Malformed(_))));
|
||||
let bad = CodecParams::new(CodecId::Alac).with_extradata(vec![0; 10]);
|
||||
assert!(matches!(TrackDecoder::new(&bad, &[]), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
|
||||
/// ALAC 5.1 comes out in WAV order at full scale, and a lost packet is as long as the last.
|
||||
#[cfg(all(feature = "alac-decode", feature = "alac-encode"))]
|
||||
#[test]
|
||||
|
||||
@@ -43,15 +43,3 @@ pub fn crc8(data: &[u8]) -> u8 {
|
||||
pub fn crc16(data: &[u8]) -> u16 {
|
||||
data.iter().fold(0u16, |c, &b| (c << 8) ^ T16[usize::from((c >> 8) as u8 ^ b)])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn check_values() {
|
||||
// the standard check value of each polynomial over "123456789"
|
||||
assert_eq!(crc8(b"123456789"), 0xF4);
|
||||
assert_eq!(crc16(b"123456789"), 0xFEE8);
|
||||
}
|
||||
}
|
||||
@@ -270,20 +270,3 @@ impl Encoder {
|
||||
data
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn streaminfo_holds_a_36_bit_total_and_leaves_a_larger_one_unknown() {
|
||||
let enc = Encoder::new(EncoderConfig::new(48_000, 1, 16)).unwrap();
|
||||
let total = |t| {
|
||||
let si = enc.streaminfo_with(0, 0, t, [0; 16]);
|
||||
(u64::from(si[13] & 0x0F) << 32) | u64::from(u32::from_be_bytes([si[14], si[15], si[16], si[17]]))
|
||||
};
|
||||
assert_eq!(total((1 << 36) - 1), (1 << 36) - 1);
|
||||
assert_eq!(total((1 << 35) + 5), (1 << 35) + 5);
|
||||
assert_eq!(total(1 << 36), 0);
|
||||
}
|
||||
}
|
||||
@@ -196,51 +196,3 @@ pub fn write(spec: &FrameSpec) -> Vec<u8> {
|
||||
out.extend_from_slice(&crc.to_be_bytes());
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn coded_numbers() {
|
||||
let code = |v| {
|
||||
let mut o = Vec::new();
|
||||
coded_number(v, &mut o);
|
||||
o
|
||||
};
|
||||
assert_eq!(code(0), [0]);
|
||||
assert_eq!(code(0x7F), [0x7F]);
|
||||
assert_eq!(code(0x80), [0xC2, 0x80]);
|
||||
assert_eq!(code(0x7FF), [0xDF, 0xBF]);
|
||||
assert_eq!(code(0x800), [0xE0, 0xA0, 0x80]);
|
||||
assert_eq!(code(0xFFFF), [0xEF, 0xBF, 0xBF]);
|
||||
assert_eq!(code(0x1_0000), [0xF0, 0x90, 0x80, 0x80]);
|
||||
assert_eq!(code(0x7FFF_FFFF), [0xFD, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF]);
|
||||
assert_eq!(code(0xF_FFFF_FFFF), [0xFE, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF, 0xBF]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_sizes_are_named_in_the_header_except_32_bits() {
|
||||
assert_eq!([8, 12, 16, 20, 24, 32].map(sample_size_code), [1, 2, 4, 5, 6, 0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_rates_in_the_table_have_their_codes() {
|
||||
let table = [88_200, 176_400, 192_000, 8_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000, 96_000];
|
||||
for (rate, code) in table.into_iter().zip(1..) {
|
||||
assert_eq!(sample_rate_code(rate), (code, None), "{rate}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sample_rates_outside_the_table_are_named_in_the_header() {
|
||||
assert_eq!(sample_rate_code(48_000), (10, None));
|
||||
assert_eq!(sample_rate_code(64_000), (12, Some((64, 8))));
|
||||
assert_eq!(sample_rate_code(11_025), (13, Some((11_025, 16))));
|
||||
assert_eq!(sample_rate_code(37_800), (13, Some((37_800, 16))));
|
||||
assert_eq!(sample_rate_code(352_800), (14, Some((35_280, 16))));
|
||||
assert_eq!(sample_rate_code(655_350), (14, Some((65_535, 16))));
|
||||
// neither whole kHz, at most 65535 Hz, nor whole tens of Hz
|
||||
assert_eq!(sample_rate_code(100_001), (0, None));
|
||||
}
|
||||
}
|
||||
@@ -1,249 +0,0 @@
|
||||
//! Golden hashes of the encoder output for a fixed set of synthetic signals.
|
||||
//!
|
||||
//! Encoder speed-ups must not change a single output byte, so this pins the encoded frames and the
|
||||
//! final STREAMINFO (which holds the MD5 of the input) of 64 deterministic cases: noise, sines, silence,
|
||||
//! full-scale squares, wasted bits and a music-like mix, at 8/12/16/24/32 bits, 1 to 4 channels,
|
||||
//! several block sizes (with a short final frame), and levels 0 to 8.
|
||||
//!
|
||||
//! The hashes were captured from FilmCraft's encoder (68919ed8), which this one came from, before the per-order
|
||||
//! predictor kernels and merged partition sums were added. Six cases differ from FilmCraft's table
|
||||
//! on purpose and were captured here, identical before and after those changes: the five `wasted`
|
||||
//! cases (this encoder codes wasted bits) and `click-32b` (32-bit stereo is coded as independent
|
||||
//! channels). Signals use integer arithmetic only. The
|
||||
//! encoder itself uses `f64` (window, autocorrelation), so a platform whose libm rounds `cos`
|
||||
//! differently could in principle differ; the hashes were made on x86-64 Linux.
|
||||
//!
|
||||
//! An intentional change of the output (for example a different LPC order choice) regenerates the
|
||||
//! table with `cargo test -p craft-audio --features flac-encode golden -- --ignored --nocapture print`.
|
||||
|
||||
use super::encoder::{Encoder, EncoderConfig};
|
||||
|
||||
struct Rng(u64);
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// FNV-1a, 64 bit.
|
||||
fn fnv(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().fold(0xcbf2_9ce4_8422_2325, |h, &b| (h ^ u64::from(b)).wrapping_mul(0x0000_0100_0000_01b3))
|
||||
}
|
||||
|
||||
/// A sine-like wave from an integer resonator: `y[n] = 2cos(w) y[n-1] - y[n-2]` in Q14, amplitude `amp`.
|
||||
fn resonator(n: usize, coef_q14: i64, amp: i64) -> Vec<i64> {
|
||||
let (mut y1, mut y2) = (amp, amp * 9 / 10);
|
||||
(0..n)
|
||||
.map(|_| {
|
||||
let y = ((coef_q14 * y1) >> 14) - y2;
|
||||
y2 = y1;
|
||||
y1 = y.clamp(-amp, amp);
|
||||
y1
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// One channel of `kind` at `bps` bits, values always inside the sample range.
|
||||
fn signal(kind: &str, n: usize, bps: u8, seed: u64) -> Vec<i32> {
|
||||
let max = (1i64 << (bps - 1)) - 1;
|
||||
let mut r = Rng(seed | 1);
|
||||
let sine = resonator(n, 32_000 - (seed as i64 % 7) * 900, max / 2);
|
||||
let sine2 = resonator(n, 27_000, max / 4);
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let noise = |r: &mut Rng, amp: i64| (r.next() >> 11) as i64 % (2 * amp + 1) - amp;
|
||||
let v = match kind {
|
||||
"noise" => noise(&mut r, max),
|
||||
"sine" => sine[i],
|
||||
"music" => sine[i] + sine2[i] + noise(&mut r, max / 64),
|
||||
"square" => {
|
||||
if (i / 37) % 2 == 0 {
|
||||
max
|
||||
} else {
|
||||
-max - 1
|
||||
}
|
||||
}
|
||||
// low 3 bits always zero (wasted bits) on a quiet sine
|
||||
"wasted" => (sine[i] / 8) * 8,
|
||||
"click" => {
|
||||
if i == n / 2 {
|
||||
max
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
// a silent stretch between two noisy ones
|
||||
"gap" => {
|
||||
if (n / 3..2 * n / 3).contains(&i) {
|
||||
0
|
||||
} else {
|
||||
noise(&mut r, max / 3)
|
||||
}
|
||||
}
|
||||
_ => 0,
|
||||
};
|
||||
v.clamp(-max - 1, max) as i32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
struct Case {
|
||||
kind: &'static str,
|
||||
bps: u8,
|
||||
channels: u8,
|
||||
block: u16,
|
||||
level: u8,
|
||||
samples: usize,
|
||||
chunk: usize,
|
||||
}
|
||||
|
||||
impl Case {
|
||||
fn name(&self) -> String {
|
||||
format!("{}-{}b-{}ch-bs{}-L{}-n{}-c{}", self.kind, self.bps, self.channels, self.block, self.level, self.samples, self.chunk)
|
||||
}
|
||||
|
||||
/// Hash of every frame and the final STREAMINFO (the file header carries the crate version).
|
||||
fn hash(&self) -> u64 {
|
||||
let planar: Vec<Vec<i32>> =
|
||||
(0..self.channels).map(|c| signal(self.kind, self.samples, self.bps, 0x9E37_79B9 + u64::from(c) * 7919)).collect();
|
||||
let mut cfg = EncoderConfig::new(44_100, self.channels, self.bps);
|
||||
cfg.block_size = self.block;
|
||||
cfg.level = self.level;
|
||||
let mut enc = Encoder::new(cfg).expect("valid config");
|
||||
let mut out = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < self.samples {
|
||||
let end = (at + self.chunk).min(self.samples);
|
||||
let parts: Vec<&[i32]> = planar.iter().map(|c| &c[at..end]).collect();
|
||||
out.extend(enc.encode(&parts).expect("samples in range"));
|
||||
at = end;
|
||||
}
|
||||
out.extend(enc.finish());
|
||||
out.extend_from_slice(&enc.streaminfo());
|
||||
fnv(&out)
|
||||
}
|
||||
}
|
||||
|
||||
fn cases() -> Vec<Case> {
|
||||
const KINDS: [&str; 8] = ["noise", "sine", "music", "square", "wasted", "click", "gap", "silence"];
|
||||
const BPS: [u8; 5] = [8, 12, 16, 24, 32];
|
||||
const BLOCKS: [u16; 5] = [16, 576, 1000, 4096, 4608];
|
||||
let mut v = Vec::new();
|
||||
// every kind at every bit depth; channels, block size and level rotate through their ranges
|
||||
for (k, kind) in KINDS.iter().enumerate() {
|
||||
for (b, &bps) in BPS.iter().enumerate() {
|
||||
let block = BLOCKS[(k + 2 * b) % BLOCKS.len()];
|
||||
let samples = 2 * usize::from(block) + 37 + (k * 101 + b * 13) % 700;
|
||||
v.push(Case {
|
||||
kind,
|
||||
bps,
|
||||
channels: 1 + ((k + b) % 4) as u8,
|
||||
block,
|
||||
level: ((k * 5 + b * 3) % 9) as u8,
|
||||
samples,
|
||||
chunk: 1 + (k * 977 + b * 311) % 5000,
|
||||
});
|
||||
}
|
||||
}
|
||||
// all levels on stereo music at 16 and 24 bits, and the 4096 blocks real files use
|
||||
for level in 0..=8 {
|
||||
for bps in [16u8, 24] {
|
||||
v.push(Case { kind: "music", bps, channels: 2, block: 4096, level, samples: 9000, chunk: 4096 });
|
||||
}
|
||||
}
|
||||
// 4 channels, short blocks and a block that is not a power of two
|
||||
for level in [0u8, 5, 8] {
|
||||
v.push(Case { kind: "noise", bps: 16, channels: 4, block: 1000, level, samples: 2500, chunk: 777 });
|
||||
v.push(Case { kind: "gap", bps: 16, channels: 2, block: 576, level, samples: 2000, chunk: 2000 });
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
/// (case name, hash), captured on FilmCraft 68919ed8.
|
||||
const GOLDEN: &[(&str, u64)] = &[
|
||||
("noise-8b-1ch-bs16-L0-n69-c1", 0x69cba522cd83247a),
|
||||
("noise-12b-2ch-bs1000-L3-n2050-c312", 0xbd8aa93b40b5b078),
|
||||
("noise-16b-3ch-bs4608-L6-n9279-c623", 0xe1969205fcfb7d74),
|
||||
("noise-24b-4ch-bs576-L0-n1228-c934", 0xd444404f16d70169),
|
||||
("noise-32b-1ch-bs4096-L3-n8281-c1245", 0x45ca92f380216922),
|
||||
("sine-8b-2ch-bs576-L5-n1290-c978", 0x135ff72f3b74e284),
|
||||
("sine-12b-3ch-bs4096-L8-n8343-c1289", 0x95c4d0720e59d826),
|
||||
("sine-16b-4ch-bs16-L2-n196-c1600", 0x84bf0b50ef111b77),
|
||||
("sine-24b-1ch-bs1000-L5-n2177-c1911", 0xf4cb2b792c100e1c),
|
||||
("sine-32b-2ch-bs4608-L8-n9406-c2222", 0x45aaf5d6091ecc85),
|
||||
("music-8b-3ch-bs1000-L1-n2239-c1955", 0x3540af737b613e03),
|
||||
("music-12b-4ch-bs4608-L4-n9468-c2266", 0x07d8c76385536b70),
|
||||
("music-16b-1ch-bs576-L7-n1417-c2577", 0x1b5300d81d3a8eac),
|
||||
("music-24b-2ch-bs4096-L1-n8470-c2888", 0x570f7821161e7932),
|
||||
("music-32b-3ch-bs16-L4-n323-c3199", 0xb720fd6b9fb8d7c9),
|
||||
("square-8b-4ch-bs4096-L6-n8532-c2932", 0xf1e702077432c346),
|
||||
("square-12b-1ch-bs16-L0-n385-c3243", 0x2820a440a7465bb2),
|
||||
("square-16b-2ch-bs1000-L3-n2366-c3554", 0x827ee17d45c447bc),
|
||||
("square-24b-3ch-bs4608-L6-n9595-c3865", 0x88b6af280896f131),
|
||||
("square-32b-4ch-bs576-L0-n1544-c4176", 0x8a72918d0834a2f1),
|
||||
("wasted-8b-1ch-bs4608-L2-n9657-c3909", 0xa7516cdcf761110e),
|
||||
("wasted-12b-2ch-bs576-L5-n1606-c4220", 0xf1894eef730d7546),
|
||||
("wasted-16b-3ch-bs4096-L8-n8659-c4531", 0x39d34c6ea3569b7c),
|
||||
("wasted-24b-4ch-bs16-L2-n512-c4842", 0xfa3786f5b0f1004d),
|
||||
("wasted-32b-1ch-bs1000-L5-n2493-c153", 0x00934303beb10016),
|
||||
("click-8b-2ch-bs16-L7-n574-c4886", 0x54b956cd16590b80),
|
||||
("click-12b-3ch-bs1000-L1-n2555-c197", 0x5b5c00ba683e16fb),
|
||||
("click-16b-4ch-bs4608-L4-n9784-c508", 0x906ae4960be0eb16),
|
||||
("click-24b-1ch-bs576-L7-n1733-c819", 0x815a9e001b296ae1),
|
||||
("click-32b-2ch-bs4096-L1-n8786-c1130", 0x9d4424021be06705),
|
||||
("gap-8b-3ch-bs576-L3-n1795-c863", 0xa372ac31d477b4de),
|
||||
("gap-12b-4ch-bs4096-L6-n8848-c1174", 0x0f98e2cbcff69b73),
|
||||
("gap-16b-1ch-bs16-L0-n701-c1485", 0xf0de17bb815bc8eb),
|
||||
("gap-24b-2ch-bs1000-L3-n2682-c1796", 0x09a7b31c70740cc1),
|
||||
("gap-32b-3ch-bs4608-L6-n9911-c2107", 0x8ba6d94ee8c85b0c),
|
||||
("silence-8b-4ch-bs1000-L8-n2044-c1840", 0x845724c286fa7300),
|
||||
("silence-12b-1ch-bs4608-L2-n9273-c2151", 0xe09802e7a78bf137),
|
||||
("silence-16b-2ch-bs576-L5-n1222-c2462", 0x9bfd29a65f5d4a8c),
|
||||
("silence-24b-3ch-bs4096-L8-n8275-c2773", 0xfcf34cb0553f5b39),
|
||||
("silence-32b-4ch-bs16-L2-n128-c3084", 0xc4c8f1f5d73208e0),
|
||||
("music-16b-2ch-bs4096-L0-n9000-c4096", 0x7ee21e0646af3021),
|
||||
("music-24b-2ch-bs4096-L0-n9000-c4096", 0x384bb9626dd0eeb3),
|
||||
("music-16b-2ch-bs4096-L1-n9000-c4096", 0x7ee21e0646af3021),
|
||||
("music-24b-2ch-bs4096-L1-n9000-c4096", 0x384bb9626dd0eeb3),
|
||||
("music-16b-2ch-bs4096-L2-n9000-c4096", 0x7ee21e0646af3021),
|
||||
("music-24b-2ch-bs4096-L2-n9000-c4096", 0x384bb9626dd0eeb3),
|
||||
("music-16b-2ch-bs4096-L3-n9000-c4096", 0xf948f408d6ea5f90),
|
||||
("music-24b-2ch-bs4096-L3-n9000-c4096", 0xc448a8514df4434d),
|
||||
("music-16b-2ch-bs4096-L4-n9000-c4096", 0xd6524def929fdb8e),
|
||||
("music-24b-2ch-bs4096-L4-n9000-c4096", 0xf8f9ddf3036880be),
|
||||
("music-16b-2ch-bs4096-L5-n9000-c4096", 0xd6524def929fdb8e),
|
||||
("music-24b-2ch-bs4096-L5-n9000-c4096", 0xf8f9ddf3036880be),
|
||||
("music-16b-2ch-bs4096-L6-n9000-c4096", 0xd6524def929fdb8e),
|
||||
("music-24b-2ch-bs4096-L6-n9000-c4096", 0xf8f9ddf3036880be),
|
||||
("music-16b-2ch-bs4096-L7-n9000-c4096", 0x5be70a6777d3303e),
|
||||
("music-24b-2ch-bs4096-L7-n9000-c4096", 0x70773b947683c189),
|
||||
("music-16b-2ch-bs4096-L8-n9000-c4096", 0x5be70a6777d3303e),
|
||||
("music-24b-2ch-bs4096-L8-n9000-c4096", 0x70773b947683c189),
|
||||
("noise-16b-4ch-bs1000-L0-n2500-c777", 0x5d0bbda30208b8e9),
|
||||
("gap-16b-2ch-bs576-L0-n2000-c2000", 0x294b47f7663f3861),
|
||||
("noise-16b-4ch-bs1000-L5-n2500-c777", 0x5d0bbda30208b8e9),
|
||||
("gap-16b-2ch-bs576-L5-n2000-c2000", 0xb8a5a6d18a43f0da),
|
||||
("noise-16b-4ch-bs1000-L8-n2500-c777", 0x5d0bbda30208b8e9),
|
||||
("gap-16b-2ch-bs576-L8-n2000-c2000", 0xb8a5a6d18a43f0da),
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn encoder_output_matches_golden_hashes() {
|
||||
let all = cases();
|
||||
assert_eq!(all.len(), GOLDEN.len(), "golden table out of date: regenerate it");
|
||||
for (case, &(name, want)) in all.iter().zip(GOLDEN) {
|
||||
assert_eq!(case.name(), name, "case list changed");
|
||||
assert_eq!(case.hash(), want, "output changed for {name}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "prints the golden table"]
|
||||
fn print() {
|
||||
for c in cases() {
|
||||
println!(" (\"{}\", {:#018x}),", c.name(), c.hash());
|
||||
}
|
||||
}
|
||||
@@ -10,8 +10,6 @@ mod predict;
|
||||
#[cfg(test)]
|
||||
use craft_media_testkit as common;
|
||||
#[cfg(test)]
|
||||
mod golden_tests;
|
||||
#[cfg(test)]
|
||||
mod oracle_tests;
|
||||
|
||||
use super::pcm::{Quantizer, validate_buffer, validate_layout};
|
||||
|
||||
@@ -131,66 +131,6 @@ fn every_signal_round_trips_exactly() {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn channel_layouts_rates_and_sizes() {
|
||||
let cases: [(&str, u8, u8, u32, usize); 12] = [
|
||||
("mono-8bit", 1, 8, 8_000, 3_001),
|
||||
("mono-24-44k1", 1, 24, 44_100, 9_999),
|
||||
("stereo-20bit", 2, 20, 96_000, 10_000),
|
||||
("5.1-24", 6, 24, 48_000, 12_345),
|
||||
("mono-32", 1, 32, 48_000, 7_777),
|
||||
("5.1-32", 6, 32, 96_000, 12_345),
|
||||
("odd-rate", 2, 16, 37_800, 5_000),
|
||||
("rate-khz", 2, 16, 64_000, 5_000),
|
||||
("rate-tens", 2, 24, 352_800, 5_000),
|
||||
("rate-max", 1, 16, 655_350, 5_000),
|
||||
("rate-from-streaminfo", 1, 16, 100_001, 5_000),
|
||||
("tiny", 2, 16, 48_000, 1),
|
||||
];
|
||||
for (name, ch, bps, rate, n) in cases {
|
||||
let planar: Vec<Vec<i32>> = (0..ch).map(|c| signal(if c == 3 { "silence" } else { "music" }, n, bps, u64::from(c) + 7)).collect();
|
||||
if round_trip(name, &planar, EncoderConfig::new(rate, ch, bps), 1000).is_none() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_and_block_sizes_trade_time_for_size() {
|
||||
let planar = vec![signal("music", 48_000, 16, 11), signal("sweep", 48_000, 16, 12)];
|
||||
let mut sizes = Vec::new();
|
||||
for level in 0..=8 {
|
||||
let cfg = EncoderConfig { level, ..EncoderConfig::new(48_000, 2, 16) };
|
||||
let Some(size) = round_trip(&format!("level{level}"), &planar, cfg, 48_000) else { return };
|
||||
sizes.push(size);
|
||||
}
|
||||
// linear prediction beats the fastest level by a wide margin, and all beat PCM
|
||||
assert!(sizes[8] <= sizes[5] && sizes[5] < sizes[0] * 4 / 5, "{sizes:?}");
|
||||
assert!(sizes.iter().all(|&s| s < 48_000 * 4), "{sizes:?}");
|
||||
for bs in [16u16, 192, 1152, 4608, 65_535] {
|
||||
let cfg = EncoderConfig { block_size: bs, ..EncoderConfig::new(48_000, 2, 16) };
|
||||
round_trip(&format!("block{bs}"), &planar, cfg, 777);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_input_is_an_error_not_a_panic() {
|
||||
assert!(Encoder::new(EncoderConfig::new(48_000, 0, 16)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig::new(48_000, 9, 16)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig::new(48_000, 2, 33)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig::new(48_000, 2, 7)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig::new(0, 2, 16)).is_err());
|
||||
assert!(Encoder::new(EncoderConfig { block_size: 8, ..EncoderConfig::new(48_000, 2, 16) }).is_err());
|
||||
let mut enc = Encoder::new(EncoderConfig::new(48_000, 2, 16)).unwrap();
|
||||
assert_eq!(enc.encode(&[&[0, 1]]), Err(Error::Channels { expected: 2, got: 1 }));
|
||||
assert_eq!(enc.encode(&[&[0, 1], &[0]]), Err(Error::UnequalChannels));
|
||||
assert_eq!(enc.encode(&[&[40_000], &[0]]), Err(Error::SampleRange(40_000)));
|
||||
assert_eq!(enc.encode(&[&[-32_769], &[0]]), Err(Error::SampleRange(-32_769)));
|
||||
// nothing encoded: no frames, and a header that still says "unknown"
|
||||
assert!(enc.finish().is_empty());
|
||||
assert_eq!(&enc.header(&[])[..4], b"fLaC");
|
||||
}
|
||||
|
||||
/// 32-bit stereo at the extremes of i32: left minus right would need 33 bits, so the encoder must
|
||||
/// not code a side channel (it overflowed `i32` and wrote garbage); every level decodes exactly.
|
||||
#[test]
|
||||
@@ -209,286 +149,6 @@ fn full_scale_32_bit_stereo_round_trips() {
|
||||
assert!(enc.encode(&[&[i32::MIN, i32::MAX], &[0, -1]]).is_ok());
|
||||
}
|
||||
|
||||
/// A layout decoders would not assume for the channel count is recorded as a channel mask comment,
|
||||
/// which ffmpeg reads: they read 6 channels with side surrounds, and 7 as 6.1 with sides.
|
||||
#[test]
|
||||
fn layouts_decoders_would_not_assume_are_recorded() {
|
||||
use crate::{AudioBuffer, ChannelLayout, EncodeFormat, EncodeOptions};
|
||||
let Some(ffprobe) = common::ffprobe() else { return };
|
||||
let cases = [
|
||||
("layout-stereo", 2, None, "stereo"),
|
||||
("layout-7-default", 7, None, "6.1(back)"),
|
||||
("layout-6.1-side", 7, Some(ChannelLayout::SURROUND_6_1), "6.1"),
|
||||
("layout-5.1-side", 6, Some(ChannelLayout::SURROUND_5_1_SIDE), "5.1(side)"),
|
||||
("layout-5.1-back", 6, Some(ChannelLayout::SURROUND_5_1), "5.1"),
|
||||
("layout-6-default", 6, None, "5.1"),
|
||||
];
|
||||
for (name, channels, layout, expected) in cases {
|
||||
let buf = AudioBuffer::new(48_000, channels, 100);
|
||||
let mut opts = EncodeOptions::new(EncodeFormat::Flac);
|
||||
opts.layout = layout;
|
||||
let file = crate::encode(&buf, &opts).unwrap();
|
||||
let path = common::fixture_subdir("flac").join(format!("{name}.flac"));
|
||||
std::fs::write(&path, &file).unwrap();
|
||||
let out =
|
||||
Command::new(&ffprobe).args(["-v", "error", "-show_entries", "stream=channel_layout", "-of", "csv=p=0"]).arg(&path).output().unwrap();
|
||||
assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), expected, "{name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// FLAC in Ogg reads its layout as a FLAC file does: from the mask comment, or else the one
|
||||
/// decoders assume for the count.
|
||||
#[cfg(feature = "symphonia")]
|
||||
#[test]
|
||||
fn ogg_flac_reads_the_mask_comment() {
|
||||
use crate::ChannelLayout;
|
||||
let Some(ff) = ffmpeg() else { return };
|
||||
let cases: [(&str, &str, &[&str], u16, u32); 5] = [
|
||||
("ogg-mask", "aevalsrc=0|0|0|0:c=4c:d=0.1:s=48000", &["-metadata", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"], 4, 0x107),
|
||||
("ogg-5.1", "aevalsrc=0|0|0|0|0|0:c=5.1:d=0.1:s=48000", &[], 6, 0x60F),
|
||||
("ogg-stereo", "aevalsrc=0|0:c=stereo:d=0.1:s=48000", &["-metadata", "TITLE=x"], 2, 0x3),
|
||||
("ogg-6.1", "aevalsrc=0|0|0|0|0|0|0:c=6.1:d=0.1:s=48000", &[], 7, 0x70F),
|
||||
("ogg-zero-mask", "aevalsrc=0|0|0|0|0|0:c=5.1:d=0.1:s=48000", &["-metadata", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0"], 6, 0),
|
||||
];
|
||||
for (name, source, extra, channels, mask) in cases {
|
||||
let path = common::fixture_subdir("flac").join(format!("{name}.oga"));
|
||||
let status = Command::new(&ff)
|
||||
.args(["-v", "error", "-y", "-f", "lavfi", "-i", source, "-c:a", "flac", "-f", "ogg"])
|
||||
.args(extra)
|
||||
.arg(&path)
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(status.success(), "{name}");
|
||||
let bytes = std::fs::read(&path).unwrap();
|
||||
let expected = ChannelLayout::from_mask_and_channels(mask, channels);
|
||||
assert_eq!(crate::probe(&bytes, None).unwrap().layout, expected, "probe {name}");
|
||||
assert_eq!(crate::decode(&bytes, None).unwrap().0.layout, expected, "decode {name}");
|
||||
}
|
||||
}
|
||||
|
||||
/// `file`, an Ogg file of two streams, with its streams' serial numbers replaced by `serials`, in
|
||||
/// the order the streams start.
|
||||
#[cfg(feature = "symphonia")]
|
||||
fn set_ogg_serials(mut file: Vec<u8>, serials: [u32; 2]) -> Vec<u8> {
|
||||
let mut seen = Vec::new();
|
||||
let mut at = 0;
|
||||
while at < file.len() {
|
||||
assert_eq!(&file[at..at + 4], b"OggS");
|
||||
let segments = usize::from(file[at + 26]);
|
||||
let body: usize = file[at + 27..at + 27 + segments].iter().map(|&n| usize::from(n)).sum();
|
||||
let end = at + 27 + segments + body;
|
||||
let old: [u8; 4] = file[at + 14..at + 18].try_into().unwrap();
|
||||
let stream = seen.iter().position(|s| *s == old).unwrap_or_else(|| {
|
||||
seen.push(old);
|
||||
seen.len() - 1
|
||||
});
|
||||
file[at + 14..at + 18].copy_from_slice(&serials[stream].to_le_bytes());
|
||||
// The page's checksum covers its serial number, and is computed with its own field zero.
|
||||
file[at + 22..at + 26].fill(0);
|
||||
let crc = craft_media::ogg::crc32(&file[at..end]);
|
||||
file[at + 22..at + 26].copy_from_slice(&crc.to_le_bytes());
|
||||
at = end;
|
||||
}
|
||||
assert_eq!(seen.len(), 2);
|
||||
file
|
||||
}
|
||||
|
||||
/// Two streams in an Ogg file written by ffmpeg, with serial numbers in file order or in `reversed`
|
||||
/// order. ffmpeg picks them at random, and symphonia orders tracks by serial, so the reversed order
|
||||
/// is the one that tells the two orders apart. `None` after `skip` when this ffmpeg cannot write the
|
||||
/// file.
|
||||
#[cfg(feature = "symphonia")]
|
||||
fn two_ogg_streams(ff: &Path, name: &str, args: &[&str], reversed: bool) -> Option<Vec<u8>> {
|
||||
let path = common::fixture_subdir("flac").join(format!("{name}.ogg"));
|
||||
let status = Command::new(ff)
|
||||
.args(["-v", "error", "-y", "-f", "lavfi", "-i", "aevalsrc=0|0|0|0:c=4c:d=0.1:s=48000"])
|
||||
.args(["-f", "lavfi", "-i", "aevalsrc=0|0|0|0:c=4c:d=0.1:s=44100"])
|
||||
.args(["-map", "0", "-map", "1"])
|
||||
.args(args)
|
||||
.args(["-f", "ogg"])
|
||||
.arg(&path)
|
||||
.status()
|
||||
.unwrap();
|
||||
if !status.success() {
|
||||
return common::skip(&format!("this ffmpeg cannot write {name}"));
|
||||
}
|
||||
let serials = if reversed { [2, 1] } else { [1, 2] };
|
||||
let bytes = set_ogg_serials(std::fs::read(&path).unwrap(), serials);
|
||||
let file = craft_media::ogg::open(bytes.as_slice()).unwrap();
|
||||
assert_eq!(file.streams.iter().map(|s| s.serial).collect::<Vec<_>>(), serials, "{name}");
|
||||
assert!(file.warnings.is_empty(), "{name}: {:?}", file.warnings);
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
/// A track index means the same stream in `tracks`, `probe` and `decode`: the file's order. Each
|
||||
/// track has its own mask comment, or else the layout decoders assume for the count.
|
||||
#[cfg(feature = "symphonia")]
|
||||
#[test]
|
||||
fn ogg_flac_tracks_are_in_file_order_with_their_own_mask_comments() {
|
||||
use crate::{ChannelLayout, DecodeOptions};
|
||||
let Some(ff) = ffmpeg() else { return };
|
||||
let args = ["-c:a", "flac", "-metadata:s:a:0", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"];
|
||||
for reversed in [false, true] {
|
||||
let Some(bytes) = two_ogg_streams(&ff, "ogg-one-mask", &args, reversed) else { return };
|
||||
let rates: Vec<_> = crate::tracks(&bytes, None).unwrap().iter().map(|t| t.sample_rate).collect();
|
||||
assert_eq!(rates, [Some(48_000), Some(44_100)]);
|
||||
for (track, rate, layout) in [(0, 48_000, ChannelLayout::from_mask(0x107)), (1, 44_100, ChannelLayout::default_for(4))] {
|
||||
let opts = DecodeOptions::default().with_track(track);
|
||||
let info = crate::probe_with(&bytes, None, &opts).unwrap();
|
||||
assert_eq!((info.sample_rate, info.layout), (rate, layout), "probe track {track}");
|
||||
let info = crate::decode_with(&bytes, None, &opts).unwrap().0;
|
||||
assert_eq!((info.sample_rate, info.layout), (rate, layout), "decode track {track}");
|
||||
}
|
||||
assert_eq!(crate::decode(&bytes, None).unwrap().0.sample_rate, 48_000, "the first track");
|
||||
}
|
||||
}
|
||||
|
||||
/// A FLAC stream before a stream symphonia cannot decode is still the first track.
|
||||
#[cfg(feature = "symphonia")]
|
||||
#[test]
|
||||
fn ogg_flac_before_opus_is_the_first_track() {
|
||||
use crate::CodecId;
|
||||
let Some(ff) = ffmpeg() else { return };
|
||||
let args = ["-c:a:0", "flac", "-c:a:1", "libopus", "-ac:a:1", "2"];
|
||||
for reversed in [false, true] {
|
||||
let Some(bytes) = two_ogg_streams(&ff, "ogg-flac-opus", &args, reversed) else { return };
|
||||
assert_eq!(crate::tracks(&bytes, None).unwrap()[0].codec, CodecId::Flac);
|
||||
assert_eq!(crate::decode(&bytes, None).unwrap().0.codec, CodecId::Flac);
|
||||
}
|
||||
}
|
||||
|
||||
/// The first page of a Speex stream, which symphonia has no reader for.
|
||||
#[cfg(feature = "symphonia")]
|
||||
fn speex_ogg_page(serial: u32) -> Vec<u8> {
|
||||
let mut packet = b"Speex ".to_vec();
|
||||
packet.resize(80, 0);
|
||||
let mut page = b"OggS\0\x02".to_vec(); // the start of a stream
|
||||
page.extend_from_slice(&[0; 8]); // granule position
|
||||
page.extend_from_slice(&serial.to_le_bytes());
|
||||
page.extend_from_slice(&[0; 8]); // page number and checksum
|
||||
page.extend_from_slice(&[1, packet.len() as u8]);
|
||||
page.extend_from_slice(&packet);
|
||||
let crc = craft_media::ogg::crc32(&page);
|
||||
page[22..26].copy_from_slice(&crc.to_le_bytes());
|
||||
page
|
||||
}
|
||||
|
||||
/// A stream symphonia has no track for does not stop the default decode from reading the next one,
|
||||
/// and it keeps its index.
|
||||
#[cfg(feature = "symphonia")]
|
||||
#[test]
|
||||
fn ogg_flac_after_a_stream_with_no_reader_is_the_default_track() {
|
||||
use crate::{CodecId, DecodeOptions};
|
||||
let Some(ff) = ffmpeg() else { return };
|
||||
let args = ["-c:a", "flac"];
|
||||
for reversed in [false, true] {
|
||||
let Some(flac) = two_ogg_streams(&ff, "ogg-speex-flac", &args, reversed) else { return };
|
||||
for speex_serial in [0, 9] {
|
||||
let file = [speex_ogg_page(speex_serial), flac.clone()].concat();
|
||||
let codecs: Vec<_> = crate::tracks(&file, None).unwrap().iter().map(|t| t.codec).collect();
|
||||
assert_eq!(codecs, [CodecId::Speex, CodecId::Flac, CodecId::Flac]);
|
||||
let info = crate::decode(&file, None).unwrap().0;
|
||||
assert_eq!((info.codec, info.sample_rate), (CodecId::Flac, 48_000), "reversed {reversed}, speex {speex_serial}");
|
||||
assert!(crate::decode_with(&file, None, &DecodeOptions::default().with_track(0)).is_err());
|
||||
let second = crate::decode_with(&file, None, &DecodeOptions::default().with_track(2)).unwrap().0;
|
||||
assert_eq!(second.sample_rate, 44_100, "reversed {reversed}, speex {speex_serial}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Bytes before the first page do not lose the file's track order or mask comments.
|
||||
#[cfg(feature = "symphonia")]
|
||||
#[test]
|
||||
fn ogg_flac_after_leading_bytes_keeps_its_track_order() {
|
||||
use crate::{ChannelLayout, DecodeOptions};
|
||||
let Some(ff) = ffmpeg() else { return };
|
||||
let args = ["-c:a", "flac", "-metadata:s:a:0", "WAVEFORMATEXTENSIBLE_CHANNEL_MASK=0x0107"];
|
||||
let Some(bytes) = two_ogg_streams(&ff, "ogg-leading-bytes", &args, true) else { return };
|
||||
let file = [vec![0; 64], bytes].concat();
|
||||
let info = crate::decode_with(&file, None, &DecodeOptions::default().with_track(0)).unwrap().0;
|
||||
assert_eq!((info.sample_rate, info.layout), (48_000, ChannelLayout::from_mask(0x107)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_mask_comment_is_written_only_when_decoders_would_assume_otherwise() {
|
||||
use super::mask_comment;
|
||||
let comment = |m: &str| Some(format!("WAVEFORMATEXTENSIBLE_CHANNEL_MASK={m}"));
|
||||
for channels in [1, 2, 3, 4, 8] {
|
||||
assert_eq!(mask_comment(channels, None), None, "{channels}");
|
||||
}
|
||||
assert_eq!(mask_comment(5, None), comment("0x0037"));
|
||||
assert_eq!(mask_comment(5, Some(0x607)), None);
|
||||
assert_eq!(mask_comment(6, None), comment("0x003F"));
|
||||
assert_eq!(mask_comment(6, Some(0x60F)), None);
|
||||
assert_eq!(mask_comment(7, None), comment("0x013F"));
|
||||
assert_eq!(mask_comment(7, Some(0x70F)), None);
|
||||
// no speaker assignment
|
||||
assert_eq!(mask_comment(2, Some(0)), comment("0x0000"));
|
||||
}
|
||||
|
||||
/// Left and right at opposite full scale: the side channel needs its extra bit at every depth.
|
||||
#[test]
|
||||
fn opposite_polarity_stereo_round_trips() {
|
||||
for bps in [16u8, 24] {
|
||||
let left = signal("square", 9_000, bps, 1);
|
||||
let right: Vec<i32> = left.iter().map(|&v| !v).collect();
|
||||
let planar = vec![left, right];
|
||||
if round_trip(&format!("opposite-{bps}"), &planar, EncoderConfig::new(48_000, 2, bps), 4096).is_none() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaminfo_states_the_block_and_frame_sizes() {
|
||||
// silence in the middle: the smallest frame is neither the first nor the last
|
||||
let channel = |seed| [signal("noise", 4096, 16, seed), signal("silence", 4096, 16, seed), signal("noise", 1000, 16, seed)].concat();
|
||||
let planar = [channel(21), channel(22)];
|
||||
let mut enc = Encoder::new(EncoderConfig::new(48_000, 2, 16)).unwrap();
|
||||
let parts: Vec<&[i32]> = planar.iter().map(Vec::as_slice).collect();
|
||||
let mut sizes: Vec<usize> = enc.encode_frames(&parts).unwrap().iter().map(Vec::len).collect();
|
||||
sizes.push(enc.finish().len());
|
||||
let si = enc.streaminfo();
|
||||
let u24 = |b: &[u8]| usize::from(b[0]) << 16 | usize::from(b[1]) << 8 | usize::from(b[2]);
|
||||
assert_eq!(&si[..4], &[0x10, 0x00, 0x10, 0x00]);
|
||||
assert_eq!(u24(&si[4..7]), sizes.iter().copied().min().unwrap());
|
||||
assert_eq!(u24(&si[7..10]), sizes.iter().copied().max().unwrap());
|
||||
}
|
||||
|
||||
/// Frame numbers count up from 0; a decoder that seeks depends on them, though one that reads from
|
||||
/// the start does not.
|
||||
#[test]
|
||||
fn frames_are_numbered_in_order() {
|
||||
let planar = [signal("music", 4096 * 10, 16, 31)];
|
||||
let mut enc = Encoder::new(EncoderConfig::new(48_000, 1, 16)).unwrap();
|
||||
let frames = enc.encode_frames(&[&planar[0]]).unwrap();
|
||||
let numbers: Vec<u8> = frames.iter().map(|f| f[4]).collect();
|
||||
assert_eq!(numbers, (0..10).collect::<Vec<u8>>());
|
||||
}
|
||||
|
||||
/// Two equal channels cost little more than one: the side channel is all zeros.
|
||||
#[test]
|
||||
fn stereo_decorrelation_removes_a_duplicated_channel() {
|
||||
let x = signal("music", 20_000, 16, 41);
|
||||
let mono = encode(std::slice::from_ref(&x), EncoderConfig::new(48_000, 1, 16), 4096).unwrap();
|
||||
let stereo = encode(&[x.clone(), x], EncoderConfig::new(48_000, 2, 16), 4096).unwrap();
|
||||
assert!(stereo.len() < mono.len() * 11 / 10, "stereo {} mono {}", stereo.len(), mono.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_frame_limit_stops_a_write_before_it_reaches_the_sink() {
|
||||
use super::Writer;
|
||||
use crate::{AudioError, BitDepth};
|
||||
let mut w = Writer::new(std::io::Cursor::new(Vec::new()), 1, 48_000, BitDepth::Int16, false, None).unwrap();
|
||||
let header = w.out.get_ref().len();
|
||||
w.frames = (1 << 36) - 2;
|
||||
assert!(matches!(w.write(&[[0.0f32; 4096]], 4096), Err(AudioError::TooLarge(_))));
|
||||
assert_eq!(w.out.get_ref().len(), header);
|
||||
// refused, not failed: what fits can still be written
|
||||
assert!(w.write(&[[0.0f32; 1]], 1).is_ok());
|
||||
assert!(matches!(w.write(&[[0.0f32; 1]], 1), Err(AudioError::TooLarge(_))));
|
||||
}
|
||||
|
||||
/// Samples with unused low bits, on every kind of subframe and stereo mode: the decoder must put
|
||||
/// the bits back before it undoes the stereo decorrelation.
|
||||
#[test]
|
||||
@@ -507,31 +167,3 @@ fn wasted_bits_round_trip() {
|
||||
let lowest: Vec<i32> = (0..9_000).map(|i| if i % 3 == 0 { -(1 << 23) } else { 0 }).collect();
|
||||
round_trip("wasted-to-one-bit", &[lowest], EncoderConfig::new(48_000, 1, 24), 4096);
|
||||
}
|
||||
|
||||
/// A click at full scale needs a residual near the limit; a block is not stored verbatim for it.
|
||||
#[test]
|
||||
fn a_full_scale_click_at_32_bits_is_still_predicted() {
|
||||
let planar = [signal("click", 4_096, 32, 61)];
|
||||
let Some(size) = round_trip("click-32", &planar, EncoderConfig::new(48_000, 1, 32), 4096) else { return };
|
||||
assert!(size < 4_096 * 4 / 2, "{size}");
|
||||
}
|
||||
|
||||
/// Signals that reach the format's limits, which a decoder refuses when they are passed: a Rice
|
||||
/// parameter of 31 is the escape code, and an LPC shift above 15 reads as negative.
|
||||
#[test]
|
||||
fn rice_parameter_and_lpc_shift_stay_in_range() {
|
||||
let mut r = Rng(71);
|
||||
let bursts: Vec<i32> =
|
||||
(0..9_000).map(|i| if i % 1024 < 128 { if i % 2 == 0 { i32::MAX } else { -i32::MAX } } else { (r.next() * 100.0) as i32 }).collect();
|
||||
if round_trip("limit-rice", &[bursts], EncoderConfig::new(48_000, 1, 32), 4096).is_none() {
|
||||
return;
|
||||
}
|
||||
let mut y = 0.0;
|
||||
let correlated: Vec<i32> = (0..9_000)
|
||||
.map(|_| {
|
||||
y = 0.24 * y + r.next() * 8000.0;
|
||||
y as i32
|
||||
})
|
||||
.collect();
|
||||
round_trip("limit-shift", &[correlated], EncoderConfig::new(48_000, 1, 16), 4096);
|
||||
}
|
||||
@@ -356,59 +356,6 @@ pub fn choose(x: &[i32], bps: u8, effort: Effort, win: &[f64]) -> (Subframe, u64
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn folding() {
|
||||
assert_eq!([0, -1, 1, -2, 2].map(fold), [0, 1, 2, 3, 4]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn predictable_signals_beat_verbatim() {
|
||||
// a ramp is exactly predicted by the order-2 fixed predictor
|
||||
let ramp: Vec<i32> = (0..4096).map(|i| i * 3 - 6000).collect();
|
||||
let (sub, bits) = choose(&ramp, 16, Effort::level(5), &window(ramp.len()));
|
||||
assert!(matches!(sub, Subframe::Fixed { order: 2, .. } | Subframe::Lpc { .. }), "{sub:?}");
|
||||
assert!(bits < 4096 * 2, "{bits}");
|
||||
// a sine is well predicted by LPC
|
||||
let sine: Vec<i32> = (0..4096).map(|i| ((i as f64 * 0.05).sin() * 20000.0) as i32).collect();
|
||||
let (_, bits) = choose(&sine, 16, Effort::level(5), &window(sine.len()));
|
||||
assert!(bits < 4096 * 6, "{bits}");
|
||||
assert_eq!(choose(&[7; 100], 16, Effort::level(5), &window(100)), (Subframe::Constant(7), 24));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn residuals_may_reach_the_limit_of_a_32_bit_integer() {
|
||||
assert!(fixed_fold(&[i32::MAX, -i32::MAX], 0).is_some());
|
||||
assert!(fixed_fold(&[0, i32::MAX], 1).is_some());
|
||||
// the most negative value is out of range (§9.2.7.3)
|
||||
assert!(fixed_fold(&[i32::MIN], 0).is_none());
|
||||
assert!(fixed_fold(&[0, 1 << 30, -(1 << 30)], 1).is_none());
|
||||
assert!(lpc_fold(&[0, i32::MAX], &[1], 0).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linear_predictions_stay_in_the_range_of_a_32_bit_integer() {
|
||||
let x = [1 << 30, 1 << 30];
|
||||
assert!(lpc_fold(&x, &[1], 0).is_some());
|
||||
// predicts 2^31, and the residual would be small
|
||||
assert!(lpc_fold(&x, &[2], 0).is_none());
|
||||
assert!(lpc_fold(&x, &[4], 1).is_none());
|
||||
assert!(lpc_fold(&x, &[3], 1).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wasted_bits_are_not_coded() {
|
||||
let x = tones(4096);
|
||||
let padded: Vec<i32> = x.iter().map(|&s| s << 8).collect();
|
||||
let effort = Effort::level(5);
|
||||
let (sub, bits) = choose(&x, 16, effort, &window(x.len()));
|
||||
// the same coding, plus the 8 bits that say how many are wasted
|
||||
assert_eq!(choose(&padded, 24, effort, &window(padded.len())), (Subframe::Wasted { bits: 8, coded: Box::new(sub) }, bits + 8));
|
||||
// at most what leaves one bit per sample, and nothing for silence, a constant keeps its bits
|
||||
let lowest = [0, -(1 << 23)];
|
||||
assert!(matches!(choose(&lowest, 24, effort, &window(lowest.len())).0, Subframe::Wasted { bits: 23, .. }));
|
||||
assert_eq!(choose(&[256; 10], 24, effort, &window([256; 10].len())).0, Subframe::Constant(256));
|
||||
}
|
||||
|
||||
/// Two tones and a little noise, from a fixed seed.
|
||||
fn tones(n: usize) -> Vec<i32> {
|
||||
let mut seed = 1u32;
|
||||
@@ -430,48 +377,4 @@ mod tests {
|
||||
let (_, fixed) = choose(&x, 16, Effort { max_lpc_order: 0, ..effort }, &window(x.len()));
|
||||
assert!(lpc < fixed * 4 / 5, "lpc {lpc} fixed {fixed}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rice_partitions_follow_a_change_in_loudness() {
|
||||
// quiet, then loud: one Rice parameter cannot suit both
|
||||
let x: Vec<i32> = tones(4096).iter().enumerate().map(|(i, &s)| if i < 2048 { s / 256 } else { s }).collect();
|
||||
let effort = Effort::level(5);
|
||||
let (_, partitioned) = choose(&x, 16, effort, &window(x.len()));
|
||||
let (_, whole) = choose(&x, 16, Effort { max_partition_order: 0, ..effort }, &window(x.len()));
|
||||
assert!(partitioned < whole * 19 / 20, "partitioned {partitioned} whole {whole}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lpc_residual_inverts() {
|
||||
let x: Vec<i32> = (0..500).map(|i| ((i as f64 * 0.1).sin() * 1000.0) as i32).collect();
|
||||
let coefs = lpc_orders(&x, 4, &window(x.len())).pop().unwrap();
|
||||
let (q, shift) = quantise(&coefs, 15).unwrap();
|
||||
let r: Vec<i64> =
|
||||
lpc_fold(&x, &q, shift).unwrap().iter().map(|&u| if u & 1 == 0 { i64::from(u >> 1) } else { -i64::from(u >> 1) - 1 }).collect();
|
||||
// rebuild the signal from the warm-up and the residual, as a decoder would
|
||||
let mut y: Vec<i32> = x[..q.len()].to_vec();
|
||||
for (i, &res) in r.iter().enumerate() {
|
||||
let p: i64 = q.iter().zip(y[i..i + q.len()].iter().rev()).map(|(&c, &s)| i64::from(c) * i64::from(s)).sum();
|
||||
y.push((res + (p >> shift)) as i32);
|
||||
}
|
||||
assert_eq!(y, x);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn noise_and_extremes_do_not_panic() {
|
||||
let mut seed = 1u32;
|
||||
let noise: Vec<i32> = (0..4096)
|
||||
.map(|_| {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
(seed >> 8) as i32 - (1 << 23)
|
||||
})
|
||||
.collect();
|
||||
let (_, bits) = choose(&noise, 24, Effort::level(8), &window(noise.len()));
|
||||
assert!(bits <= 8 + 4096 * 24);
|
||||
let square: Vec<i32> = (0..4096).map(|i| if i % 2 == 0 { (1 << 23) - 1 } else { -(1 << 23) }).collect();
|
||||
choose(&square, 24, Effort::level(8), &window(square.len()));
|
||||
choose(&[], 16, Effort::level(5), &window(0));
|
||||
choose(&[1], 16, Effort::level(5), &window(1));
|
||||
choose(&[1, 2], 16, Effort::level(8), &window(2));
|
||||
}
|
||||
}
|
||||
@@ -249,45 +249,3 @@ pub fn wav_float_header(sample_rate: u32, channels: u16, frames: u64) -> Result<
|
||||
}
|
||||
wav::header(usize::from(channels), sample_rate, (32, true), None, None, frames, false)
|
||||
}
|
||||
|
||||
// With only one of `pcm-encode` and `flac-encode`, the other's formats are refused, not silently
|
||||
// written as something else.
|
||||
#[cfg(all(test, not(all(feature = "pcm-encode", feature = "flac-encode"))))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn unbuilt_format_is_unsupported() {
|
||||
let (format, name) = if cfg!(feature = "pcm-encode") { (EncodeFormat::Flac, "flac") } else { (EncodeFormat::Wav, "wav") };
|
||||
let opts = EncodeOptions::new(format);
|
||||
let buf = AudioBuffer::new(48_000, 1, 16);
|
||||
assert!(matches!(encode(&buf, &opts), Err(AudioError::Unsupported(_))));
|
||||
let enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 1);
|
||||
assert!(matches!(enc, Err(AudioError::Unsupported(_))));
|
||||
assert_eq!(encode_format_for(name), None);
|
||||
// Also with a layout it could not use.
|
||||
let opts = opts.with_layout(ChannelLayout::STEREO);
|
||||
assert!(matches!(encode(&buf, &opts), Err(AudioError::Unsupported(_))));
|
||||
let enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 1);
|
||||
assert!(matches!(enc, Err(AudioError::Unsupported(_))));
|
||||
}
|
||||
|
||||
/// Streaming in any block sizes writes the bytes `encode` writes.
|
||||
#[cfg(feature = "flac-encode")]
|
||||
#[test]
|
||||
fn streamed_flac_matches_encode() {
|
||||
let channels: Vec<Vec<f32>> = (0..2).map(|c| (0..20_000).map(|i| ((i * (c + 3)) as f32 * 0.01).sin() * 0.5).collect()).collect();
|
||||
let buf = AudioBuffer { sample_rate: 48_000, channels };
|
||||
let opts = EncodeOptions::new(EncodeFormat::Flac);
|
||||
let whole = encode(&buf, &opts).unwrap();
|
||||
let mut enc = FileEncoder::new(std::io::Cursor::new(Vec::new()), &opts, 48_000, 2).unwrap();
|
||||
let mut at = 0;
|
||||
for n in [1000, 4096, 1, 9000, 5903] {
|
||||
let block: Vec<&[f32]> = buf.channels.iter().map(|c| &c[at..at + n]).collect();
|
||||
enc.write(&block, n).unwrap();
|
||||
at += n;
|
||||
}
|
||||
assert_eq!(at, buf.frames());
|
||||
assert_eq!(enc.finish().unwrap().into_inner(), whole);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
use craft_audio::{EncodeFormat, encode_format_for};
|
||||
|
||||
#[test]
|
||||
fn only_formats_the_encoder_writes_are_named() {
|
||||
assert_eq!(encode_format_for("wav"), Some(EncodeFormat::Wav));
|
||||
assert_eq!(encode_format_for("WAV"), Some(EncodeFormat::Wav));
|
||||
assert_eq!(encode_format_for(".aif"), Some(EncodeFormat::Aiff));
|
||||
assert_eq!(encode_format_for("aiff"), Some(EncodeFormat::Aiff));
|
||||
assert_eq!(encode_format_for("wave"), Some(EncodeFormat::Wav));
|
||||
assert_eq!(encode_format_for("BWF"), Some(EncodeFormat::Wav));
|
||||
assert_eq!(encode_format_for(".aifc"), Some(EncodeFormat::Aiff));
|
||||
assert_eq!(encode_format_for("flac"), Some(EncodeFormat::Flac));
|
||||
assert!(craft_audio::ENCODE_EXTENSIONS.contains(&"flac"));
|
||||
for name in craft_audio::ENCODE_EXTENSIONS {
|
||||
assert!(encode_format_for(name).is_some(), "{name}");
|
||||
}
|
||||
for other in ["mp3", "ogg", "m4a", "xyz", ""] {
|
||||
assert_eq!(encode_format_for(other), None, "{other}");
|
||||
}
|
||||
}
|
||||
@@ -63,39 +63,3 @@ fn assert_float_headroom(streaming: bool) {
|
||||
fn whole_file_float32_preserves_finite_headroom() {
|
||||
assert_float_headroom(false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn streaming_float32_preserves_finite_headroom() {
|
||||
assert_float_headroom(true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float32_keeps_non_finite_sample_handling() {
|
||||
let audio = AudioBuffer { sample_rate: 48_000, channels: vec![vec![f32::NAN, f32::NEG_INFINITY, f32::INFINITY]] };
|
||||
let expected = [0.0_f32, -1.0, 1.0];
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff] {
|
||||
for streaming in [false, true] {
|
||||
let options = EncodeOptions::new(format).with_bit_depth(BitDepth::Float32).with_dither(false);
|
||||
let bytes = encoded(&audio, &options, streaming);
|
||||
// Inspect stored samples too: the decoder itself replaces non-finite values.
|
||||
let pcm: Vec<u8> = expected.iter().flat_map(|v| if format == EncodeFormat::Wav { v.to_le_bytes() } else { v.to_be_bytes() }).collect();
|
||||
assert!(bytes.ends_with(&pcm), "{format:?}, streaming={streaming}");
|
||||
assert_eq!(decode(&bytes, None).unwrap().1.channels[0], expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn integer_pcm_still_clips_at_full_scale() {
|
||||
let audio = AudioBuffer { sample_rate: 48_000, channels: vec![vec![-2.0, -1.25, -1.0, -0.5, 0.0, 0.5, 1.0, 1.25, 2.0]] };
|
||||
for (depth, max) in [(BitDepth::Int16, 32767.0 / 32768.0), (BitDepth::Int24, 8_388_607.0 / 8_388_608.0), (BitDepth::Int32, 1.0)] {
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] {
|
||||
for streaming in [false, true] {
|
||||
let options = EncodeOptions::new(format).with_bit_depth(depth).with_dither(false);
|
||||
let bytes = encoded(&audio, &options, streaming);
|
||||
let (_, decoded) = decode(&bytes, None).unwrap();
|
||||
assert_eq!(decoded.channels[0], [-1.0, -1.0, -1.0, -0.5, 0.0, 0.5, max, max, max], "{format:?} {depth:?}, streaming={streaming}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
//! Integration tests, built as one test binary: each file is a module.
|
||||
|
||||
mod decode_extensions;
|
||||
mod encode_format;
|
||||
mod flac_damage;
|
||||
mod float_headroom;
|
||||
mod malformed;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
//! Hostile inputs must produce `Err` (or a best-effort `Ok`), never a panic.
|
||||
|
||||
use craft_audio::{
|
||||
AudioBuffer, AudioError, BitDepth, CodecId, Container, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe,
|
||||
};
|
||||
use craft_audio::{AudioBuffer, AudioError, BitDepth, EncodeFormat, EncodeOptions, decode, encode, probe};
|
||||
use proptest::prelude::*;
|
||||
|
||||
fn small(format: EncodeFormat, depth: BitDepth, channels: usize) -> Vec<u8> {
|
||||
@@ -15,104 +13,6 @@ fn small(format: EncodeFormat, depth: BitDepth, channels: usize) -> Vec<u8> {
|
||||
encode(&b, &EncodeOptions::new(format).with_bit_depth(depth).with_dither(false)).unwrap()
|
||||
}
|
||||
|
||||
/// An ID3v2.4 header whose syncsafe size field declares `size` bytes of tag body.
|
||||
fn id3_header(size: usize) -> [u8; 10] {
|
||||
let size = size as u32;
|
||||
[b'I', b'D', b'3', 4, 0, 0, ((size >> 21) & 0x7F) as u8, ((size >> 14) & 0x7F) as u8, ((size >> 7) & 0x7F) as u8, (size & 0x7F) as u8]
|
||||
}
|
||||
|
||||
/// Wrap `body` in an ID3v2.4 tag.
|
||||
fn id3_tag(body: &[u8]) -> Vec<u8> {
|
||||
[&id3_header(body.len())[..], body].concat()
|
||||
}
|
||||
|
||||
/// Little helper for building RIFF files by hand.
|
||||
fn riff(chunks: &[(&[u8; 4], Vec<u8>)]) -> Vec<u8> {
|
||||
let mut body = b"WAVE".to_vec();
|
||||
for (id, data) in chunks {
|
||||
body.extend_from_slice(*id);
|
||||
body.extend_from_slice(&(data.len() as u32).to_le_bytes());
|
||||
body.extend_from_slice(data);
|
||||
if data.len() % 2 == 1 {
|
||||
body.push(0);
|
||||
}
|
||||
}
|
||||
let mut out = b"RIFF".to_vec();
|
||||
out.extend_from_slice(&(body.len() as u32).to_le_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
out
|
||||
}
|
||||
|
||||
fn fmt(tag: u16, channels: u16, sr: u32, bits: u16) -> Vec<u8> {
|
||||
let align = channels * bits.div_ceil(8);
|
||||
let mut f = Vec::new();
|
||||
f.extend_from_slice(&tag.to_le_bytes());
|
||||
f.extend_from_slice(&channels.to_le_bytes());
|
||||
f.extend_from_slice(&sr.to_le_bytes());
|
||||
f.extend_from_slice(&(sr * u32::from(align)).to_le_bytes());
|
||||
f.extend_from_slice(&align.to_le_bytes());
|
||||
f.extend_from_slice(&bits.to_le_bytes());
|
||||
f
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncation_is_handled() {
|
||||
let files = [
|
||||
small(EncodeFormat::Wav, BitDepth::Int16, 2),
|
||||
small(EncodeFormat::Wav, BitDepth::Float32, 6),
|
||||
small(EncodeFormat::Aiff, BitDepth::Int24, 1),
|
||||
small(EncodeFormat::Aiff, BitDepth::Float32, 2),
|
||||
small(EncodeFormat::Flac, BitDepth::Int16, 2),
|
||||
small(EncodeFormat::Flac, BitDepth::Int24, 1),
|
||||
];
|
||||
for file in &files {
|
||||
for n in 0..file.len() {
|
||||
let cut = &file[..n];
|
||||
let _ = probe(cut, None);
|
||||
if let Ok((info, buf)) = decode(cut, None) {
|
||||
assert_eq!(buf.num_channels(), info.channels);
|
||||
assert_eq!(buf.frames() as u64, info.frames);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn truncated_data_chunk_yields_partial_audio() {
|
||||
let file = small(EncodeFormat::Wav, BitDepth::Int16, 2);
|
||||
let (info, buf) = decode(&file[..file.len() - 400], None).unwrap();
|
||||
assert_eq!(info.frames, 200);
|
||||
assert_eq!(buf.frames(), 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_single_byte_corruption_is_handled() {
|
||||
for file in
|
||||
[small(EncodeFormat::Wav, BitDepth::Int24, 2), small(EncodeFormat::Aiff, BitDepth::Int16, 2), small(EncodeFormat::Flac, BitDepth::Int16, 1)]
|
||||
{
|
||||
for i in 0..file.len().min(200) {
|
||||
for v in [0x00, 0xFF, 0x7F, 0x80] {
|
||||
let mut f = file.clone();
|
||||
f[i] = v;
|
||||
let _ = probe(&f, None);
|
||||
let _ = decode(&f, None);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_channels_is_malformed() {
|
||||
let wav = riff(&[(b"fmt ", fmt(1, 0, 44_100, 16)), (b"data", vec![0; 16])]);
|
||||
assert!(matches!(decode(&wav, None), Err(AudioError::Malformed(_))));
|
||||
assert!(probe(&wav, None).is_err());
|
||||
let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1);
|
||||
let comm = aiff.windows(4).position(|w| w == b"COMM").unwrap();
|
||||
aiff[comm + 8] = 0;
|
||||
aiff[comm + 9] = 0;
|
||||
assert!(matches!(decode(&aiff, None), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiff_negative_channel_count_is_malformed() {
|
||||
let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1);
|
||||
@@ -121,61 +21,6 @@ fn aiff_negative_channel_count_is_malformed() {
|
||||
aiff[comm + 9] = 0;
|
||||
assert!(probe(&aiff, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_sample_rate_is_malformed() {
|
||||
let wav = riff(&[(b"fmt ", fmt(1, 2, 0, 16)), (b"data", vec![0; 16])]);
|
||||
assert!(decode(&wav, None).is_err());
|
||||
let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1);
|
||||
let comm = aiff.windows(4).position(|w| w == b"COMM").unwrap();
|
||||
for b in &mut aiff[comm + 16..comm + 26] {
|
||||
*b = 0;
|
||||
}
|
||||
assert!(decode(&aiff, None).is_err());
|
||||
// Infinite exponent.
|
||||
aiff[comm + 16] = 0x7F;
|
||||
aiff[comm + 17] = 0xFF;
|
||||
assert!(decode(&aiff, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absurd_chunk_sizes() {
|
||||
// fmt chunk claims 4 GiB.
|
||||
let mut wav = riff(&[(b"fmt ", fmt(1, 2, 44_100, 16)), (b"data", vec![0; 16])]);
|
||||
wav[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(decode(&wav, None).is_err());
|
||||
// data chunk claims 4 GiB: lenient read of what's there.
|
||||
let mut wav = riff(&[(b"fmt ", fmt(1, 2, 44_100, 16)), (b"data", vec![0; 16])]);
|
||||
let d = wav.windows(4).position(|w| w == b"data").unwrap();
|
||||
wav[d + 4..d + 8].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
let (info, buf) = decode(&wav, None).unwrap();
|
||||
assert_eq!((info.frames, buf.frames()), (4, 4));
|
||||
// An unknown chunk with an absurd size before fmt.
|
||||
let mut wav = riff(&[(b"junk", vec![0; 4]), (b"fmt ", fmt(1, 2, 44_100, 16)), (b"data", vec![0; 16])]);
|
||||
wav[16..20].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes());
|
||||
assert!(decode(&wav, None).is_err());
|
||||
// RF64 with a ds64 claiming an exabyte of data.
|
||||
let mut ds64 = Vec::new();
|
||||
ds64.extend_from_slice(&u64::MAX.to_le_bytes());
|
||||
ds64.extend_from_slice(&u64::MAX.to_le_bytes());
|
||||
ds64.extend_from_slice(&u64::MAX.to_le_bytes());
|
||||
ds64.extend_from_slice(&0u32.to_le_bytes());
|
||||
let mut rf = riff(&[(b"ds64", ds64), (b"fmt ", fmt(1, 1, 8_000, 8)), (b"data", vec![0x80; 10])]);
|
||||
rf[..4].copy_from_slice(b"RF64");
|
||||
let d = rf.windows(4).rposition(|w| w == b"data").unwrap();
|
||||
rf[d + 4..d + 8].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
let (info, buf) = decode(&rf, None).unwrap();
|
||||
assert_eq!((info.frames, buf.frames()), (10, 10));
|
||||
// AIFF COMM claims more frames than present; SSND offset beyond the end.
|
||||
let mut aiff = small(EncodeFormat::Aiff, BitDepth::Int16, 1);
|
||||
let comm = aiff.windows(4).position(|w| w == b"COMM").unwrap();
|
||||
aiff[comm + 10..comm + 14].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert_eq!(decode(&aiff, None).unwrap().1.frames(), 300);
|
||||
let ssnd = aiff.windows(4).position(|w| w == b"SSND").unwrap();
|
||||
aiff[ssnd + 8..ssnd + 12].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
assert_eq!(decode(&aiff, None).unwrap().1.frames(), 0);
|
||||
}
|
||||
|
||||
fn caf(chunks: &[(&[u8; 4], i64, Vec<u8>)]) -> Vec<u8> {
|
||||
let mut out = b"caff\0\x01\0\0".to_vec();
|
||||
for (kind, size, body) in chunks {
|
||||
@@ -199,27 +44,6 @@ fn packet_table(packets: i64, frames: i64, entries: &[u8]) -> Vec<u8> {
|
||||
[&packets.to_be_bytes()[..], &frames.to_be_bytes(), &[0; 8], entries].concat()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn caf_sizes_beyond_the_file_are_errors_not_aborts() {
|
||||
let aac = || caf_desc(b"aac ", 0, 1024, 2, 0);
|
||||
let huge = 1i64 << 50;
|
||||
let cookie = caf(&[aac(), (b"kuki", huge, vec![0; 8])]);
|
||||
let files = [
|
||||
cookie.clone(),
|
||||
[vec![0; 100], cookie].concat(),
|
||||
caf(&[aac(), (b"data", -1, [&[0; 4][..], b"kuki", &huge.to_be_bytes()].concat())]),
|
||||
caf(&[aac(), (b"pakt", 24, packet_table(huge, 1024, &[])), (b"data", -1, vec![0; 16])]),
|
||||
caf(&[aac(), (b"pakt", 32, packet_table(1, 1024, &[0x82, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0])), (b"data", -1, vec![0; 64])]),
|
||||
caf(&[aac(), (b"pakt", 25, packet_table(1, 1024, &[0x80]))]),
|
||||
];
|
||||
for f in files {
|
||||
assert!(matches!(probe(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
let constant = caf(&[caf_desc(b"lpcm", 2, 1, 1, 16), (b"pakt", 25, packet_table(1, 1, &[1])), (b"data", -1, vec![0; 16])]);
|
||||
assert!(matches!(decode(&constant, None), Err(AudioError::Malformed(m)) if m.contains("lists packets")));
|
||||
}
|
||||
|
||||
/// An EBML element: `id`, then `size` as an 8-byte vint (so any size up to 2^56 − 2 fits, and
|
||||
/// `u64::MAX` writes the reserved "unknown size"), then `body`.
|
||||
fn ebml(id: &[u8], size: u64, body: &[u8]) -> Vec<u8> {
|
||||
@@ -283,20 +107,6 @@ fn matroska_sizes_beyond_the_file_are_errors_not_aborts() {
|
||||
assert!(decode(&cluster, hint).map_or(0, |(_, b)| b.frames()) < 1_000, "{hint:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn well_formed_caf_still_reads() {
|
||||
let pcm: Vec<u8> = (0..480i16).flat_map(|i| (i * 50).to_be_bytes()).collect();
|
||||
let chan = [((100u32 << 16) | 1).to_be_bytes(), [0; 4], [0; 4]].concat();
|
||||
let data = [vec![0; 4], pcm].concat();
|
||||
let lpcm = caf(&[caf_desc(b"lpcm", 2, 1, 1, 16), (b"chan", 12, chan), (b"free", 8, vec![0; 8]), (b"data", data.len() as i64, data)]);
|
||||
let (info, buf) = decode(&lpcm, None).unwrap();
|
||||
assert_eq!((info.container, buf.frames()), (Container::Caf, 480));
|
||||
let table = packet_table(3, 3072, &[10, 0x81, 0x48, 5]);
|
||||
let aac = caf(&[caf_desc(b"aac ", 0, 1024, 2, 0), (b"pakt", table.len() as i64, table), (b"data", 219, vec![0; 219])]);
|
||||
assert_eq!(probe(&aac, None).unwrap().frames, 3072);
|
||||
}
|
||||
|
||||
fn atom(kind: &[u8; 4], body: &[u8]) -> Vec<u8> {
|
||||
[&(8 + body.len() as u32).to_be_bytes()[..], kind, body].concat()
|
||||
}
|
||||
@@ -328,207 +138,6 @@ fn mp4(frames: u32, entry: &[u8], swap: impl Fn(&[u8; 4], Vec<u8>) -> Vec<u8>) -
|
||||
[ftyp, moov(offset), atom(b"mdat", &pcm)].concat()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mp4_sizes_beyond_the_file_are_errors_not_aborts() {
|
||||
let pcm = sample_entry(b"sowt", 0, &[], &[]);
|
||||
let (_, buf) = decode(&mp4(480, &pcm, |_, a| a), None).unwrap();
|
||||
assert_eq!(buf.frames(), 480);
|
||||
let huge = |kind: &[u8; 4], a: Vec<u8>| [&1u32.to_be_bytes()[..], kind, &(1u64 << 60).to_be_bytes(), &a[8..]].concat();
|
||||
// The first field after version and flags: stts's entry count, stsz's sample size.
|
||||
let first_field_max = |mut a: Vec<u8>| {
|
||||
a[12..16].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||
a
|
||||
};
|
||||
let sizes: Vec<u8> = (0..480u32).flat_map(|i| if i == 479 { u32::MAX } else { 2 }.to_be_bytes()).collect();
|
||||
let per_sample = atom(b"stsz", &[&[0; 8][..], &480u32.to_be_bytes(), &sizes].concat());
|
||||
// A header that starts inside its container is read whole, past the container's end.
|
||||
let mdia = atom(b"mdia", &1u32.to_be_bytes());
|
||||
let straddling = [&b"hdlr"[..], &(1u64 << 60).to_be_bytes(), &[0; 24]].concat();
|
||||
let files = [
|
||||
mp4(480, &pcm, |k, a| if k == b"hdlr" { huge(k, a) } else { a }),
|
||||
mp4(480, &pcm, |k, a| if k == b"stts" { first_field_max(a) } else { a }),
|
||||
mp4(480, &pcm, |k, a| if k == b"stsz" { first_field_max(a) } else { a }),
|
||||
mp4(480, &pcm, |k, a| if k == b"stsz" { per_sample.clone() } else { a }),
|
||||
[atom(b"ftyp", b"M4A \0\0\0\0M4A isom"), atom(b"moov", &atom(b"trak", &mdia)), straddling].concat(),
|
||||
];
|
||||
for f in files {
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn atoms_running_past_their_parent_are_walked_once() {
|
||||
// Each moov holds a trak that runs to the end of the file; symphonia stops after the first.
|
||||
let unit = atom(b"moov", &[&u32::MAX.to_be_bytes()[..], b"trak"].concat());
|
||||
let f = [atom(b"ftyp", b"M4A \0\0\0\0M4A isom"), unit.repeat(1 << 18)].concat();
|
||||
assert!(decode(&f, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_longer_than_any_codec_uses_are_refused() {
|
||||
let be = |v: &[u32]| v.iter().flat_map(|x| x.to_be_bytes()).collect::<Vec<u8>>();
|
||||
let v2 = |frames: u32| [&be(&[72])[..], &48_000f64.to_be_bytes(), &be(&[1, 0x7f00_0000, 16, 4, 2, frames])].concat();
|
||||
let lpcm = |frames: u32| sample_entry(b"lpcm", 2, &v2(frames), &[]);
|
||||
let config = |frames: u32| [&be(&[0, frames])[..], &[0, 16, 40, 10, 14, 1, 0, 255], &be(&[0, 0, 48_000])].concat();
|
||||
let alac = |frames: u32| sample_entry(b"alac", 0, &[], &atom(b"alac", &config(frames)));
|
||||
let (_, buf) = decode(&mp4(480, &lpcm(1), |_, a| a), None).unwrap();
|
||||
assert_eq!(buf.frames(), 480);
|
||||
// PCM is read by craft-media's own demuxer, which reads version-2 sound description fields only
|
||||
// in QuickTime files (ISO BMFF has no such version): the bogus frame count of this MP4 is never
|
||||
// read, and nothing is allocated from it. symphonia read it, so SoundCraft refused the file.
|
||||
let (_, buf) = decode(&mp4(480, &lpcm(1 << 21), |_, a| a), None).unwrap();
|
||||
assert_eq!(buf.frames(), 480);
|
||||
// ALAC: a cookie declaring such packets is refused by the native decoder and then by the
|
||||
// symphonia path's guard.
|
||||
assert!(matches!(decode(&mp4(480, &alac(1 << 21), |_, a| a), None), Err(AudioError::Malformed(m)) if m.contains("declares packets")));
|
||||
}
|
||||
|
||||
/// FLAC metadata blocks with field lengths exceeding their block boundary are refused as malformed.
|
||||
#[test]
|
||||
fn flac_metadata_fields_beyond_their_block_are_refused() {
|
||||
let with_block = |kind: u8, body: &[u8]| {
|
||||
let f = small(EncodeFormat::Flac, BitDepth::Int16, 1);
|
||||
// between STREAMINFO and the encoder's VORBIS_COMMENT, which stays the last block
|
||||
let head = (u32::from(kind) << 24 | body.len() as u32).to_be_bytes();
|
||||
[&f[..42], &head, body, &f[42..]].concat()
|
||||
};
|
||||
let picture = |data: u32| [&[0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0][..], &[0; 16], &data.to_be_bytes(), &[1, 2, 3]].concat();
|
||||
assert_eq!(decode(&with_block(6, &picture(3)), None).unwrap().1.frames(), 300);
|
||||
let comment = [&0u32.to_le_bytes()[..], &1u32.to_le_bytes(), &u32::MAX.to_le_bytes()].concat();
|
||||
let vendor_overflow = [&0x7fff_fff0u32.to_le_bytes()[..], &0u32.to_le_bytes()].concat();
|
||||
for f in [with_block(6, &picture(0x7fff_fff0)), with_block(4, &comment), with_block(4, &vendor_overflow)] {
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than its block")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id3_tag_before_the_audio_is_skipped_unread() {
|
||||
let frame = [&b"TIT2"[..], &0x7fff_ffffu32.to_be_bytes(), &[0, 0, 3, b'h', b'i', 0]].concat();
|
||||
let tag = [&b"ID3\x03\0\0\0\0\0"[..], &[frame.len() as u8], &frame].concat();
|
||||
let flac = small(EncodeFormat::Flac, BitDepth::Int16, 1);
|
||||
assert_eq!(decode(&[tag, flac].concat(), None).unwrap().1.frames(), 300);
|
||||
}
|
||||
|
||||
/// Container magic inside an MP3 frame payload must not change detection or make probing reject the stream.
|
||||
#[test]
|
||||
fn a_valid_mp3_with_incidental_container_magic_still_probes() {
|
||||
let mut frame = vec![0u8; 417];
|
||||
frame[..4].copy_from_slice(&[0xFF, 0xFB, 0x90, 0x00]); // MPEG-1 Layer III, 128 kbps, 44.1 kHz, stereo
|
||||
let mut f: Vec<u8> = (0..8).flat_map(|_| frame.clone()).collect();
|
||||
let at = 417 * 2 + 10; // Inside frame 2's payload, leaving every frame header intact.
|
||||
f[at..at + 8].copy_from_slice(b"caff\0\x01\0\0");
|
||||
f[at + 8..at + 12].copy_from_slice(b"kuki");
|
||||
f[at + 12..at + 20].copy_from_slice(&(1u64 << 50).to_be_bytes());
|
||||
assert_eq!(detect_container(&f, None), Some(Container::MpegAudio));
|
||||
let info = probe(&f, None).expect("valid MP3 with incidental container magic");
|
||||
assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Mp3, 44_100, 2));
|
||||
}
|
||||
|
||||
/// Symphonia 0.6's CAF/FLAC/MP4 `Scoreable` implementations are unconditional
|
||||
/// (`Supported(255)`), so a container magic before the first audio frame *is* the reader the probe
|
||||
/// selects; there is no API to ask the probe to skip it. The preflight must therefore keep
|
||||
/// refusing an oversized CAF cookie instead of ignoring the marker and playing the MPEG frames
|
||||
/// behind it (which would also let a real malformed container bypass the size guard).
|
||||
#[test]
|
||||
fn a_container_marker_before_the_first_audio_frame_is_the_probed_candidate() {
|
||||
let mut frame = vec![0u8; 417];
|
||||
frame[..4].copy_from_slice(&[0xFF, 0xFB, 0x90, 0x00]); // MPEG-1 Layer III, 128 kbps, 44.1 kHz, stereo
|
||||
let mp3: Vec<u8> = (0..8).flat_map(|_| frame.clone()).collect();
|
||||
let malformed = caf(&[caf_desc(b"aac ", 0, 1024, 2, 0), (b"kuki", 1i64 << 50, vec![0; 8])]);
|
||||
for f in [[vec![0u8], malformed.clone(), mp3.clone()].concat(), [vec![0u8; 32], malformed.clone(), mp3.clone()].concat()] {
|
||||
// The hint still names the raw stream, but the probe sees the CAF marker first.
|
||||
assert_eq!(detect_container(&f, Some("mp3")), Some(Container::MpegAudio));
|
||||
assert!(matches!(probe(&f, Some("mp3")), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
assert!(matches!(decode(&f, Some("mp3")), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
// Plain leading junk without format magic is tolerated, as before.
|
||||
let f = [vec![0u8; 32], mp3].concat();
|
||||
assert_eq!(detect_container(&f, Some("mp3")), Some(Container::MpegAudio));
|
||||
let info = probe(&f, Some("mp3")).expect("junk before a valid MP3");
|
||||
assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Mp3, 44_100, 2));
|
||||
}
|
||||
|
||||
/// More false `0xFFEx` pairs than the preflight's scoring budget must not make a later container
|
||||
/// magic inside the valid audio payload authoritative. Past the cap the scan is unchecked and the
|
||||
/// probe selects the MPEG reader at the first real frame.
|
||||
#[test]
|
||||
fn an_exhausted_audio_score_budget_does_not_reject_the_mp3_behind_it() {
|
||||
let mut frame = vec![0u8; 417];
|
||||
frame[..4].copy_from_slice(&[0xFF, 0xFB, 0x90, 0x00]);
|
||||
let mut audio: Vec<u8> = (0..8).flat_map(|_| frame.clone()).collect();
|
||||
let at = 417 * 2 + 10; // Inside frame 2's payload, leaving every frame header intact.
|
||||
audio[at..at + 8].copy_from_slice(b"caff\0\x01\0\0");
|
||||
audio[at + 8..at + 12].copy_from_slice(b"kuki");
|
||||
audio[at + 12..at + 20].copy_from_slice(&(1u64 << 50).to_be_bytes());
|
||||
let false_syncs: Vec<u8> = (0..256).flat_map(|_| [0xFFu8, 0xE2]).collect();
|
||||
let f = [false_syncs, audio].concat();
|
||||
assert_eq!(detect_container(&f, Some("mp3")), Some(Container::MpegAudio));
|
||||
let info = probe(&f, Some("mp3")).expect("valid MP3 after an exhausted audio score budget");
|
||||
assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Mp3, 44_100, 2));
|
||||
let (decoded, buf) = decode(&f, Some("mp3")).expect("decode the same MP3");
|
||||
assert_eq!((decoded.codec, decoded.sample_rate, decoded.channels), (CodecId::Mp3, 44_100, 2));
|
||||
assert_eq!(decoded.frames, buf.frames() as u64);
|
||||
}
|
||||
|
||||
/// Past the score budget the preflight does not run, so if the probe then selects a container
|
||||
/// whose reader allocates from sizes in the file, the post-probe refusal still applies.
|
||||
#[test]
|
||||
fn a_container_selected_without_its_size_check_is_refused() {
|
||||
let flac = small(EncodeFormat::Flac, BitDepth::Int16, 1);
|
||||
// Exactly the cap of false candidates, then one more that the reader rejects (invalid
|
||||
// bit-rate), so the preflight stops unchecked before reaching the FLAC marker behind it.
|
||||
let mut false_syncs: Vec<u8> = (0..256).flat_map(|_| [0xFFu8, 0xE2]).collect();
|
||||
false_syncs.extend_from_slice(&[0xFF, 0xFB, 0xF0, 0x00]);
|
||||
let f = [false_syncs, flac].concat();
|
||||
assert_eq!(detect_container(&f, None), Some(Container::MpegAudio));
|
||||
assert!(matches!(probe(&f, None), Err(AudioError::Malformed(m)) if m.contains("was not size-checked")));
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("was not size-checked")));
|
||||
}
|
||||
|
||||
/// A zero-frame FLAC after arbitrary bytes or ID3 tags is still detected and reported as an empty stream, not a
|
||||
/// decode failure.
|
||||
#[test]
|
||||
fn zero_frame_flac_after_a_prefix_is_still_empty() {
|
||||
let flac =
|
||||
encode(&AudioBuffer::new(48_000, 1, 0), &EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int16).with_dither(false)).unwrap();
|
||||
let tag = id3_tag(b"tag");
|
||||
for (f, detected) in [
|
||||
([vec![0x7A; 64], flac.clone()].concat(), None),
|
||||
([tag.clone(), vec![0x7A; 16], flac.clone()].concat(), Some(Container::MpegAudio)),
|
||||
([tag.clone(), tag, flac.clone()].concat(), Some(Container::MpegAudio)),
|
||||
] {
|
||||
assert_eq!(detect_container(&f, None), detected);
|
||||
let info = probe(&f, None).expect("empty FLAC after a prefix");
|
||||
assert_eq!((info.container, info.sample_rate, info.channels, info.frames), (Container::Flac, 48_000, 1, 0));
|
||||
assert_eq!(decode(&f, None).unwrap().1.frames(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// Build one MPEG-4 AAC-LC ADTS frame at 48 kHz stereo around `payload`, with the 13-bit length covering the 7-byte
|
||||
/// header.
|
||||
fn adts_frame(payload: &[u8]) -> Vec<u8> {
|
||||
// MPEG-4 AAC-LC, 48 kHz, stereo; the 13-bit frame length includes this 7-byte header.
|
||||
let len = 7 + payload.len();
|
||||
let mut h = [0xFF, 0xF1, 0x4C, 0x00, 0x00, 0x1F, 0xFC];
|
||||
h[3] = 0x80 | ((len >> 11) & 0x03) as u8; // stereo channel config low bits
|
||||
h[4] = ((len >> 3) & 0xFF) as u8;
|
||||
h[5] = (((len & 0x07) as u8) << 5) | 0x1F;
|
||||
[&h[..], payload].concat()
|
||||
}
|
||||
|
||||
/// False MPEG sync prefixes must not stop a following zero-frame FLAC from probing as empty.
|
||||
#[test]
|
||||
fn zero_frame_flac_after_a_false_mpeg_sync_is_still_empty() {
|
||||
let flac =
|
||||
encode(&AudioBuffer::new(48_000, 1, 0), &EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int16).with_dither(false)).unwrap();
|
||||
for junk in [vec![0xFF, 0xE0, 0x00], vec![0xFF, 0xF0, 0x00], vec![0xFF, 0xFB, 0xF0, 0x00]] {
|
||||
let f = [junk, flac.clone()].concat();
|
||||
let info = probe(&f, None).expect("empty FLAC after a false sync");
|
||||
assert_eq!((info.container, info.sample_rate, info.channels, info.frames), (Container::Flac, 48_000, 1, 0));
|
||||
assert_eq!(decode(&f, None).unwrap().1.frames(), 0);
|
||||
}
|
||||
}
|
||||
|
||||
/// A false MPEG sync prefix must not let malformed CAF or MP4 size fields bypass the container preflight.
|
||||
#[test]
|
||||
fn a_false_sync_does_not_bypass_container_checks() {
|
||||
@@ -555,218 +164,9 @@ fn a_false_sync_does_not_bypass_container_checks() {
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
|
||||
/// Container magic inside a valid ADTS payload must not override AAC detection or make probing fail.
|
||||
#[test]
|
||||
fn a_valid_adts_stream_with_incidental_container_magic_still_probes() {
|
||||
let payload = [0u8; 400];
|
||||
let mut frames: Vec<Vec<u8>> = (0..8).map(|_| adts_frame(&payload)).collect();
|
||||
let at = 100; // Inside frame 2's payload, leaving every frame header intact.
|
||||
frames[2][7 + at..7 + at + 12].copy_from_slice(b"caff\0\x01\0\0kuki");
|
||||
let f: Vec<u8> = frames.concat();
|
||||
assert_eq!(detect_container(&f, None), Some(Container::Adts));
|
||||
let info = probe(&f, None).expect("valid ADTS with incidental container magic");
|
||||
assert_eq!((info.codec, info.sample_rate, info.channels), (CodecId::Aac, 48_000, 2));
|
||||
}
|
||||
|
||||
/// A later valid CAF must not excuse an earlier malformed container that the preflight or probe rejects.
|
||||
#[test]
|
||||
fn an_earlier_malformed_container_is_not_excused_by_a_later_valid_one() {
|
||||
let malformed = caf(&[caf_desc(b"aac ", 0, 1024, 2, 0), (b"kuki", 1i64 << 50, vec![0; 8])]);
|
||||
let pcm: Vec<u8> = (0..32i16).flat_map(|i| (i * 50).to_be_bytes()).collect();
|
||||
let data = [vec![0; 4], pcm].concat();
|
||||
let valid = caf(&[caf_desc(b"lpcm", 2, 1, 1, 16), (b"data", data.len() as i64, data)]);
|
||||
let f = [vec![0u8; 32], malformed, valid].concat();
|
||||
assert!(matches!(probe(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
|
||||
/// Truncated ID3 bodies, declared tag sizes beyond the file, and a complete tag with no audio after it are malformed
|
||||
/// for both probe and decode.
|
||||
#[test]
|
||||
fn truncated_or_oversized_id3_tags_are_malformed() {
|
||||
let cases = vec![[&id3_header(100)[..], b"xx"].concat(), id3_header(0x0FFF_FFFF).to_vec(), id3_tag(b"tag")];
|
||||
for f in cases {
|
||||
assert!(matches!(probe(&f, None), Err(AudioError::Malformed(_))));
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wav_info_entries_beyond_the_file_are_refused() {
|
||||
let alaw = |len: u32| {
|
||||
let info = [&b"INFO"[..], b"INAM", &len.to_le_bytes(), b"hi"].concat();
|
||||
riff(&[(b"fmt ", [fmt(6, 1, 8_000, 8), vec![0, 0]].concat()), (b"LIST", info), (b"data", vec![0xD5; 800])])
|
||||
};
|
||||
assert_eq!(decode(&alaw(2), None).unwrap().1.frames(), 800);
|
||||
let mut f = alaw(0x7fff_fff0);
|
||||
f[4..8].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
let list = f.windows(4).position(|w| w == b"LIST").unwrap();
|
||||
f[list + 4..list + 8].copy_from_slice(&0x7fff_fffcu32.to_le_bytes());
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_wave_behind_another_riff_form_is_checked() {
|
||||
let info = [&b"INFO"[..], b"INAM", &0x7fff_fff0u32.to_le_bytes(), b"hi"].concat();
|
||||
let mut wav = riff(&[(b"fmt ", [fmt(6, 1, 8_000, 8), vec![0, 0]].concat()), (b"LIST", info), (b"data", vec![0xD5; 800])]);
|
||||
wav[4..8].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
let list = wav.windows(4).position(|w| w == b"LIST").unwrap();
|
||||
wav[list + 4..list + 8].copy_from_slice(&0x7fff_fffcu32.to_le_bytes());
|
||||
// The probe skips the AVI form and reads the WAVE behind it.
|
||||
let f = [&b"RIFF"[..], &4u32.to_le_bytes(), b"AVI ", &wav].concat();
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wav_info_entries_are_found_where_symphonia_reads_them() {
|
||||
let list = [&b"LIST"[..], &0x7fff_fffcu32.to_le_bytes(), b"INFO", b"INAM", &0x7fff_fff0u32.to_le_bytes(), b"hi"].concat();
|
||||
let alaw = |extra: u16| (b"fmt ", [fmt(6, 1, 8_000, 8), extra.to_le_bytes().to_vec()].concat());
|
||||
// A-law's extra bytes are read past its chunk; an odd list is padded twice.
|
||||
let files =
|
||||
[riff(&[alaw(12), (b"JUNK", [&[0; 4][..], &list].concat())]), [riff(&[alaw(0), (b"LIST", b"adtl\0".to_vec())]), vec![0], list].concat()];
|
||||
for mut f in files {
|
||||
f[4..8].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(m)) if m.contains("larger than the file")));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn many_tiny_chunks_terminate() {
|
||||
let mut chunks: Vec<(&[u8; 4], Vec<u8>)> = vec![(b"fmt ", fmt(1, 1, 8_000, 16))];
|
||||
for _ in 0..200_000 {
|
||||
chunks.push((b"pad ", Vec::new()));
|
||||
}
|
||||
let wav = riff(&chunks);
|
||||
assert!(decode(&wav, None).is_err()); // no data chunk within the scan limit
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hand_built_wav_variants() {
|
||||
// 8-bit unsigned.
|
||||
let wav = riff(&[(b"fmt ", fmt(1, 1, 8_000, 8)), (b"data", vec![0x80, 0xFF, 0x00])]);
|
||||
let (info, buf) = decode(&wav, None).unwrap();
|
||||
assert_eq!(info.sample_format, SampleFormat::Int8);
|
||||
assert_eq!(buf.channels[0], vec![0.0, 127.0 / 128.0, -1.0]);
|
||||
// 64-bit float, with NaN replaced by silence.
|
||||
let mut data = Vec::new();
|
||||
for v in [0.25f64, -0.5, f64::NAN] {
|
||||
data.extend_from_slice(&v.to_le_bytes());
|
||||
}
|
||||
let wav = riff(&[(b"fmt ", fmt(3, 1, 8_000, 64)), (b"data", data)]);
|
||||
let (info, buf) = decode(&wav, None).unwrap();
|
||||
assert_eq!(info.sample_format, SampleFormat::Float64);
|
||||
assert_eq!(buf.channels[0], vec![0.25, -0.5, 0.0]);
|
||||
// Unsupported PCM width.
|
||||
let wav = riff(&[(b"fmt ", fmt(3, 1, 8_000, 16)), (b"data", vec![0; 4])]);
|
||||
assert!(matches!(decode(&wav, None), Err(AudioError::Unsupported(_))));
|
||||
// No data chunk / no fmt chunk.
|
||||
assert!(decode(&riff(&[(b"fmt ", fmt(1, 1, 8_000, 16))]), None).is_err());
|
||||
assert!(decode(&riff(&[(b"data", vec![0; 4])]), None).is_err());
|
||||
// Short fmt chunk.
|
||||
assert!(decode(&riff(&[(b"fmt ", vec![1, 0, 1]), (b"data", vec![0; 4])]), None).is_err());
|
||||
// Unknown codec tag goes to symphonia and fails cleanly.
|
||||
let wav = riff(&[(b"fmt ", fmt(0x1234, 1, 8_000, 16)), (b"data", vec![0; 4])]);
|
||||
assert!(decode(&wav, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiff_sowt_little_endian() {
|
||||
let be = small(EncodeFormat::Aiff, BitDepth::Int16, 2);
|
||||
let (_, expect) = decode(&be, None).unwrap();
|
||||
// Rebuild as AIFC/sowt by hand.
|
||||
let comm = be.windows(4).position(|w| w == b"COMM").unwrap();
|
||||
let ssnd = be.windows(4).position(|w| w == b"SSND").unwrap();
|
||||
let mut comm_body = be[comm + 8..comm + 26].to_vec();
|
||||
comm_body.extend_from_slice(b"sowt");
|
||||
comm_body.extend_from_slice(&[0, 0]); // empty pstring, padded
|
||||
let mut ssnd_body = be[ssnd + 8..].to_vec();
|
||||
for pair in ssnd_body[8..].as_chunks_mut::<2>().0 {
|
||||
pair.swap(0, 1);
|
||||
}
|
||||
let mut body = b"AIFC".to_vec();
|
||||
for (id, data) in [(b"COMM", &comm_body), (b"SSND", &ssnd_body)] {
|
||||
body.extend_from_slice(id);
|
||||
body.extend_from_slice(&(data.len() as u32).to_be_bytes());
|
||||
body.extend_from_slice(data);
|
||||
}
|
||||
let mut f = b"FORM".to_vec();
|
||||
f.extend_from_slice(&(body.len() as u32).to_be_bytes());
|
||||
f.extend_from_slice(&body);
|
||||
let (info, got) = decode(&f, None).unwrap();
|
||||
assert_eq!(info.sample_format, SampleFormat::Int16);
|
||||
assert_eq!(got, expect);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detect_container_by_magic_and_hint() {
|
||||
assert_eq!(detect_container(&small(EncodeFormat::Wav, BitDepth::Int16, 1), Some("mp3")), Some(Container::Wav));
|
||||
assert_eq!(detect_container(&small(EncodeFormat::Aiff, BitDepth::Int16, 1), None), Some(Container::Aiff));
|
||||
assert_eq!(detect_container(&small(EncodeFormat::Flac, BitDepth::Int16, 1), None), Some(Container::Flac));
|
||||
assert_eq!(detect_container(b"OggS\0\x02rest", None), Some(Container::Ogg));
|
||||
assert_eq!(detect_container(b"caff\0\x01\0\0", None), Some(Container::Caf));
|
||||
assert_eq!(detect_container(b"ID3\x04\0\0\0\0\0\x00", None), Some(Container::MpegAudio));
|
||||
let mut id3_flac = b"ID3\x04\0\0\0\0\0\x02xx".to_vec();
|
||||
id3_flac.extend_from_slice(b"fLaC");
|
||||
assert_eq!(detect_container(&id3_flac, None), Some(Container::Flac));
|
||||
assert_eq!(detect_container(&[0xFF, 0xFB, 0x90, 0x00], None), Some(Container::MpegAudio));
|
||||
assert_eq!(detect_container(&[0xFF, 0xF1, 0x50, 0x80], None), Some(Container::Adts));
|
||||
assert_eq!(detect_container(&[0x0B, 0x77, 0x00, 0x00], None), Some(Container::Ac3));
|
||||
let mut m4a = b"\0\0\0\x20ftypM4A ".to_vec();
|
||||
m4a.extend_from_slice(b"....stsd\0\0\0\0\0\0\0\x01\0\0\0\x24alac");
|
||||
assert_eq!(detect_container(&m4a, None), Some(Container::Mp4));
|
||||
assert_eq!(detect_container(b"\0\0\0\x20ftypM4A ", None), Some(Container::Mp4));
|
||||
assert_eq!(detect_container(b"\0\0\0\x14ftypqt ", None), Some(Container::QuickTime));
|
||||
assert_eq!(detect_container(b"", Some(".WAV")), Some(Container::Wav));
|
||||
assert_eq!(detect_container(b"zz", Some("aif")), Some(Container::Aiff));
|
||||
assert_eq!(detect_container(b"zz", Some("m4a")), Some(Container::Mp4));
|
||||
assert_eq!(detect_container(b"zz", Some("M4B")), Some(Container::Mp4));
|
||||
assert_eq!(detect_container(b"zz", Some("webm")), Some(Container::WebM));
|
||||
assert_eq!(detect_container(b"zz", Some("flac")), Some(Container::Flac));
|
||||
assert_eq!(detect_container(b"zz", Some("xyz")), None);
|
||||
assert_eq!(detect_container(b"zz", None), None);
|
||||
assert_eq!(detect_container(b"", None), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn garbage_in_compressed_containers_errors() {
|
||||
let garbage: Vec<u8> = (0..4096u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect();
|
||||
for hint in [None, Some("mp3"), Some("ogg"), Some("flac"), Some("m4a"), Some("caf"), Some("aac"), Some("mkv"), Some("wav"), Some("aiff")] {
|
||||
assert!(decode(&garbage, hint).is_err(), "{hint:?}");
|
||||
assert!(probe(&garbage, hint).is_err(), "{hint:?}");
|
||||
}
|
||||
for magic in [&b"fLaC"[..], b"OggS", b"caff", b"ID3\x03\0\0\0\0\0\0", &[0xFF, 0xFB, 0x90, 0x00], b"\0\0\0\x20ftypM4A "] {
|
||||
let mut f = magic.to_vec();
|
||||
f.extend_from_slice(&garbage);
|
||||
let _ = probe(&f, None);
|
||||
assert!(decode(&f, None).map(|(_, b)| b.frames()).unwrap_or(0) < 1_000_000);
|
||||
}
|
||||
assert!(decode(&[], None).is_err());
|
||||
}
|
||||
|
||||
/// A marker that passes its container check must not let the probe select a different container
|
||||
/// without its own checks: the reader is refused when the probed format disagrees.
|
||||
#[test]
|
||||
fn a_probed_container_that_disagrees_with_the_checked_marker_is_refused() {
|
||||
// The junk byte hides both magics, so the hint picks the marker: the FLAC is checked, but the
|
||||
// probe reads the WAVE before it.
|
||||
let bytes = [vec![0], small(EncodeFormat::Wav, BitDepth::Int24, 2), small(EncodeFormat::Flac, BitDepth::Int24, 2)].concat();
|
||||
match decode(&bytes, Some("flac")) {
|
||||
Err(AudioError::Malformed(message)) => assert!(message.contains("probed container"), "unexpected message: {message}"),
|
||||
Err(other) => panic!("unexpected error kind: {other:?}"),
|
||||
Ok(_) => panic!("the mismatched container must be refused"),
|
||||
}
|
||||
}
|
||||
|
||||
proptest! {
|
||||
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||
|
||||
#[test]
|
||||
fn random_bytes_never_panic(bytes in proptest::collection::vec(any::<u8>(), 0..2048), hint in 0usize..6) {
|
||||
let hint = [None, Some("wav"), Some("aiff"), Some("flac"), Some("mp3"), Some("ogg")][hint];
|
||||
let _ = detect_container(&bytes, hint);
|
||||
let _ = probe(&bytes, hint);
|
||||
let _ = decode(&bytes, hint);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_bodies_behind_valid_headers_never_panic(body in proptest::collection::vec(any::<u8>(), 0..1024), which in 0usize..4) {
|
||||
@@ -781,97 +181,6 @@ proptest! {
|
||||
let _ = decode(&f, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn random_audio_roundtrips_through_flac(samples in proptest::collection::vec(-1.2f32..1.2, 1..3000), channels in 1usize..4) {
|
||||
let buf = AudioBuffer::from_interleaved(48_000, channels as u16, &samples);
|
||||
prop_assume!(buf.frames() > 0);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int24).with_dither(false);
|
||||
let (_, flac) = decode(&encode(&buf, &opts).unwrap(), None).unwrap();
|
||||
let (_, wav) = decode(&encode(&buf, &opts.clone().with_format(EncodeFormat::Wav)).unwrap(), None).unwrap();
|
||||
prop_assert_eq!(flac, wav);
|
||||
}
|
||||
}
|
||||
|
||||
/// An extensible `fmt ` chunk: cbSize, valid bits, mask, then the 16-byte subtype GUID.
|
||||
fn extensible_fmt(cb_size: u16, valid_bits: u16, guid: &[u8]) -> Vec<u8> {
|
||||
let mut f = fmt(0xFFFE, 1, 44_100, 16);
|
||||
f.extend_from_slice(&cb_size.to_le_bytes());
|
||||
f.extend_from_slice(&valid_bits.to_le_bytes());
|
||||
f.extend_from_slice(&4u32.to_le_bytes());
|
||||
f.extend_from_slice(guid);
|
||||
f
|
||||
}
|
||||
|
||||
const PCM_GUID: [u8; 16] = [1, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0, 0xAA, 0, 0x38, 0x9B, 0x71];
|
||||
|
||||
#[test]
|
||||
fn extensible_fmt_is_checked_in_full() {
|
||||
let data = vec![0u8; 8];
|
||||
let good = riff(&[(b"fmt ", extensible_fmt(22, 16, &PCM_GUID)), (b"data", data.clone())]);
|
||||
assert_eq!(probe(&good, None).unwrap().sample_format, SampleFormat::Int16);
|
||||
// Subtype GUID cut short after the format code.
|
||||
let cut = riff(&[(b"fmt ", extensible_fmt(22, 16, &PCM_GUID[..4])), (b"data", data.clone())]);
|
||||
assert!(matches!(probe(&cut, None), Err(AudioError::Malformed(_))));
|
||||
assert!(matches!(decode(&cut, None), Err(AudioError::Malformed(_))));
|
||||
// cbSize too small for the extension.
|
||||
let small_cb = riff(&[(b"fmt ", extensible_fmt(0, 16, &PCM_GUID)), (b"data", data.clone())]);
|
||||
assert!(matches!(probe(&small_cb, None), Err(AudioError::Malformed(_))));
|
||||
// More valid bits than the 16-bit container holds.
|
||||
let wide = riff(&[(b"fmt ", extensible_fmt(22, 24, &PCM_GUID)), (b"data", data.clone())]);
|
||||
assert!(matches!(probe(&wide, None), Err(AudioError::Malformed(_))));
|
||||
// PCM-like prefix but a foreign GUID tail is not read as native PCM.
|
||||
let mut foreign = PCM_GUID;
|
||||
foreign[15] ^= 0xFF;
|
||||
let foreign = riff(&[(b"fmt ", extensible_fmt(22, 16, &foreign)), (b"data", data)]);
|
||||
assert!(!matches!(probe(&foreign, None), Ok(i) if i.sample_format == SampleFormat::Int16));
|
||||
// The Ambisonic PCM subtype is PCM.
|
||||
let ambi = [1, 0, 0, 0, 0x21, 0x07, 0xD3, 0x11, 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0, 0, 0];
|
||||
let ambi = riff(&[(b"fmt ", extensible_fmt(22, 16, &ambi)), (b"data", vec![0u8; 8])]);
|
||||
assert_eq!(probe(&ambi, None).unwrap().sample_format, SampleFormat::Int16);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiff_frames_without_sound_data_are_malformed() {
|
||||
// COMM declares 300 frames, and the file ends before any SSND chunk
|
||||
let full = small(EncodeFormat::Aiff, BitDepth::Int16, 1);
|
||||
let ssnd = full.windows(4).position(|w| w == b"SSND").unwrap();
|
||||
let mut f = full[..ssnd].to_vec();
|
||||
let size = (f.len() - 8) as u32;
|
||||
f[4..8].copy_from_slice(&size.to_be_bytes());
|
||||
assert!(matches!(probe(&f, None), Err(AudioError::Malformed(_))));
|
||||
// with no frames declared, no SSND is needed (AIFF 1.3)
|
||||
let comm = f.windows(4).position(|w| w == b"COMM").unwrap();
|
||||
f[comm + 10..comm + 14].fill(0);
|
||||
assert_eq!(probe(&f, None).unwrap().frames, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_flac_has_one_track() {
|
||||
use craft_audio::{DecodeOptions, decode_with};
|
||||
// STREAMINFO: 4096-frame blocks, 44.1 kHz, 2 channels, 16 bits, no samples
|
||||
let mut f = b"fLaC".to_vec();
|
||||
f.extend_from_slice(&[0x80, 0, 0, 34]);
|
||||
f.extend_from_slice(&[0x10, 0x00, 0x10, 0x00, 0, 0, 0, 0, 0, 0]);
|
||||
f.extend_from_slice(&((44_100u64 << 44) | (1 << 41) | (15 << 36)).to_be_bytes());
|
||||
f.extend_from_slice(&[0; 16]);
|
||||
assert_eq!(decode_with(&f, None, &DecodeOptions::default().with_track(0)).unwrap().1.frames(), 0);
|
||||
let e = decode_with(&f, None, &DecodeOptions::default().with_track(1)).unwrap_err();
|
||||
assert!(matches!(e, AudioError::Unsupported(_)), "{e}");
|
||||
}
|
||||
|
||||
/// A damaged MP4 or Matroska file is malformed when symphonia cannot read it either, as it is
|
||||
/// without symphonia.
|
||||
#[test]
|
||||
fn damaged_mp4_and_matroska_are_malformed() {
|
||||
// an `ftyp` box and nothing after it: no `moov`
|
||||
let mp4 = [&16u32.to_be_bytes()[..], b"ftypisom", &[0, 0, 2, 0]].concat();
|
||||
// an EBML header naming Matroska and nothing after it: no Segment
|
||||
let mkv = [&[0x1A, 0x45, 0xDF, 0xA3, 0x8B, 0x42, 0x82, 0x88][..], b"matroska"].concat();
|
||||
for f in [mp4, mkv] {
|
||||
assert!(matches!(decode(&f, None), Err(AudioError::Malformed(_))), "{:?}", decode(&f, None));
|
||||
assert!(matches!(probe(&f, None), Err(AudioError::Malformed(_))));
|
||||
assert!(matches!(craft_audio::tracks(&f, None), Err(AudioError::Malformed(_))));
|
||||
}
|
||||
}
|
||||
|
||||
/// MP3 in MP4 is decoded by symphonia (PCM, AAC, ALAC, Opus and AC-3 are native), so it reaches
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
use craft_audio::{
|
||||
AudioBuffer, BitDepth, BwfInfo, ChannelLayout, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe,
|
||||
wav_float_header,
|
||||
};
|
||||
use craft_audio::{AudioBuffer, BitDepth, EncodeFormat, EncodeOptions, SampleFormat, decode, detect_container, encode, probe};
|
||||
|
||||
fn sine(sr: u32, channels: usize, frames: usize) -> AudioBuffer {
|
||||
let mut b = AudioBuffer::new(sr, channels as u16, frames);
|
||||
@@ -20,7 +17,6 @@ fn tolerance(depth: BitDepth, dither: bool) -> f32 {
|
||||
BitDepth::Int24 => 1.0 / 8_388_608.0,
|
||||
BitDepth::Int32 => 1e-7,
|
||||
BitDepth::Float32 => 0.0,
|
||||
_ => unreachable!("a bit depth this test does not know"),
|
||||
};
|
||||
lsb * if dither { 1.6 } else { 0.6 } + 1e-7
|
||||
}
|
||||
@@ -39,7 +35,6 @@ fn expected_sf(d: BitDepth) -> SampleFormat {
|
||||
BitDepth::Int24 => SampleFormat::Int24,
|
||||
BitDepth::Int32 => SampleFormat::Int32,
|
||||
BitDepth::Float32 => SampleFormat::Float32,
|
||||
_ => unreachable!("a bit depth this test does not know"),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,346 +64,3 @@ fn wav_and_aiff_roundtrip_all_depths_and_layouts() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flac_roundtrip_is_lossless_vs_wav() {
|
||||
for depth in [BitDepth::Int16, BitDepth::Int24, BitDepth::Int32] {
|
||||
for channels in [1, 2, 3, 4, 5, 6, 7, 8] {
|
||||
// Spans several blocks plus a short final block.
|
||||
let src = sine(44_100, channels, 4096 * 2 + 17);
|
||||
let wav = encode(&src, &EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(depth).with_dither(false)).unwrap();
|
||||
let flac = encode(&src, &EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(depth).with_dither(false)).unwrap();
|
||||
assert_eq!(detect_container(&flac, None), Some(craft_audio::Container::Flac));
|
||||
let info = probe(&flac, None).unwrap();
|
||||
assert_eq!((info.container, info.codec), (craft_audio::Container::Flac, craft_audio::CodecId::Flac));
|
||||
assert_eq!((info.sample_rate, info.channels as usize, info.frames), (44_100, channels, src.frames() as u64));
|
||||
assert_eq!(info.sample_format, expected_sf(depth));
|
||||
let (_, from_wav) = decode(&wav, None).unwrap();
|
||||
let (finfo, from_flac) = decode(&flac, None).unwrap();
|
||||
assert_eq!(finfo.frames, src.frames() as u64);
|
||||
assert_eq!(from_flac, from_wav, "{depth:?} {channels}ch");
|
||||
if depth != BitDepth::Int32 {
|
||||
assert!(flac.len() < wav.len(), "{depth:?} {channels}ch: flac {} >= wav {}", flac.len(), wav.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flac_handles_silence_noise_full_scale_and_odd_rates() {
|
||||
let frames = 10_000;
|
||||
let mut b = AudioBuffer::new(37_123, 3, frames);
|
||||
let mut seed = 1u32;
|
||||
for i in 0..frames {
|
||||
seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
|
||||
b.channels[1][i] = (seed as f32 / u32::MAX as f32) * 2.0 - 1.0; // white noise
|
||||
b.channels[2][i] = if i % 2 == 0 { 1.5 } else { -1.5 }; // clipped full-scale square
|
||||
}
|
||||
for depth in [BitDepth::Int16, BitDepth::Int24, BitDepth::Int32] {
|
||||
for dither in [false, true] {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(depth).with_dither(dither);
|
||||
let flac = encode(&b, &opts).unwrap();
|
||||
let (info, out) = decode(&flac, None).unwrap();
|
||||
assert_eq!(info.sample_rate, 37_123);
|
||||
let wav = encode(&b, &opts.clone().with_format(EncodeFormat::Wav)).unwrap();
|
||||
let (_, expect) = decode(&wav, None).unwrap();
|
||||
assert_eq!(out, expect, "{depth:?} dither={dither}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 16-bit audio exported at a larger depth costs no more: the padding is not coded.
|
||||
#[test]
|
||||
fn flac_does_not_store_padding() {
|
||||
let mut src = sine(48_000, 2, 20_000);
|
||||
for s in src.channels.iter_mut().flatten() {
|
||||
*s = (*s * 32768.0).round() / 32768.0;
|
||||
}
|
||||
let size = |depth| {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(depth).with_dither(false);
|
||||
let flac = encode(&src, &opts).unwrap();
|
||||
let (_, wav) = decode(&encode(&src, &opts.clone().with_format(EncodeFormat::Wav)).unwrap(), None).unwrap();
|
||||
assert_eq!(decode(&flac, None).unwrap().1, wav, "{depth:?}");
|
||||
flac.len()
|
||||
};
|
||||
let base = size(BitDepth::Int16);
|
||||
assert!(size(BitDepth::Int24) < base * 11 / 10);
|
||||
assert!(size(BitDepth::Int32) < base * 11 / 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flac_rejects_unsupported_layouts() {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Float32).with_dither(false);
|
||||
assert!(encode(&sine(48_000, 2, 10), &opts).is_err());
|
||||
let opts = opts.clone().with_bit_depth(BitDepth::Int16);
|
||||
assert!(encode(&sine(48_000, 9, 10), &opts).is_err());
|
||||
assert!(encode(&sine(655_351, 1, 10), &opts).is_err());
|
||||
assert!(encode(&sine(655_350, 1, 10), &opts).is_ok());
|
||||
// Tiny buffers still encode and decode.
|
||||
let one = sine(48_000, 2, 1);
|
||||
let (_, out) = decode(&encode(&one, &opts).unwrap(), None).unwrap();
|
||||
assert_eq!(out.frames(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bwf_roundtrip() {
|
||||
let bwf = BwfInfo::default()
|
||||
.with_description("Scene 12 take 3")
|
||||
.with_originator("SoundCraft")
|
||||
.with_originator_reference("SC-0001")
|
||||
.with_origination("2026-10-06", "12:34:56")
|
||||
.with_time_reference(0x1_2345_6789); // > 32 bits
|
||||
let src = sine(96_000, 2, 1000);
|
||||
// RF64 is a WAV layout: other formats ignore it.
|
||||
let aiff = encode(&src, &EncodeOptions::new(EncodeFormat::Aiff).with_force_rf64(true)).unwrap();
|
||||
assert_eq!(&aiff[..4], b"FORM");
|
||||
let flac = encode(&src, &EncodeOptions::new(EncodeFormat::Flac).with_force_rf64(true)).unwrap();
|
||||
assert_eq!(&flac[..4], b"fLaC");
|
||||
for depth in DEPTHS {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(depth).with_dither(false).with_bwf(bwf.clone());
|
||||
let bytes = encode(&src, &opts).unwrap();
|
||||
let info = probe(&bytes, None).unwrap();
|
||||
assert_eq!(info.bwf.as_ref(), Some(&bwf));
|
||||
let (dinfo, _) = decode(&bytes, None).unwrap();
|
||||
assert_eq!(dinfo.bwf, Some(bwf.clone()));
|
||||
// RF64 layout reads back identically.
|
||||
let rf64 = encode(&src, &opts.clone().with_force_rf64(true)).unwrap();
|
||||
assert_eq!(&rf64[..4], b"RF64");
|
||||
let (rinfo, rbuf) = decode(&rf64, None).unwrap();
|
||||
assert_eq!(rinfo.bwf, Some(bwf.clone()));
|
||||
assert_eq!(rinfo.frames, 1000);
|
||||
assert_eq!(rbuf, decode(&bytes, None).unwrap().1);
|
||||
}
|
||||
// Overlong strings are truncated to the field width, not an error.
|
||||
let long = BwfInfo::default().with_description("x".repeat(400));
|
||||
let bytes = encode(&src, &EncodeOptions::default().with_bwf(long)).unwrap();
|
||||
assert_eq!(probe(&bytes, None).unwrap().bwf.unwrap().description.len(), 256);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wav_header_layout() {
|
||||
let b = encode(&sine(44_100, 2, 10), &EncodeOptions::default().with_bit_depth(BitDepth::Int16)).unwrap();
|
||||
// Plain PCM for 16-bit stereo; extensible otherwise.
|
||||
let fmt = b.windows(4).position(|w| w == b"fmt ").unwrap();
|
||||
assert_eq!(u16::from_le_bytes([b[fmt + 8], b[fmt + 9]]), 1);
|
||||
let b = encode(&sine(44_100, 2, 10), &EncodeOptions::default()).unwrap();
|
||||
let fmt = b.windows(4).position(|w| w == b"fmt ").unwrap();
|
||||
assert_eq!(u16::from_le_bytes([b[fmt + 8], b[fmt + 9]]), 0xFFFE);
|
||||
let riff = u32::from_le_bytes([b[4], b[5], b[6], b[7]]) as usize;
|
||||
assert_eq!(riff + 8, b.len());
|
||||
// Odd data length (24-bit mono, odd frames) gets a pad byte.
|
||||
let b = encode(&sine(44_100, 1, 3), &EncodeOptions::default()).unwrap();
|
||||
assert_eq!(b.len() % 2, 0);
|
||||
assert_eq!(decode(&b, None).unwrap().1.frames(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aiff_float_is_aifc() {
|
||||
let b = encode(&sine(44_100, 2, 10), &EncodeOptions::new(EncodeFormat::Aiff).with_bit_depth(BitDepth::Float32)).unwrap();
|
||||
assert_eq!(&b[8..12], b"AIFC");
|
||||
assert!(b.windows(4).any(|w| w == b"fl32"));
|
||||
let b = encode(&sine(44_100, 2, 10), &EncodeOptions::new(EncodeFormat::Aiff)).unwrap();
|
||||
assert_eq!(&b[8..12], b"AIFF");
|
||||
let form = u32::from_be_bytes([b[4], b[5], b[6], b[7]]) as usize;
|
||||
assert_eq!(form + 8, b.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unusual_sample_rates_roundtrip() {
|
||||
for sr in [1, 8_000, 11_025, 22_050, 44_100, 88_200, 176_400, 192_000, 352_800, 384_000, 768_000] {
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff] {
|
||||
let bytes = encode(&sine(sr, 1, 8), &EncodeOptions::new(format)).unwrap();
|
||||
assert_eq!(probe(&bytes, None).unwrap().sample_rate, sr, "{format:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn encode_rejects_bad_buffers_and_formats() {
|
||||
assert!(encode(&AudioBuffer::default(), &EncodeOptions::default()).is_err());
|
||||
assert!(encode(&AudioBuffer::new(0, 2, 10), &EncodeOptions::default()).is_err());
|
||||
// Formats `encode` cannot write are not `EncodeFormat` variants, so asking for one does not compile.
|
||||
// Non-finite samples are sanitized; only integer output clips finite samples.
|
||||
let mut b = AudioBuffer::new(48_000, 1, 4);
|
||||
b.channels[0] = vec![f32::NAN, f32::INFINITY, -5.0, 0.5];
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] {
|
||||
for depth in DEPTHS {
|
||||
if format == EncodeFormat::Flac && depth == BitDepth::Float32 {
|
||||
continue;
|
||||
}
|
||||
let bytes = encode(&b, &EncodeOptions::new(format).with_bit_depth(depth)).unwrap();
|
||||
let (_, out) = decode(&bytes, None).unwrap();
|
||||
assert_eq!(out.channels[0][0], 0.0);
|
||||
assert!(out.channels[0][1] > 0.99 && out.channels[0][1] <= 1.0);
|
||||
assert_eq!(out.channels[0][2], if depth == BitDepth::Float32 { -5.0 } else { -1.0 });
|
||||
}
|
||||
}
|
||||
// Ragged buffers encode the common length.
|
||||
let ragged = AudioBuffer { sample_rate: 48_000, channels: vec![vec![0.1; 10], vec![0.2; 7]] };
|
||||
let (_, out) = decode(&encode(&ragged, &EncodeOptions::default()).unwrap(), None).unwrap();
|
||||
assert_eq!(out.frames(), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_buffer_helpers() {
|
||||
let b = AudioBuffer::from_interleaved(48_000, 2, &[0.1, -0.2, 0.3, -0.4, 0.5]);
|
||||
assert_eq!(b.frames(), 2);
|
||||
assert_eq!(b.num_channels(), 2);
|
||||
assert_eq!(b.interleaved(), vec![0.1, -0.2, 0.3, -0.4]);
|
||||
assert!((b.peak() - 0.4).abs() < 1e-7);
|
||||
assert!((b.duration_secs() - 2.0 / 48_000.0).abs() < 1e-12);
|
||||
assert_eq!(AudioBuffer::from_interleaved(1, 0, &[1.0]).num_channels(), 0);
|
||||
assert_eq!(AudioBuffer::new(0, 1, 5).duration_secs(), 0.0);
|
||||
assert_eq!(AudioBuffer::default().frames(), 0);
|
||||
}
|
||||
|
||||
#[cfg(feature = "serde")]
|
||||
#[test]
|
||||
fn serde_types_roundtrip() {
|
||||
let opts = EncodeOptions::default().with_bwf(BwfInfo::default().with_time_reference(42));
|
||||
let s = serde_json::to_string(&opts).unwrap();
|
||||
assert_eq!(serde_json::from_str::<EncodeOptions>(&s).unwrap(), opts);
|
||||
let info = probe(&encode(&sine(48_000, 1, 4), &opts).unwrap(), None).unwrap();
|
||||
let s = serde_json::to_string(&info).unwrap();
|
||||
assert_eq!(serde_json::from_str::<craft_audio::AudioInfo>(&s).unwrap(), info);
|
||||
// A layout reads back only when its mask describes its channel count.
|
||||
let l = ChannelLayout::SURROUND_5_1;
|
||||
assert_eq!(serde_json::from_str::<ChannelLayout>(&serde_json::to_string(&l).unwrap()).unwrap(), l);
|
||||
assert_eq!(serde_json::from_str::<ChannelLayout>(r#"{"channels":4,"mask":0}"#).unwrap(), ChannelLayout::unordered(4));
|
||||
assert!(serde_json::from_str::<ChannelLayout>(r#"{"channels":2,"mask":63}"#).is_err());
|
||||
assert!(serde_json::from_str::<ChannelLayout>(r#"{"channels":1,"mask":2147483648}"#).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multichannel_wav_speaker_masks() {
|
||||
let buf = |n: usize| AudioBuffer { sample_rate: 48_000, channels: (0..n).map(|c| vec![0.01 * c as f32; 64]).collect() };
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int24).with_dither(false);
|
||||
for (n, mask) in [(6usize, 0x3Fu32), (8, 0x63F), (12, 0x2_D63F)] {
|
||||
let bytes = craft_audio::encode(&buf(n), &opts).unwrap();
|
||||
assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::from_mask(mask), "{n} channels");
|
||||
assert_eq!(craft_audio::decode(&bytes, Some("wav")).unwrap().1.channels.len(), n);
|
||||
}
|
||||
// Explicit masks: 7.0 (sides + rears, no LFE) and Ambisonics (no positions).
|
||||
let bytes = craft_audio::encode(&buf(7), &opts.clone().with_layout(ChannelLayout::from_mask(0x637))).unwrap();
|
||||
assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::from_mask(0x637));
|
||||
let bytes = craft_audio::encode(&buf(4), &opts.clone().with_layout(ChannelLayout::unordered(4))).unwrap();
|
||||
assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::unordered(4));
|
||||
// Plain 16-bit stereo stays a plain PCM header (format tag 1), read back as stereo.
|
||||
let o16 = opts.clone().with_bit_depth(BitDepth::Int16);
|
||||
let bytes = craft_audio::encode(&buf(2), &o16.clone().with_layout(ChannelLayout::STEREO)).unwrap();
|
||||
let fmt = bytes.windows(4).position(|w| w == b"fmt ").unwrap();
|
||||
assert_eq!(bytes.get(fmt + 8..fmt + 10), Some(&[1u8, 0][..]));
|
||||
assert_eq!(probe(&bytes, None).unwrap().layout, ChannelLayout::STEREO);
|
||||
// FLAC (decoded by symphonia) reports its channel assignment: six channels are 5.1.
|
||||
let flac = o16.clone().with_format(EncodeFormat::Flac);
|
||||
let info = probe(&craft_audio::encode(&buf(6), &flac).unwrap(), None).unwrap();
|
||||
assert_eq!((info.container, info.codec, info.layout), (craft_audio::Container::Flac, craft_audio::CodecId::Flac, ChannelLayout::SURROUND_5_1));
|
||||
// A layout for another channel count is refused.
|
||||
assert!(craft_audio::encode(&buf(2), &o16.clone().with_layout(ChannelLayout::SURROUND_5_1)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_wav_header_is_rewritten_in_place_as_the_file_grows() {
|
||||
let take = sine(48_000, 2, 1_000);
|
||||
let mut file = wav_float_header(48_000, 2, 0).unwrap();
|
||||
let len = file.len();
|
||||
file.extend(take.interleaved().iter().flat_map(|s| s.to_le_bytes()));
|
||||
assert_eq!(decode(&file, None).unwrap().1.frames(), 1_000);
|
||||
file[..len].copy_from_slice(&wav_float_header(48_000, 2, 600).unwrap());
|
||||
assert_eq!(decode(&file, None).unwrap().1.frames(), 600);
|
||||
file[..len].copy_from_slice(&wav_float_header(48_000, 2, 1_000).unwrap());
|
||||
assert_eq!(file, encode(&take, &EncodeOptions::default().with_bit_depth(BitDepth::Float32)).unwrap());
|
||||
let big = wav_float_header(48_000, 2, 600_000_000).unwrap();
|
||||
assert_eq!((&big[..4], big.len()), (&b"RF64"[..], len));
|
||||
assert!(wav_float_header(48_000, 0, 0).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_frame_flac_round_trips_like_wav_and_aiff() {
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] {
|
||||
for depth in [BitDepth::Int16, BitDepth::Int24] {
|
||||
for channels in [1, 2] {
|
||||
let opts = EncodeOptions::new(format).with_bit_depth(depth);
|
||||
let bytes = encode(&AudioBuffer::new(48_000, channels, 0), &opts).unwrap();
|
||||
let info = probe(&bytes, None).unwrap();
|
||||
assert_eq!((info.container, info.sample_format, info.sample_rate, info.frames), (format.container(), expected_sf(depth), 48_000, 0));
|
||||
assert_eq!(info.channels, channels);
|
||||
let (info, buf) = decode(&bytes, None).unwrap();
|
||||
assert_eq!((info.frames, buf.frames(), buf.num_channels()), (0, 0, channels));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flac_claiming_frames_but_holding_none_still_errors() {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Flac).with_bit_depth(BitDepth::Int16);
|
||||
let mut bytes = encode(&AudioBuffer::new(48_000, 2, 0), &opts).unwrap();
|
||||
bytes[25] = 1; // STREAMINFO total samples (low byte of the 36-bit field) = 1
|
||||
assert!(decode(&bytes, None).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn float_wav_header_rejects_a_frame_count_whose_total_size_overflows() {
|
||||
// 4 bytes per frame: the data length fits in u64, but adding the header to it does not.
|
||||
let frames = u64::MAX / 4;
|
||||
assert!(matches!(wav_float_header(48_000, 1, frames), Err(craft_audio::AudioError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dither_changes_integer_output() {
|
||||
// a quiet signal whose samples fall between the integer levels
|
||||
let mut src = AudioBuffer::new(48_000, 1, 4800);
|
||||
for (i, s) in src.channels[0].iter_mut().enumerate() {
|
||||
*s = 0.001 * (i as f32 * 0.01).sin();
|
||||
}
|
||||
for depth in [BitDepth::Int16, BitDepth::Int24, BitDepth::Int32] {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(depth);
|
||||
let plain = encode(&src, &opts.clone().with_dither(false)).unwrap();
|
||||
let dithered = encode(&src, &opts.with_dither(true)).unwrap();
|
||||
assert_ne!(plain, dithered, "{depth:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bwf_text_is_cut_at_a_character_boundary() {
|
||||
// 255 ASCII bytes then a 2-byte character: the 256-byte description field cannot hold it
|
||||
let description = format!("{}é", "a".repeat(255));
|
||||
let bwf = BwfInfo::default().with_description(&description);
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bwf(bwf);
|
||||
let info = probe(&encode(&sine(48_000, 1, 100), &opts).unwrap(), None).unwrap();
|
||||
assert_eq!(info.bwf.unwrap().description, "a".repeat(255));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_byte_rate_past_32_bits_is_an_error() {
|
||||
// 4 GHz × 8 bytes per frame does not fit the 32-bit nAvgBytesPerSec field
|
||||
assert!(matches!(wav_float_header(4_000_000_000, 2, 0), Err(craft_audio::AudioError::Encode(_))));
|
||||
assert!(wav_float_header(4_000_000_000 / 8, 2, 0).is_ok());
|
||||
}
|
||||
|
||||
/// The channel mask comment of a FLAC file is its layout, for `probe`, `decode` and `Decoder`, and
|
||||
/// for a file with no audio frames.
|
||||
#[test]
|
||||
fn flac_layouts_read_back_from_the_mask_comment() {
|
||||
use craft_audio::{DecodeOptions, Decoder};
|
||||
let cases = [
|
||||
(6, Some(ChannelLayout::SURROUND_5_1_SIDE), ChannelLayout::SURROUND_5_1_SIDE),
|
||||
(6, None, ChannelLayout::SURROUND_5_1),
|
||||
(7, Some(ChannelLayout::SURROUND_6_1), ChannelLayout::SURROUND_6_1),
|
||||
(7, None, ChannelLayout::default_for(7)),
|
||||
(4, Some(ChannelLayout::from_mask(0x107)), ChannelLayout::from_mask(0x107)),
|
||||
(2, Some(ChannelLayout::unordered(2)), ChannelLayout::unordered(2)),
|
||||
];
|
||||
for (channels, layout, expected) in cases {
|
||||
for frames in [4096, 0] {
|
||||
let mut opts = EncodeOptions::new(EncodeFormat::Flac);
|
||||
opts.layout = layout;
|
||||
let file = craft_audio::encode(&AudioBuffer::new(48_000, channels, frames), &opts).unwrap();
|
||||
assert_eq!(probe(&file, None).unwrap().layout, expected, "probe {channels} {layout:?} {frames}");
|
||||
assert_eq!(decode(&file, None).unwrap().0.layout, expected, "decode {channels} {layout:?} {frames}");
|
||||
let dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap();
|
||||
assert_eq!(dec.info().layout, expected, "Decoder {channels} {layout:?} {frames}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use craft_audio::{AudioBuffer, AudioError, BitDepth, BwfInfo, ChannelLayout, EncodeFormat, EncodeOptions, FileEncoder, encode};
|
||||
use std::io::{Cursor, Seek, SeekFrom, Write};
|
||||
use craft_audio::{AudioBuffer, BitDepth, BwfInfo, ChannelLayout, EncodeFormat, EncodeOptions, FileEncoder, encode};
|
||||
use std::io::Cursor;
|
||||
|
||||
fn tone(channels: usize, frames: usize) -> AudioBuffer {
|
||||
let channels = (0..channels).map(|c| (0..frames).map(|i| ((i * (c + 3)) as f32 * 0.013).sin() * 1.2).collect()).collect();
|
||||
@@ -58,219 +58,3 @@ fn streamed_files_match_whole_buffer_encodes() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A `Write + Seek` sink that accepts `budget` bytes in total and then fails every write, so
|
||||
/// a `write_all` on it appends a prefix of the block and only then reports the error.
|
||||
struct FailAfter {
|
||||
inner: Cursor<Vec<u8>>,
|
||||
budget: usize,
|
||||
}
|
||||
|
||||
impl Write for FailAfter {
|
||||
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
|
||||
if self.budget == 0 {
|
||||
return Err(std::io::Error::other("sink is full"));
|
||||
}
|
||||
let n = buf.len().min(self.budget);
|
||||
self.budget -= n;
|
||||
self.inner.write(&buf[..n])
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
self.inner.flush()
|
||||
}
|
||||
}
|
||||
|
||||
impl Seek for FailAfter {
|
||||
fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
|
||||
self.inner.seek(pos)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_write_poisons_the_encoder() {
|
||||
let buf = tone(2, 20_001);
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] {
|
||||
let opts = EncodeOptions::new(format).with_bit_depth(BitDepth::Int16).with_dither(false);
|
||||
let sink = FailAfter { inner: Cursor::new(Vec::new()), budget: 256 };
|
||||
let mut enc = FileEncoder::new(sink, &opts, buf.sample_rate, 2).unwrap();
|
||||
// The sink accepts a prefix of the first block, then fails.
|
||||
assert!(enc.write(&buf.channels, buf.frames()).is_err(), "{format:?}");
|
||||
// Later calls must not claim success: the bytes on the sink no longer match the
|
||||
// encoder's counters (and for FLAC the failed frame's samples are already gone).
|
||||
assert!(matches!(enc.write(&buf.channels, 16), Err(AudioError::Encode(_))), "{format:?}");
|
||||
assert!(matches!(enc.finish(), Err(AudioError::Encode(_))), "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blocks_past_a_format_limit_are_refused_before_anything_is_written() {
|
||||
let buf = tone(2, 100);
|
||||
for (format, limit) in [(EncodeFormat::Aiff, 1u64 << 30), (EncodeFormat::Flac, 1u64 << 36)] {
|
||||
let opts = EncodeOptions::new(format).with_bit_depth(BitDepth::Int16).with_dither(false);
|
||||
let mut enc = FileEncoder::new(Cursor::new(Vec::new()), &opts, buf.sample_rate, 2).unwrap();
|
||||
enc.write(&buf.channels, 100).unwrap();
|
||||
assert!(enc.check_room(limit / 2).is_ok(), "{format:?}");
|
||||
assert!(matches!(enc.check_room(limit), Err(AudioError::TooLarge(_))), "{format:?}");
|
||||
if format == EncodeFormat::Flac {
|
||||
// 100 frames are in: STREAMINFO counts up to 2^36 - 1 in all.
|
||||
assert!(enc.check_room(limit - 101).is_ok());
|
||||
assert!(matches!(enc.check_room(limit - 100), Err(AudioError::TooLarge(_))));
|
||||
}
|
||||
// A block that does not hold the frames it claims is refused before the limit is checked.
|
||||
if let Ok(frames) = usize::try_from(limit) {
|
||||
assert!(matches!(enc.write::<Vec<f32>>(&[], frames), Err(AudioError::Encode(_))), "{format:?}");
|
||||
}
|
||||
assert_eq!(enc.finish().unwrap().into_inner(), encode(&buf, &opts).unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
// A source that stops serving reads past `fail_from`, as a network-backed file might.
|
||||
struct FlakySource {
|
||||
bytes: Vec<u8>,
|
||||
fail_from: u64,
|
||||
}
|
||||
|
||||
use craft_media::ByteSource;
|
||||
|
||||
impl ByteSource for FlakySource {
|
||||
fn len(&self) -> u64 {
|
||||
self.bytes.len() as u64
|
||||
}
|
||||
fn read_at(&self, offset: u64, buf: &mut [u8]) -> std::io::Result<()> {
|
||||
if offset + buf.len() as u64 > self.fail_from {
|
||||
return Err(std::io::Error::other("connection reset"));
|
||||
}
|
||||
self.bytes.as_slice().read_at(offset, buf)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoder_reads_any_read_seek_source_and_reports_source_failures() {
|
||||
use craft_audio::{DecodeOptions, Decoder};
|
||||
use craft_media::ReadSeekSource;
|
||||
let wav = encode(&tone(2, 48_000), &EncodeOptions::new(EncodeFormat::Wav)).unwrap();
|
||||
|
||||
// `ReadSeekSource` (any `Read + Seek`) is accepted, so a `BufReader<File>` works the same way.
|
||||
let source = ReadSeekSource::new(Cursor::new(wav.clone())).unwrap();
|
||||
let info = Decoder::open(source, Some("wav"), &DecodeOptions::default()).unwrap().probe().unwrap();
|
||||
assert_eq!((info.frames, info.damaged), (48_000, 0));
|
||||
|
||||
// A source failing half way through gives an I/O error, not concealed silence.
|
||||
let half = wav.len() as u64 / 2;
|
||||
let mut dec = Decoder::open(FlakySource { bytes: wav, fail_from: half }, Some("wav"), &DecodeOptions::default()).unwrap();
|
||||
let err = loop {
|
||||
match dec.next_block() {
|
||||
Ok(Some(_)) => continue,
|
||||
Ok(None) => panic!("the source failure was not reported"),
|
||||
Err(e) => break e,
|
||||
}
|
||||
};
|
||||
assert!(matches!(err, AudioError::Io(_)), "{err}");
|
||||
assert_eq!(dec.info().damaged, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeking_to_or_past_the_end_ends_the_stream() {
|
||||
use craft_audio::{DecodeOptions, Decoder};
|
||||
let buf = tone(2, 4800);
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff, EncodeFormat::Flac] {
|
||||
let file = encode(&buf, &EncodeOptions::new(format).with_bit_depth(BitDepth::Int16)).unwrap();
|
||||
for target in [4800, 4801, 1_000_000] {
|
||||
let mut dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap();
|
||||
assert_eq!(dec.seek(target).unwrap(), 4800, "{format:?} seek({target})");
|
||||
assert!(dec.next_block().unwrap().is_none(), "{format:?} seek({target})");
|
||||
// Seeking back still works.
|
||||
assert_eq!(dec.seek(4000).unwrap(), 4000, "{format:?}");
|
||||
let mut left = vec![Vec::new(); buf.channels.len()];
|
||||
while let Some(b) = dec.next_block().unwrap() {
|
||||
for (l, c) in left.iter_mut().zip(b.channels) {
|
||||
l.extend(c);
|
||||
}
|
||||
}
|
||||
for (l, source) in left.iter().zip(&buf.channels) {
|
||||
assert_eq!(l.len(), 800, "{format:?}");
|
||||
assert!(l.iter().zip(&source[4000..]).all(|(a, b)| (a - b.clamp(-1.0, 1.0)).abs() <= 2.0 / 32768.0), "{format:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_track_files_refuse_other_track_indexes() {
|
||||
use craft_audio::{DecodeOptions, decode_with};
|
||||
let buf = tone(1, 1000);
|
||||
for format in [EncodeFormat::Wav, EncodeFormat::Aiff] {
|
||||
let file = encode(&buf, &EncodeOptions::new(format)).unwrap();
|
||||
assert!(decode_with(&file, None, &DecodeOptions::default().with_track(0)).is_ok(), "{format:?}");
|
||||
let e = decode_with(&file, None, &DecodeOptions::default().with_track(1)).unwrap_err();
|
||||
assert!(matches!(e, AudioError::Unsupported(_)), "{format:?}: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_or_missing_channels_are_refused_without_writing() {
|
||||
let opts = EncodeOptions::new(EncodeFormat::Wav).with_bit_depth(BitDepth::Int16);
|
||||
let mut enc = FileEncoder::new(Cursor::new(Vec::new()), &opts, 48_000, 2).unwrap();
|
||||
let left = vec![0.1f32; 4];
|
||||
// More frames than the channels hold, or too few channels: refused, nothing written.
|
||||
assert!(matches!(enc.write(&[&left, &left], 10), Err(AudioError::Encode(_))));
|
||||
assert!(matches!(enc.write(&[&left], 4), Err(AudioError::Encode(_))));
|
||||
// The encoder is still usable.
|
||||
enc.write(&[&left, &left], 4).unwrap();
|
||||
let wav = enc.finish().unwrap().into_inner();
|
||||
assert_eq!(craft_audio::probe(&wav, None).unwrap().frames, 4);
|
||||
}
|
||||
|
||||
/// A 48 kHz mono float PCM Matroska file: ten 10 ms blocks from `first_ns`, with block durations
|
||||
/// when `durations` is set (otherwise its length is unknown), and a `CodecDelay` of `delay_ns`.
|
||||
fn pcm_mkv(first_ns: i64, durations: bool, delay_ns: u64) -> Vec<u8> {
|
||||
use craft_media::matroska::{LacingMode, MkvWriter, MuxOptions, TrackKind, TrackSpec};
|
||||
let mut spec = TrackSpec::new(TrackKind::Audio, "A_PCM/FLOAT/IEEE");
|
||||
spec.audio = Some((48_000.0, 1, Some(32)));
|
||||
spec.codec_delay_ns = delay_ns;
|
||||
let opts = MuxOptions { lacing: LacingMode::None, ..MuxOptions::default() };
|
||||
let mut w = MkvWriter::new(Cursor::new(Vec::new()), vec![spec], opts).unwrap();
|
||||
for k in 0..10i64 {
|
||||
let data: Vec<u8> = (0..480).flat_map(|i| ((k * 480 + i) as f32 * 0.001).sin().to_le_bytes()).collect();
|
||||
w.write_frame(0, first_ns + k * 10_000_000, true, &data, durations.then_some(10_000_000)).unwrap();
|
||||
}
|
||||
w.finish().unwrap().into_inner()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matroska_track_that_starts_late_counts_only_its_own_frames() {
|
||||
use craft_audio::{DecodeOptions, Decoder};
|
||||
let file = pcm_mkv(1_000_000_000, true, 0);
|
||||
let dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap();
|
||||
assert!(dec.length_known());
|
||||
assert_eq!(dec.info().frames, 4800);
|
||||
let decoded: usize = dec.probe().map(|i| i.frames as usize).unwrap();
|
||||
assert_eq!(decoded, 4800);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_matroska_codec_delay_is_taken_off_the_length() {
|
||||
use craft_audio::{decode, probe};
|
||||
// `probe` reports the length the container gives, before anything is decoded; `decode`
|
||||
// reports what it presented. 100 ms are decoded and the 20 ms of codec delay dropped, wherever
|
||||
// the first block is stored.
|
||||
for first_ns in [-20_000_000, 0, 50_000_000] {
|
||||
let file = pcm_mkv(first_ns, true, 20_000_000);
|
||||
let (_, buf) = decode(&file, None).unwrap();
|
||||
assert_eq!((probe(&file, None).unwrap().frames, buf.frames()), (3840, 3840), "first block at {first_ns} ns");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn seeking_far_past_an_unknown_end_does_not_overflow() {
|
||||
use craft_audio::{DecodeOptions, Decoder};
|
||||
let file = pcm_mkv(0, false, 1_000_000);
|
||||
let mut dec = Decoder::from_bytes(&file, None, &DecodeOptions::default()).unwrap();
|
||||
assert!(!dec.length_known());
|
||||
dec.seek(u64::MAX).unwrap();
|
||||
assert!(dec.next_block().unwrap().is_none());
|
||||
// and back to the start
|
||||
assert_eq!(dec.seek(0).unwrap(), 0);
|
||||
assert!(dec.next_block().unwrap().is_some_and(|b| b.frames() > 0));
|
||||
}
|
||||
@@ -37,30 +37,6 @@ fn riff(chunks: &[Vec<u8>]) -> Vec<u8> {
|
||||
out
|
||||
}
|
||||
|
||||
fn list_info() -> Vec<u8> {
|
||||
let mut l = b"INFO".to_vec();
|
||||
l.extend_from_slice(&chunk(b"INAM", b"Silence"));
|
||||
chunk(b"LIST", &l)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_data_chunk_followed_by_metadata_has_no_frames() {
|
||||
let file = riff(&[chunk(b"fmt ", &fmt16(2, 48_000)), chunk(b"data", &[]), list_info(), chunk(b"bext", &[0u8; 602])]);
|
||||
let info = probe(&file, Some("wav")).unwrap();
|
||||
assert_eq!(info.frames, 0, "the LIST and bext chunks are not samples");
|
||||
let (info, buf) = decode(&file, Some("wav")).unwrap();
|
||||
assert_eq!((info.frames, buf.frames()), (0, 0));
|
||||
// The same with the metadata first.
|
||||
let file = riff(&[chunk(b"fmt ", &fmt16(1, 44_100)), list_info(), chunk(b"data", &[])]);
|
||||
assert_eq!(probe(&file, Some("wav")).unwrap().frames, 0);
|
||||
// And with a single trailing chunk of odd size and no pad byte at the very end.
|
||||
let mut file = riff(&[chunk(b"fmt ", &fmt16(1, 44_100)), chunk(b"data", &[]), chunk(b"note", b"abc")]);
|
||||
file.pop();
|
||||
let riff_size = (file.len() - 8) as u32;
|
||||
file[4..8].copy_from_slice(&riff_size.to_le_bytes());
|
||||
assert_eq!(probe(&file, Some("wav")).unwrap().frames, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_recording_that_was_never_finalised_still_gives_its_audio() {
|
||||
let samples: Vec<u8> = (0..400i16).flat_map(|i| (i * 40).to_le_bytes()).collect();
|
||||
@@ -79,12 +55,6 @@ fn a_recording_that_was_never_finalised_still_gives_its_audio() {
|
||||
assert_eq!(probe(&file, Some("wav")).unwrap().frames, 200);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_data_chunk_with_audio_is_unchanged() {
|
||||
let samples: Vec<u8> = (0..100i16).flat_map(|i| i.to_le_bytes()).collect();
|
||||
let file = riff(&[chunk(b"fmt ", &fmt16(1, 44_100)), chunk(b"data", &samples), list_info()]);
|
||||
assert_eq!(probe(&file, Some("wav")).unwrap().frames, 100);
|
||||
}
|
||||
/// Whether an empty `data` chunk is followed by chunks alone is decided by walking the rest of the
|
||||
/// file. Doing that for every empty `data` chunk made parsing quadratic in their number (minutes
|
||||
/// for this 4 MB file); only the first one is used.
|
||||
|
||||
@@ -5,13 +5,13 @@ use std::process::Command;
|
||||
|
||||
use craft_audio::aac::{Decoder, Encoder, EncoderConfig, EncoderStats, split_adts};
|
||||
|
||||
/// ffmpeg (see `crate::testkit::oracle`); `None` after printing `SKIPPED`.
|
||||
/// ffmpeg (see `crate::integration::codecs::testkit::oracle`); `None` after printing `SKIPPED`.
|
||||
pub fn ffmpeg() -> Option<PathBuf> {
|
||||
crate::testkit::ffmpeg_or_skip("aac oracle")
|
||||
crate::integration::codecs::testkit::ffmpeg_or_skip("aac oracle")
|
||||
}
|
||||
|
||||
pub fn fixtures() -> PathBuf {
|
||||
crate::testkit::fixtures_dir("aac")
|
||||
crate::integration::codecs::testkit::fixtures_dir("aac")
|
||||
}
|
||||
|
||||
pub struct Rng(pub u64);
|
||||
|
||||
@@ -101,7 +101,7 @@ fn check_packets(packets: &[Packet], config: Config, label: &str) -> Vec<u8> {
|
||||
fn external_decode(ffmpeg: &Path, config: Config, label: &str, stream: &[u8], decoded_samples: usize) -> Vec<f32> {
|
||||
let channels = config.channels();
|
||||
let format = if config.codec == Codec::Ac3 { "ac3" } else { "eac3" };
|
||||
let path = crate::testkit::fixtures_dir("ac3-encoder-oracle").join(format!(
|
||||
let path = crate::integration::codecs::testkit::fixtures_dir("ac3-encoder-oracle").join(format!(
|
||||
"{}-{:?}-lfe{}-{}-{}.{}",
|
||||
std::process::id(),
|
||||
config.mode,
|
||||
|
||||
@@ -133,8 +133,8 @@ const SPECS: &[Spec] = &[
|
||||
];
|
||||
|
||||
fn make(ff: &Path, s: &Spec) -> Option<PathBuf> {
|
||||
let out = crate::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec));
|
||||
crate::testkit::fixtures::generate(&out, |tmp| {
|
||||
let out = crate::integration::codecs::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec));
|
||||
crate::integration::codecs::testkit::fixtures::generate(&out, |tmp| {
|
||||
let st = Command::new(ff)
|
||||
.args(["-hide_banner", "-v", "error", "-y", "-f", "lavfi", "-i", s.input, "-t", "1"])
|
||||
.args(["-c:a", s.codec])
|
||||
@@ -257,10 +257,10 @@ fn damaged_eac3_frames_never_panic() {
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn generate_fixtures() {
|
||||
let Some(ff) = crate::testkit::ffmpeg_or_skip("ac3 fixtures") else { return };
|
||||
let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("ac3 fixtures") else { return };
|
||||
for s in SPECS {
|
||||
let out = crate::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec));
|
||||
crate::testkit::fixtures::generate_and_report(&format!("ac3/{}", s.name), &[out], || make(&ff, s));
|
||||
let out = crate::integration::codecs::testkit::fixtures_dir("ac3").join(format!("{}.{}", s.name, s.codec));
|
||||
crate::integration::codecs::testkit::fixtures::generate_and_report(&format!("ac3/{}", s.name), &[out], || make(&ff, s));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
fn dir() -> PathBuf {
|
||||
crate::testkit::fixtures_dir("alac")
|
||||
crate::integration::codecs::testkit::fixtures_dir("alac")
|
||||
}
|
||||
|
||||
/// The ffmpeg channel layout ALAC uses for `channels`.
|
||||
@@ -103,7 +103,7 @@ fn our_decode(bytes: &[u8], bits: u32) -> Vec<Vec<i32>> {
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_alac_decodes_exactly() {
|
||||
let Some(ff) = crate::testkit::ffmpeg_or_skip("alac oracle") else { return };
|
||||
let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return };
|
||||
for (channels, bits) in [(1, 16), (2, 16), (2, 24), (3, 16), (4, 16), (5, 24), (6, 24), (7, 16), (8, 16)] {
|
||||
let wav = input(channels, bits, 12_345);
|
||||
let name = format!("ffmpeg_{channels}ch_{bits}");
|
||||
@@ -128,7 +128,7 @@ fn ffmpeg_alac_decodes_exactly() {
|
||||
/// frames ("not yet implemented"), which the noise in the input produces; Apple's decoder does.
|
||||
#[test]
|
||||
fn ffmpeg_decodes_our_alac_exactly() {
|
||||
let Some(ff) = crate::testkit::ffmpeg_or_skip("alac oracle") else { return };
|
||||
let Some(ff) = crate::integration::codecs::testkit::ffmpeg_or_skip("alac oracle") else { return };
|
||||
for (channels, bits, frame) in [
|
||||
(1, 16, 4096),
|
||||
(2, 16, 4096),
|
||||
|
||||
Loaded 100 of 491 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user