From 3c1926cd23a026e92240b70066cecc03192b212e Mon Sep 17 00:00:00 2001 From: Nicolas Bohn Date: Sat, 14 Nov 2026 23:54:21 +0100 Subject: [PATCH] Save Unity sounds: a WAV for 16-bit PCM, else the FMOD bank (R3.9) (#1879) game_unity_asset_export now takes AudioClips (Unity 5 and later). The sound is read from the .resource file beside the serialized file or inside the bundle, 256 MiB at most. A single 16-bit PCM sample in mono or stereo is saved as a WAV; anything else (Vorbis, ADPCM, a bank that isn't read) is saved as the FMOD bank it's stored in, with a limitation saying so. The output's extension is set to .wav or .fsb to match. --- crates/ai/src/rebuild/brief.rs | 4 +- crates/engine/src/tools/game_archive_tools.rs | 195 +++++++++++++- crates/formats/src/lib.rs | 1 + crates/formats/src/unity_audio.rs | 247 ++++++++++++++++++ crates/formats/tests/unity_audio.rs | 124 +++++++++ crates/testkit/src/games.rs | 58 ++++ docs/ROADMAP.md | 3 +- docs/STATUS.md | 1 + 8 files changed, 624 insertions(+), 9 deletions(-) create mode 100644 crates/formats/src/unity_audio.rs create mode 100644 crates/formats/tests/unity_audio.rs diff --git a/crates/ai/src/rebuild/brief.rs b/crates/ai/src/rebuild/brief.rs index 9afa5f805..b82c948c7 100644 --- a/crates/ai/src/rebuild/brief.rs +++ b/crates/ai/src/rebuild/brief.rs @@ -243,7 +243,7 @@ pub(super) fn extract_brief(folder: &Path) -> String { "You are the asset extractor inside Craft Anything. The person owns this game and has its developer's permission to use its files in a private rebuild on this computer. Take the game's own files out of its folder ({}) into app/Original/ so the builder can use them. You don't build the game.\n\ - Call enable_toolset with \"formats\". game_archives_list finds the game's archives; game_pak_list, game_iostore_list, game_unity_list and game_unity_bundle_list show what's inside.\n\ - game_pak_extract takes files out of an Unreal .pak and makes their folders: a `file` ending in `/` (for example Game/Content/UI/) takes that whole folder in one call into the folder `output`, keeping its layout; when it says files are left, call it again the same way to carry on.\n\ - - Pictures: game_unreal_texture_export (with permission: true) or game_unity_asset_export, saved as PNG. Sounds and models: take them out with game_pak_extract as they are; convert them only with a converter you set up inside app/Original/tools/.\n\ + - Pictures: game_unreal_texture_export (with permission: true) or game_unity_asset_export, saved as PNG. Unity sounds: game_unity_asset_export too, as a WAV or as the FMOD bank (.fsb) they're stored in. Other sounds and models: take them out with game_pak_extract as they are; convert them only with a converter you set up inside app/Original/tools/.\n\ - Read the archives only with these tools; never write your own archive reader or parser. When a tool fails, read its error, fix the call and try again; if a tool can't do something, say so in your summary.\n\ - Keep the game's folder layout under app/Original/ (for example app/Original/Content/UI/Logo.png). Take what a rebuild needs first: the player's view (arms and weapons), the main enemies, the level's materials and props, the interface and its fonts, and the sounds and music.\n\ - Never decrypt, crack or bypass protection: an encrypted archive stays closed; say so and move on.\n\ @@ -310,7 +310,7 @@ pub(super) fn game_steps(deep: bool, ghidra: bool, has_target: bool, generated: ) }; s.push_str(&format!( - "\n{lead}, from their own installed copy. Use the originals wherever they can be read: bring {bring} from the game folder into the project (converting formats as the engine needs), for the person's own use on this computer. Craft Anything's own tools read game archives, so use them first: call enable_toolset with \"formats\", then game_archives_list finds the game's archives, game_pak_list, game_iostore_list, game_unity_list and game_unity_bundle_list show what's inside, game_pak_extract takes files out of an Unreal .pak, and game_unreal_texture_export (with permission: true, since the person asked for the originals) and game_unity_asset_export save pictures as PNG. Set up another converter only for what these can't convert yet (such as models and sounds), and keep it inside the project folder. Never decrypt, crack or bypass encryption or copy protection: files inside encrypted archives (for example encrypted .pak, .utoc or .ucas files) stay closed. Recreate those as closely as you can from the pictures, the game's readable data and how it plays, in the same role, size, palette and feel, without reproducing logos or trademarks. List every original file you used in app/CREDITS.md with its source path, and start app/README.md with this line, as written: \"{PRIVATE_USE_NOTE}\" Craft Anything checks both after each build.", + "\n{lead}, from their own installed copy. Use the originals wherever they can be read: bring {bring} from the game folder into the project (converting formats as the engine needs), for the person's own use on this computer. Craft Anything's own tools read game archives, so use them first: call enable_toolset with \"formats\", then game_archives_list finds the game's archives, game_pak_list, game_iostore_list, game_unity_list and game_unity_bundle_list show what's inside, game_pak_extract takes files out of an Unreal .pak, and game_unreal_texture_export (with permission: true, since the person asked for the originals) and game_unity_asset_export save pictures as PNG (and Unity sounds, as a WAV or the FMOD bank they're stored in). Set up another converter only for what these can't convert yet (such as models and sounds), and keep it inside the project folder. Never decrypt, crack or bypass encryption or copy protection: files inside encrypted archives (for example encrypted .pak, .utoc or .ucas files) stay closed. Recreate those as closely as you can from the pictures, the game's readable data and how it plays, in the same role, size, palette and feel, without reproducing logos or trademarks. List every original file you used in app/CREDITS.md with its source path, and start app/README.md with this line, as written: \"{PRIVATE_USE_NOTE}\" Craft Anything checks both after each build.", )); } s diff --git a/crates/engine/src/tools/game_archive_tools.rs b/crates/engine/src/tools/game_archive_tools.rs index 741deefb7..b691dabe6 100644 --- a/crates/engine/src/tools/game_archive_tools.rs +++ b/crates/engine/src/tools/game_archive_tools.rs @@ -8,6 +8,7 @@ use super::web_common::{Image, encode_png}; use crate::tool::{CancelToken, Ctx, Effects, Requires, ToolOutput, ToolSpec, Toolset, parse_params, schema_of}; use craft_anything_evidence::{Confidence, Coverage, CoverageStatus, ErrorCode, Limitation, Location, Subject, ToolError}; use craft_anything_formats::godot_pck; +use craft_anything_formats::unity_audio; use craft_anything_formats::unity_bundle; use craft_anything_formats::unity_serialized; use craft_anything_formats::unity_texture; @@ -87,8 +88,8 @@ pub fn specs() -> Vec { spec( "game_unity_asset_export", "Take an asset out of a Unity game", - "Save one object of a Unity serialized file (absolute path of a .assets or level file, or of a bundle: then `file` picks the serialized file inside, the first by default) as a file anyone can open: a texture (Texture2D, by its path_id from game_unity_list) becomes a PNG at `output` (an absolute path that doesn't exist yet). Pixels are read inside the object or from the .resS file it streams from. Formats: Alpha8, R8, RGB24, RGBA32, ARGB32, BGRA32, RGB565, RGBA4444, ARGB4444, RHalf, RGHalf, RGBAHalf, RFloat, RGFloat, RGBAFloat, DXT1, DXT5, BC4, BC5, BC6H and BC7. Floating-point colours are shown in 8-bit sRGB and clip at white. Other formats (crunched, ASTC, ETC…) are refused with their name. Unity 2017.3 and later.", - "Save a picture from a Unity game as a PNG.", + "Save one object of a Unity serialized file (absolute path of a .assets or level file, or of a bundle: then `file` picks the serialized file inside, the first by default) as a file anyone can open, at `output` (an absolute path that doesn't exist yet), by its path_id from game_unity_list. A texture (Texture2D) becomes a PNG. A sound (AudioClip, Unity 5 and later) is read from the .resource file it's stored in: one in 16-bit PCM (Unity's uncompressed sound), mono or stereo, becomes a WAV, others (Vorbis, ADPCM…) are saved as the FMOD sound bank (FSB5) they're stored in; `output`'s extension is set to .wav or .fsb to match, and `saved_as` says which. Pixels are read inside the object or from the .resS file it streams from. Formats: Alpha8, R8, RGB24, RGBA32, ARGB32, BGRA32, RGB565, RGBA4444, ARGB4444, RHalf, RGHalf, RGBAHalf, RFloat, RGFloat, RGBAFloat, DXT1, DXT5, BC4, BC5, BC6H and BC7. Floating-point colours are shown in 8-bit sRGB and clip at white. Other formats (crunched, ASTC, ETC…) are refused with their name. Textures from Unity 2017.3 on.", + "Save a picture or a sound from a Unity game.", Toolset::Formats, Effects::EVIDENCE.union(Effects::WRITES_FILESYSTEM), Requires::Nothing, @@ -895,19 +896,23 @@ fn game_unity_asset_export(ctx: &mut Ctx<'_>, params: Value) -> Result_Data folder, beside its globalgamemanagers file.")); } let bytes = src.read(object.offset, u64::from(object.size))?; + if object.class_id == 83 { + return unity_sound_export(ctx, &p, &out, &mut src, &bytes, &version, h.big_endian); + } let t = unity_texture::parse(&bytes, &version, h.big_endian).map_err(|e| format_err(e, "a Unity texture"))?; let format = unity_texture::format_name(t.format); if u64::from(t.width) * u64::from(t.height) > MAX_PIXELS { @@ -946,6 +951,110 @@ fn game_unity_asset_export(ctx: &mut Ctx<'_>, params: Value) -> Result PathBuf { + match out.extension().and_then(|e| e.to_str()).map(str::to_ascii_lowercase).as_deref() { + Some("wav" | "fsb") => out.with_extension(extension), + _ => { + let mut name = out.as_os_str().to_owned(); + name.push("."); + name.push(extension); + PathBuf::from(name) + } + } +} + +/// Save an AudioClip: a WAV when its FSB5 bank holds one plain PCM sound, else the stored bytes. +fn unity_sound_export( + ctx: &mut Ctx<'_>, + p: &ExportParams, + out: &Path, + src: &mut Serialized, + bytes: &[u8], + version: &str, + big_endian: bool, +) -> Result { + let clip = unity_audio::parse(bytes, version, big_endian).map_err(|e| format_err(e, "a Unity sound"))?; + let compression = unity_audio::compression_name(clip.compression); + if clip.stream.size > MAX_SOUND_BYTES { + return Err(ToolError::new(ErrorCode::OverLimit, format!("{} is {} bytes; the limit is 256 MiB", clip.name, clip.stream.size))); + } + let stored = src.stream(&clip.stream.path, clip.stream.offset, clip.stream.size)?; + let mut lims = Vec::new(); + let (saved, codec, wav) = if stored.starts_with(unity_audio::FSB5) { + match unity_audio::bank(&stored) { + Ok(bank) => { + let codec = unity_audio::codec_name(bank.codec); + let wav = match bank.samples.as_slice() { + [one] => unity_audio::wav(&bank, one, &stored), + _ => None, + }; + if wav.is_none() { + lims.push(Limitation::new( + "stored_as_is", + format!( + "{} is stored as {codec} in an FMOD sound bank (FSB5) of {} sample(s); it's saved as that bank, which tools that read FSB files can convert.", + clip.name, + bank.samples.len() + ), + )); + } + (if wav.is_some() { "wav" } else { "fsb5" }, Some(codec), wav) + } + Err(e) => { + lims.push(Limitation::new("stored_as_is", format!("{}'s FMOD sound bank isn't one that's read here ({e}); it's saved as it is.", clip.name))); + ("fsb5", None, None) + } + } + } else { + lims.push(Limitation::new("stored_as_is", format!("{}'s stored sound isn't an FMOD sound bank; its bytes are saved as they are.", clip.name))); + ("stored", None, None) + }; + // What's saved isn't known before the sound is read, so the file gets the extension it needs. + let out = match saved { + "wav" => with_sound_extension(out, "wav"), + "fsb5" => with_sound_extension(out, "fsb"), + _ => out.to_path_buf(), + }; + if out.exists() { + return Err(ToolError::invalid(format!("{} already exists", out.display())).with_remediation("Pick a new file name; nothing is overwritten.")); + } + let file = wav.unwrap_or(stored); + crate::project::write_atomic(&out, &file)?; + let result = json!({ + "path_id": p.path_id, + "name": clip.name, + "class": "AudioClip", + "channels": clip.channels, + "frequency": clip.frequency, + "seconds": clip.length, + "compression": compression, + "codec": codec, + "saved_as": saved, + "streamed_from": clip.stream.path, + "output": out.display().to_string(), + "size": file.len(), + "sha256": craft_anything_evidence::sha256_hex(&file), + }); + let shown = match saved { + "wav" => "a WAV file".to_string(), + "fsb5" => "its FMOD sound bank".to_string(), + _ => "its stored bytes".to_string(), + }; + let name = Path::new(&p.path).file_name().map(|n| n.to_string_lossy().into_owned()); + let b = builder(ctx, "game_unity_asset_export", Subject { kind: "archive".into(), sha256: None, name }, params_json(p)) + .result(result) + .summary(format!("Saved sound \"{}\" ({:.2} s, {compression}) as {shown} at {}.", clip.name, clip.length, out.display())) + .confidence(Confidence::Observed) + .coverage(Coverage::complete(1)) + .limitations(lims) + .location(Location::new("path", out.display().to_string())); + Ok(ToolOutput::evidence(b.build()?)) +} + #[derive(Debug, Deserialize, Serialize, JsonSchema)] #[serde(deny_unknown_fields)] pub struct UnrealTextureParams { @@ -2022,6 +2131,80 @@ mod tests { assert!(decode("from-bundle.png").rgba.as_chunks::<4>().0.iter().all(|p| *p == [255, 0, 0, 255])); } + #[test] + fn saves_unity_sounds_as_wav_or_as_their_bank() { + use craft_anything_testkit::games::{fsb5_bank, unity_audioclip, unity_bundle_files, unity_serialized_file}; + let e = Engine::new(crate::testing::session()); + let dir = tempfile::tempdir().unwrap(); + // A PCM16 mono bank and a Vorbis one, one after the other in the .resource file. + let pcm: Vec = (1..=8).collect(); + let wav_bank = fsb5_bank(2, &[(8, 1, 4, &pcm)]); + let vorbis_bank = fsb5_bank(15, &[(9, 2, 960, &[5; 40])]); + let mut resource = wav_bank.clone(); + resource.extend_from_slice(&vorbis_bank); + let at = wav_bank.len() as u64; + let mut broken = fsb5_bank(2, &[(8, 1, 4, &pcm)]); + broken[4] = 9; // a version that isn't read + let broken_at = resource.len() as u64; + resource.extend_from_slice(&broken); + let resource_name = "sharedassets0.resource"; + let objects = [ + (83, unity_audioclip("2019.4.19f1", "Click", 1, 44100, 0.0001, 0, (resource_name, 0, at))), + (83, unity_audioclip("2019.4.19f1", "Theme", 2, 48000, 0.02, 1, (resource_name, at, vorbis_bank.len() as u64))), + (83, unity_audioclip("2019.4.19f1", "Raw", 1, 8000, 0.1, 0, (resource_name, 2, 6))), + (83, unity_audioclip("2019.4.19f1", "Huge", 1, 8000, 0.1, 0, (resource_name, 0, 1 << 40))), + (83, unity_audioclip("2019.4.19f1", "Odd", 1, 44100, 0.0001, 0, (resource_name, broken_at, broken.len() as u64))), + ]; + std::fs::write(dir.path().join("sharedassets0.assets"), unity_serialized_file("2019.4.19f1", &objects)).unwrap(); + std::fs::write(dir.path().join(resource_name), &resource).unwrap(); + let file = dir.path().join("sharedassets0.assets"); + let call = |path: &std::path::Path, id: i64, out: &str| { + e.call("game_unity_asset_export", json!({"path": path, "path_id": id, "output": dir.path().join(out)}), CallOptions::new(Caller::Mcp)) + }; + let v = call(&file, 1, "click.wav").unwrap().to_json(); + let r = &v["result"]; + assert_eq!( + (r["class"].as_str(), r["compression"].as_str(), r["codec"].as_str(), r["saved_as"].as_str()), + (Some("AudioClip"), Some("PCM"), Some("PCM16"), Some("wav")), + "{v}" + ); + assert!(v["limitations"].as_array().unwrap().is_empty(), "{v}"); + let wav = std::fs::read(dir.path().join("click.wav")).unwrap(); + assert_eq!((&wav[..4], &wav[44..]), (b"RIFF".as_slice(), pcm.as_slice())); + assert_eq!(r["sha256"].as_str(), Some(craft_anything_evidence::sha256_hex(&wav).as_str())); + // Vorbis is saved as the bank it's stored in, and says so. + let v = call(&file, 2, "theme.fsb").unwrap().to_json(); + assert_eq!((v["result"]["codec"].as_str(), v["result"]["saved_as"].as_str()), (Some("Vorbis"), Some("fsb5"))); + assert_eq!(v["limitations"][0]["code"].as_str(), Some("stored_as_is")); + assert_eq!(std::fs::read(dir.path().join("theme.fsb")).unwrap(), vorbis_bank); + // Asked for a WAV, a bank gets the extension it needs; a bank that isn't read is still saved. + let v = call(&file, 2, "theme-again.wav").unwrap().to_json(); + assert_eq!(v["result"]["output"].as_str(), Some(dir.path().join("theme-again.fsb").to_str().unwrap())); + assert!(!dir.path().join("theme-again.wav").exists()); + assert!(call(&file, 2, "theme.wav").unwrap_err().message.contains("already exists"), "theme.fsb is there"); + let v = call(&file, 5, "odd.sharedassets0-5").unwrap().to_json(); + assert_eq!((v["result"]["saved_as"].as_str(), v["result"]["codec"].as_str()), (Some("fsb5"), None)); + assert!(v["limitations"][0]["message"].as_str().unwrap().contains("FSB5 version 9"), "{v}"); + assert_eq!(std::fs::read(dir.path().join("odd.sharedassets0-5.fsb")).unwrap(), broken, "a dot in the name is kept"); + // Stored bytes that aren't a bank are saved as they are; a size past the limit isn't read. + let v = call(&file, 3, "raw.bin").unwrap().to_json(); + assert_eq!((v["result"]["saved_as"].as_str(), v["result"]["codec"].as_str()), (Some("stored"), None)); + assert_eq!(std::fs::read(dir.path().join("raw.bin")).unwrap(), &resource[2..8]); + let err = call(&file, 4, "huge.wav").unwrap_err(); + assert_eq!(err.code, craft_anything_evidence::ErrorCode::OverLimit, "{err:?}"); + assert!(!dir.path().join("huge.wav").exists()); + + // Inside a bundle, the sound is in the bundle's .resource. + let clip = unity_audioclip("2022.3.43f1", "Click", 1, 44100, 0.0001, 0, ("archive:/CAB-0123456789abcdef/CAB-0123456789abcdef.resource", 0, at)); + let assets = unity_serialized_file("2022.3.43f1", &[(83, clip)]); + let bundle = unity_bundle_files(&[("CAB-0123456789abcdef", &assets, true), ("CAB-0123456789abcdef.resource", &resource, false)]); + let b = dir.path().join("sounds.bundle"); + std::fs::write(&b, bundle).unwrap(); + let v = call(&b, 1, "from-bundle.wav").unwrap().to_json(); + assert_eq!(v["result"]["saved_as"].as_str(), Some("wav"), "{v}"); + assert_eq!(std::fs::read(dir.path().join("from-bundle.wav")).unwrap(), wav); + } + #[test] fn saves_unreal_textures_only_with_permission() { use craft_anything_testkit::games::{unreal_pak, unreal_texture_package}; diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index a0ccf1ec3..6414b0d9c 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -58,6 +58,7 @@ pub mod strings; pub mod swift; pub mod swift_demangle; pub mod tarcpio; +pub mod unity_audio; pub mod unity_bundle; pub mod unity_serialized; pub mod unity_texture; diff --git a/crates/formats/src/unity_audio.rs b/crates/formats/src/unity_audio.rs new file mode 100644 index 000000000..31dabaf4f --- /dev/null +++ b/crates/formats/src/unity_audio.rs @@ -0,0 +1,247 @@ +//! Unity AudioClip objects and the FMOD sound banks (FSB5) their sound is stored in. +//! +//! An AudioClip from Unity 5 on holds no sound itself. After its name come the load type, the +//! channel count, the frequency and bits per sample (4 bytes each), the length in seconds (a +//! float), a tracker-format flag (and from 2017 an ambisonic one in the same 4 bytes); the subsound +//! index, three flags (preload, load in background, legacy 3D), aligned; then where the sound is +//! (a file path, a 64-bit offset and size: a `.resource` file beside the serialized file, or +//! `archive:/…` inside a bundle) and the compression format. +//! +//! The bytes there are an FSB5 bank: `FSB5`, its version, the sample count, the sizes of the +//! sample headers, the name table and the data, and the codec, then 32 more header bytes (36 in +//! version 0). Each sample header is 64 bits: bit 0 says chunks follow, bits 1-4 are a frequency +//! index, bit 5 says stereo, bits 6-33 the data offset in 16-byte units and bits 34-63 the frame +//! count; the chunks after it can set the channel count or the frequency. Readings of the format +//! differ on bit 6 (a channel-count bit, the offset then in 32-byte units), so a header with it set +//! is refused rather than read one way. Sample data follows the name table, each sample's up to +//! the next one's. + +use crate::common::FormatError; +use crate::unity_serialized::{Cur, version_numbers}; +use serde::Serialize; + +/// The oldest Unity version whose AudioClip layout is read. +pub const MIN_VERSION: (u32, u32) = (5, 0); +/// The longest name kept. +const MAX_NAME: usize = 1024; +/// The most samples a bank may hold (Unity writes one). +pub const MAX_SAMPLES: usize = 65_536; + +/// Where a clip's sound is stored. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct StreamRef { + pub path: String, + pub offset: u64, + pub size: u64, +} + +/// An AudioClip's description. +#[derive(Debug, Clone, PartialEq, Serialize)] +pub struct Clip { + pub name: String, + pub channels: i32, + pub frequency: i32, + pub bits_per_sample: i32, + /// Seconds. + pub length: f32, + pub subsound_index: i32, + /// Unity's compression format id ([`compression_name`]). + pub compression: i32, + pub stream: StreamRef, +} + +fn string(c: &mut Cur, what: &str) -> Result { + let n = c.count(what, 1)?; + let s = String::from_utf8_lossy(c.take(n, what)?).chars().take(MAX_NAME).collect(); + c.align4()?; + Ok(s) +} + +/// Read an AudioClip object's bytes (`object`), from a file written by `unity_version`. +pub fn parse(object: &[u8], unity_version: &str, big_endian: bool) -> Result { + let v = version_numbers(unity_version).ok_or_else(|| FormatError::Malformed(format!("Unity version {unity_version:?}")))?; + if v < MIN_VERSION { + return Err(FormatError::Unsupported(format!("sounds from Unity {unity_version} (before 5.0)"))); + } + let unknown = || FormatError::Unsupported(format!("this sound's layout (Unity {unity_version}) isn't one that's read here")); + let mut c = Cur { data: object, pos: 0, big: big_endian }; + let name = string(&mut c, "name")?; + c.i32("load type")?; + let channels = c.i32("channels")?; + let frequency = c.i32("frequency")?; + let bits_per_sample = c.i32("bits per sample")?; + let length = f32::from_bits(c.u32("length")?); + c.u8("tracker format")?; + c.align4()?; + let subsound_index = c.i32("subsound index")?; + c.take(3, "load flags")?; + c.align4()?; + let path = string(&mut c, "resource path")?; + let offset = c.u64("resource offset")?; + let size = c.u64("resource size")?; + let compression = c.i32("compression format")?; + // What a wrong layout would give: an impossible count, rate or length, or bytes left over. + if !(1..=64).contains(&channels) + || !(1..=768_000).contains(&frequency) + || !(0..=64).contains(&bits_per_sample) + || !length.is_finite() + || length < 0.0 + || c.pos != object.len() + { + return Err(unknown()); + } + if path.is_empty() || size == 0 { + return Err(FormatError::Unsupported(format!("{name} keeps no sound of its own (it names no .resource file, or no bytes in it)"))); + } + Ok(Clip { name, channels, frequency, bits_per_sample, length, subsound_index, compression, stream: StreamRef { path, offset, size } }) +} + +/// Unity's audio compression formats by id. +const COMPRESSIONS: &[&str] = &["PCM", "Vorbis", "ADPCM", "MP3", "VAG", "HEVAG", "XMA", "AAC", "GCADPCM", "ATRAC9"]; + +/// A compression format's name, or `format `. +pub fn compression_name(id: i32) -> String { + usize::try_from(id).ok().and_then(|i| COMPRESSIONS.get(i)).map_or_else(|| format!("format {id}"), |n| (*n).to_string()) +} + +/// The FSB5 magic. +pub const FSB5: &[u8; 4] = b"FSB5"; + +/// FSB5 codecs by id. +const CODECS: &[&str] = + &["none", "PCM8", "PCM16", "PCM24", "PCM32", "PCMFLOAT", "GCADPCM", "IMAADPCM", "VAG", "HEVAG", "XMA", "MPEG", "CELT", "AT9", "XWMA", "Vorbis"]; + +/// An FSB5 codec's name, or `codec `. +pub fn codec_name(id: u32) -> String { + usize::try_from(id).ok().and_then(|i| CODECS.get(i)).map_or_else(|| format!("codec {id}"), |n| (*n).to_string()) +} + +/// Sample rates by the index in a sample header. +const RATES: [u32; 10] = [0, 8000, 11000, 11025, 16000, 22050, 24000, 32000, 44100, 48000]; + +/// One sound in a bank. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Sample { + pub frequency: u32, + pub channels: u32, + pub frames: u32, + /// Where its data is in the bank's bytes: start and length. + #[serde(skip)] + pub data: (usize, usize), +} + +/// An FSB5 bank's header and samples. +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub struct Bank { + pub version: u32, + pub codec: u32, + pub samples: Vec, + /// Bytes the bank takes, from `FSB5` to the end of its data. + pub size: usize, +} + +fn le32(data: &[u8], at: usize, what: &str) -> Result { + let b = data.get(at..at.checked_add(4).ok_or_else(|| FormatError::Truncated(what.into()))?).ok_or_else(|| FormatError::Truncated(what.into()))?; + Ok(u32::from_le_bytes([b[0], b[1], b[2], b[3]])) +} + +fn bits(value: u64, start: u32, len: u32) -> u64 { + (value >> start) & ((1 << len) - 1) +} + +/// Read an FSB5 bank at the start of `data`. +pub fn bank(data: &[u8]) -> Result { + if !data.starts_with(FSB5) { + return Err(FormatError::Malformed("not an FSB5 bank".into())); + } + let version = le32(data, 4, "FSB5 version")?; + let header = match version { + 0 => 0x40, + 1 => 0x3c, + v => return Err(FormatError::Unsupported(format!("FSB5 version {v}"))), + }; + let field = |i: usize, what: &str| le32(data, 8 + 4 * i, what).map(|n| n as usize); + let (count, headers, names, size) = (field(0, "sample count")?, field(1, "sample headers size")?, field(2, "name table size")?, field(3, "data size")?); + let codec = le32(data, 24, "codec")?; + let truncated = || FormatError::Truncated("FSB5 sample data".into()); + let table_end = headers.checked_add(header).ok_or_else(truncated)?; + let start = table_end.checked_add(names).ok_or_else(truncated)?; + let end = start.checked_add(size).filter(|e| *e <= data.len()).ok_or_else(truncated)?; + // Each sample header takes 8 bytes at least, so a count that can't fit is refused unread. + if count == 0 || count > MAX_SAMPLES || count.saturating_mul(8) > headers { + return Err(FormatError::Malformed(format!("FSB5 sample count {count} doesn't fit its {headers}-byte headers"))); + } + let table = data.get(header..table_end).ok_or_else(|| FormatError::Truncated("FSB5 sample headers".into()))?; + let mut at = 0; + let mut found = Vec::with_capacity(count); + for _ in 0..count { + let raw = table.get(at..at + 8).ok_or_else(|| FormatError::Truncated("FSB5 sample header".into()))?; + let raw = u64::from_le_bytes(raw.try_into().map_err(|_| FormatError::Truncated("FSB5 sample header".into()))?); + at += 8; + if raw & 1 << 6 != 0 { + return Err(FormatError::Unsupported("an FSB5 sample header with bit 6 set, which readings of the format disagree on".into())); + } + let mut frequency = RATES.get(bits(raw, 1, 4) as usize).copied().unwrap_or(0); + let mut channels = bits(raw, 5, 1) as u32 + 1; + let offset = bits(raw, 7, 27) as usize * 32; + let frames = bits(raw, 34, 30) as u32; + let mut more = raw & 1 == 1; + while more { + let chunk = le32(table, at, "FSB5 sample chunk")?; + at += 4; + more = chunk & 1 == 1; + let len = ((chunk >> 1) & 0xff_ffff) as usize; + let body = table + .get(at..at.checked_add(len).ok_or_else(|| FormatError::Truncated("FSB5 sample chunk".into()))?) + .ok_or_else(|| FormatError::Truncated("FSB5 sample chunk".into()))?; + match (chunk >> 25, body) { + (1, [n, ..]) => channels = u32::from(*n), + (2, [a, b, c, d, ..]) => frequency = u32::from_le_bytes([*a, *b, *c, *d]), + _ => {} + } + at += len; + } + if offset > size { + return Err(FormatError::Malformed(format!("an FSB5 sample starts past its data ({offset} of {size} bytes)"))); + } + found.push((Sample { frequency, channels, frames, data: (start.checked_add(offset).ok_or_else(truncated)?, 0) }, offset)); + } + let mut samples = Vec::with_capacity(count); + for i in 0..found.len() { + let next = found.get(i + 1).map_or(size, |(_, o)| *o); + let (mut sample, offset) = found[i].clone(); + let len = next.checked_sub(offset).ok_or_else(|| FormatError::Malformed("FSB5 samples are out of order".into()))?; + sample.data.1 = len; + samples.push(sample); + } + Ok(Bank { version, codec, samples, size: end }) +} + +/// A WAV file of one sample of `bank` (whose bytes are `data`), or `None` unless it's 16-bit PCM in +/// mono or stereo (what Unity's PCM is, and what a plain WAV header describes) whose frames fit. +pub fn wav(bank: &Bank, sample: &Sample, data: &[u8]) -> Option> { + let (bytes, tag) = (2u32, 1u16); + if bank.codec != 2 || !(1..=2).contains(&sample.channels) || sample.frequency == 0 { + return None; + } + let len = u64::from(sample.frames) * u64::from(sample.channels) * u64::from(bytes); + let len = usize::try_from(len).ok().filter(|n| *n <= sample.data.1)?; + let pcm = data.get(sample.data.0..sample.data.0.checked_add(len)?)?; + let riff = u32::try_from(36 + len).ok()?; + let block = u16::try_from(sample.channels * bytes).ok()?; + let mut out = Vec::with_capacity(44 + len); + out.extend_from_slice(b"RIFF"); + out.extend_from_slice(&riff.to_le_bytes()); + out.extend_from_slice(b"WAVEfmt "); + out.extend_from_slice(&16u32.to_le_bytes()); + out.extend_from_slice(&tag.to_le_bytes()); + out.extend_from_slice(&u16::try_from(sample.channels).ok()?.to_le_bytes()); + out.extend_from_slice(&sample.frequency.to_le_bytes()); + out.extend_from_slice(&(sample.frequency.checked_mul(u32::from(block))?).to_le_bytes()); + out.extend_from_slice(&block.to_le_bytes()); + out.extend_from_slice(&(bytes as u16 * 8).to_le_bytes()); + out.extend_from_slice(b"data"); + out.extend_from_slice(&(len as u32).to_le_bytes()); + out.extend_from_slice(pcm); + Some(out) +} diff --git a/crates/formats/tests/unity_audio.rs b/crates/formats/tests/unity_audio.rs new file mode 100644 index 000000000..b9e1f48ee --- /dev/null +++ b/crates/formats/tests/unity_audio.rs @@ -0,0 +1,124 @@ +use craft_anything_formats::unity_audio::{self, Clip, StreamRef}; +use craft_anything_testkit::games::{fsb5_bank, unity_audioclip}; + +#[test] +fn reads_audioclips_from_unity_5_to_unity_6() { + for version in ["5.6.7f1", "2017.4.40f1", "2019.4.19f1", "2022.3.43f1", "6000.0.23f1"] { + let bytes = unity_audioclip(version, "Jump", 2, 44100, 1.5, 1, ("sharedassets0.resource", 4096, 777)); + let clip = unity_audio::parse(&bytes, version, false).unwrap_or_else(|e| panic!("{version}: {e}")); + assert_eq!( + clip, + Clip { + name: "Jump".into(), + channels: 2, + frequency: 44100, + bits_per_sample: 16, + length: 1.5, + subsound_index: 0, + compression: 1, + stream: StreamRef { path: "sharedassets0.resource".into(), offset: 4096, size: 777 }, + }, + "{version}" + ); + assert_eq!(unity_audio::compression_name(clip.compression), "Vorbis"); + } +} + +#[test] +fn a_layout_it_does_not_know_is_refused() { + let bytes = unity_audioclip("2019.4.19f1", "Jump", 2, 44100, 1.5, 0, ("a.resource", 0, 10)); + // Bytes left over, or missing, mean the fields weren't where they were looked for. + let mut longer = bytes.clone(); + longer.extend_from_slice(&[0; 4]); + assert!(unity_audio::parse(&longer, "2019.4.19f1", false).is_err()); + assert!(unity_audio::parse(&bytes[..bytes.len() - 1], "2019.4.19f1", false).is_err()); + assert!(unity_audio::parse(&bytes, "4.7.2f1", false).is_err(), "before 5.0"); + let silent = unity_audioclip("2019.4.19f1", "Gap", 1, 22050, 0.0, 0, ("", 0, 0)); + let e = unity_audio::parse(&silent, "2019.4.19f1", false).unwrap_err().to_string(); + assert!(e.contains("no sound of its own"), "{e}"); +} + +#[test] +fn a_pcm_bank_becomes_a_wav() { + let pcm: Vec = (0..20u8).collect(); // 5 stereo frames of 16 bits + let bank_bytes = fsb5_bank(2, &[(9, 2, 5, &pcm)]); + let bank = unity_audio::bank(&bank_bytes).unwrap(); + assert_eq!((bank.version, unity_audio::codec_name(bank.codec).as_str(), bank.size), (1, "PCM16", bank_bytes.len())); + let [sample] = bank.samples.as_slice() else { panic!("{:?}", bank.samples) }; + assert_eq!((sample.frequency, sample.channels, sample.frames), (48000, 2, 5)); + let wav = unity_audio::wav(&bank, sample, &bank_bytes).unwrap(); + assert_eq!(&wav[..4], b"RIFF"); + assert_eq!(u32::from_le_bytes(wav[4..8].try_into().unwrap()) as usize, wav.len() - 8); + assert_eq!(&wav[8..16], b"WAVEfmt "); + let field = |at: usize, n: usize| wav[at..at + n].iter().rev().fold(0u32, |v, b| v << 8 | u32::from(*b)); + // PCM, 2 channels, 48000 Hz, 192000 bytes a second, 4 a frame, 16 bits. + assert_eq!([field(20, 2), field(22, 2), field(24, 4), field(28, 4), field(32, 2), field(34, 2)], [1, 2, 48000, 192000, 4, 16]); + assert_eq!((&wav[36..40], field(40, 4)), (b"data".as_slice(), 20)); + assert_eq!(&wav[44..], pcm.as_slice(), "the frames, without the bank's padding"); +} + +#[test] +fn compressed_or_odd_banks_are_not_made_into_wavs() { + let vorbis = fsb5_bank(15, &[(8, 1, 4410, &[7; 40])]); + let bank = unity_audio::bank(&vorbis).unwrap(); + assert_eq!(unity_audio::codec_name(bank.codec), "Vorbis"); + assert_eq!(unity_audio::wav(&bank, &bank.samples[0], &vorbis), None); + // A channel count past stereo is in a chunk; two samples each get their own data. + let surround = fsb5_bank(2, &[(8, 6, 2, &[1; 24]), (5, 1, 3, &[2; 6])]); + let bank = unity_audio::bank(&surround).unwrap(); + assert_eq!(bank.samples.iter().map(|s| (s.frequency, s.channels, s.frames, s.data.1)).collect::>(), [(44100, 6, 2, 32), (22050, 1, 3, 32)]); + assert_eq!(unity_audio::wav(&bank, &bank.samples[1], &surround).unwrap()[44..], [2; 6]); + // Only 16-bit PCM in mono or stereo: a surround or 24-bit sample stays in its bank. + assert_eq!(unity_audio::wav(&bank, &bank.samples[0], &surround), None); + let pcm24 = fsb5_bank(3, &[(8, 1, 2, &[0; 6])]); + let bank = unity_audio::bank(&pcm24).unwrap(); + assert_eq!(unity_audio::wav(&bank, &bank.samples[0], &pcm24), None); + // A frequency chunk sets the rate the index doesn't have. + let mut odd_rate = fsb5_bank(2, &[(0, 1, 2, &[0; 4])]); + let raw = u64::from_le_bytes(odd_rate[0x3c..0x44].try_into().unwrap()) | 1; + odd_rate[0x3c..0x44].copy_from_slice(&raw.to_le_bytes()); + let mut chunk = (4u32 << 1 | 2 << 25).to_le_bytes().to_vec(); + chunk.extend_from_slice(&96_000u32.to_le_bytes()); + odd_rate.splice(0x44..0x44, chunk); + odd_rate[12..16].copy_from_slice(&16u32.to_le_bytes()); // the sample headers grew by 8 bytes + let bank = unity_audio::bank(&odd_rate).unwrap(); + assert_eq!(bank.samples[0].frequency, 96_000); + assert_eq!(unity_audio::wav(&bank, &bank.samples[0], &odd_rate).unwrap()[24..28], 96_000u32.to_le_bytes()); + // More frames than the sample holds: no WAV rather than one cut short. + let short = fsb5_bank(2, &[(8, 1, 100, &[0; 8])]); + let bank = unity_audio::bank(&short).unwrap(); + assert_eq!(unity_audio::wav(&bank, &bank.samples[0], &short), None); +} + +#[test] +fn broken_banks_are_refused() { + let good = fsb5_bank(2, &[(8, 1, 4, &[0; 8])]); + let mut cases = vec![good[..good.len() - 1].to_vec(), good[..20].to_vec(), b"FSB4".to_vec()]; + let mut version = good.clone(); + version[4] = 7; + cases.push(version); + let mut count = good.clone(); + count[8..12].copy_from_slice(&1_000_000u32.to_le_bytes()); + cases.push(count); + let mut past = good.clone(); + // The sample's data offset (in 16-byte units) past the 32 bytes of data. + let raw = u64::from_le_bytes(past[0x3c..0x44].try_into().unwrap()) | 3 << 6; + past[0x3c..0x44].copy_from_slice(&raw.to_le_bytes()); + cases.push(past); + // Bit 6, which readings of the format disagree on. + let mut bit6 = good.clone(); + let raw = u64::from_le_bytes(bit6[0x3c..0x44].try_into().unwrap()) | 1 << 6; + bit6[0x3c..0x44].copy_from_slice(&raw.to_le_bytes()); + cases.push(bit6); + // More samples than a bank may hold, even when their headers fit. + let many = unity_audio::MAX_SAMPLES as u32 + 1; + let mut crowded = b"FSB5".to_vec(); + for x in [1, many, many * 8, 0, 0, 2] { + crowded.extend_from_slice(&x.to_le_bytes()); + } + crowded.resize(0x3c + many as usize * 8, 0); + cases.push(crowded); + for bytes in cases { + assert!(unity_audio::bank(&bytes).is_err(), "{bytes:?}"); + } +} diff --git a/crates/testkit/src/games.rs b/crates/testkit/src/games.rs index f682a8e35..ebbb56bd0 100644 --- a/crates/testkit/src/games.rs +++ b/crates/testkit/src/games.rs @@ -408,6 +408,64 @@ pub fn unity_texture2d( out } +/// A Unity AudioClip object's bytes (little-endian) as `unity_version` (5.0 or later) writes it: +/// `channels` at `frequency` Hz, `seconds` long, in compression format `compression`, stored at +/// `(path, offset, size)`. +pub fn unity_audioclip(unity_version: &str, name: &str, channels: i32, frequency: i32, seconds: f32, compression: i32, stream: (&str, u64, u64)) -> Vec { + let major = unity_version.split('.').next().and_then(|p| p.parse::().ok()).unwrap_or(0); + let mut out = Vec::new(); + let string = |out: &mut Vec, s: &str| { + out.extend_from_slice(&(s.len() as i32).to_le_bytes()); + out.extend_from_slice(s.as_bytes()); + out.resize(out.len().div_ceil(4) * 4, 0); + }; + string(&mut out, name); + for x in [1, channels, frequency, 16] { + out.extend_from_slice(&x.to_le_bytes()); // load type, channels, frequency, bits per sample + } + out.extend_from_slice(&seconds.to_le_bytes()); + out.push(0); // tracker format + if major >= 2017 { + out.push(0); // ambisonic + } + out.resize(out.len().div_ceil(4) * 4, 0); + out.extend_from_slice(&0i32.to_le_bytes()); // subsound index + out.extend_from_slice(&[1, 0, 0]); // preload, load in background, legacy 3D + out.resize(out.len().div_ceil(4) * 4, 0); + string(&mut out, stream.0); + out.extend_from_slice(&stream.1.to_le_bytes()); + out.extend_from_slice(&stream.2.to_le_bytes()); + out.extend_from_slice(&compression.to_le_bytes()); + out +} + +/// An FSB5 bank (version 1) in `codec` holding one sample per `(rate index, channels, frames, +/// data)`: mono or stereo in the header, other counts in a channels chunk. Each sample's data is +/// padded to 32 bytes, as FMOD writes it. +pub fn fsb5_bank(codec: u32, samples: &[(u64, u8, u64, &[u8])]) -> Vec { + let mut headers = Vec::new(); + let mut data = Vec::new(); + for (rate, channels, frames, bytes) in samples { + let chunk = *channels > 2; + let raw = u64::from(chunk) | rate << 1 | u64::from(*channels == 2) << 5 | (data.len() as u64 / 16) << 6 | frames << 34; + headers.extend_from_slice(&raw.to_le_bytes()); + if chunk { + headers.extend_from_slice(&(1u32 << 1 | 1 << 25).to_le_bytes()); // one byte: the channel count + headers.push(*channels); + } + data.extend_from_slice(bytes); + data.resize(data.len().div_ceil(32) * 32, 0); + } + let mut out = b"FSB5".to_vec(); + for x in [1, samples.len() as u32, headers.len() as u32, 0, data.len() as u32, codec] { + out.extend_from_slice(&x.to_le_bytes()); + } + out.extend_from_slice(&[0; 32]); + out.extend_from_slice(&headers); + out.extend_from_slice(&data); + out +} + /// A cooked Unreal 4.27 texture package (`.uasset`, `.uexp`) named `name` in `pixel_format`: one /// Texture2D export with tagged properties, its first mip optionally in the `.ubulk` /// (`(width, height, length)` at offset 0), then a `width`×`height` mip with `pixels` inline. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index c4ad88e37..be587fc90 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1719,7 +1719,8 @@ Owner: open · Status: todo ### R3.9 Game assets out Owner: open · Status: in progress -- [ ] Unity: sounds out (the stored stream, usually FSB5; PCM ones as WAV) +- [x] Unity: sounds out (the stored stream, usually FSB5; PCM ones as WAV) + — claimed: NicolasBohn, branch feature/r3.9-unity-sounds - [ ] Unity: crunched textures (DXT1Crunched, DXT5Crunched; two of the games checked use them) - [x] Unity: decode R16 and RG16 texture pixels through the shared bounded PNG export path. — claimed: Afloat16, branch feature/r3.9-unity-integer-textures-20261109 diff --git a/docs/STATUS.md b/docs/STATUS.md index 40d8b6912..79c43f857 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -128,6 +128,7 @@ coverage and secrets passed. The companion CLI was built with locked dependencie | Unity EAC textures | EAC_R, EAC_R_SIGNED, EAC_RG and EAC_RG_SIGNED decode their 11-bit channel values before display quantization. Single channels appear in grey; dual channels use red/green with blue zero. Signed values map -1..1 to 0..255. | Seven synthetic regression groups cover specification-derived pixel values, all modifier tables and selectors, signed bases, clamping, channel order, clipped edges, mip/output limits and complete Texture2D objects. All seven fail on the original reader. | | Unity ETC1 textures | ETC_RGB4 decodes individual and differential blocks with both subblock orientations, all modifier tables and Unity row order. Invalid differential base colours are rejected; clipped edges and output budgets use the shared pixel pipeline. | Seven original synthetic cases cover selector planes, all tables, signed deltas, colour clipping, edge blocks, first-mip limits, malformed blocks and a serialized Texture2D object. | | Unity floating-point textures | The PNG exporter reads RHalf, RGHalf, RGBAHalf, RFloat, RGFloat and RGBAFloat. RGB is converted from linear light to 8-bit sRGB, alpha stays linear, and scalar textures are shown in grey. | Synthetic half- and full-precision textures cover every channel layout, short mips, row order, non-finite values and clipping. | +| Unity sounds | `game_unity_asset_export` saves an AudioClip (Unity 5 and later) from the `.resource` file it's stored in, beside the serialized file or inside the bundle. An FMOD bank (FSB5) holding one 16-bit PCM sample in mono or stereo becomes a WAV; other codecs (Vorbis, ADPCM…), other PCM, more channels or samples, and banks this doesn't read (another version, a sample header with bit 6 set, which readings of the format disagree on) are saved as the bank, with a `stored_as_is` limitation. The output gets `.wav` or `.fsb` to match. A clip whose fields don't end where its object does is refused as a layout this doesn't know; banks of over 65,536 samples and sounds over 256 MiB are refused. | Synthetic clips for Unity 5.6 to 6000.0, banks with stereo, a channel and a frequency chunk, two samples, 24-bit PCM, short data and broken headers, and the export from an .assets file and from a bundle. On three installed games every AudioClip in every serialized file was saved: Unity 5.6.7 (302: 100 WAV, 202 Vorbis banks), 2019.4.19 (99 Vorbis banks) and 2022.3.43 (368: 7 WAV, 361 Vorbis banks); each WAV's length agrees with its clip's within 0.1 ms in ffprobe, and each bank is whole. Not run on a bundle from a real game, an FSB5 version 0 bank or a big-endian file. | | Check Unity bundle blocks against their declared output lengths | Unity bundle pieces must match their declared decoded lengths; LZMA must finish within the supplied compressed piece. | Synthetic byte fixtures in `unity_bundle_decompressed_length` integration regressions. Cover stored pieces that are short or long, LZ4 and LZ4HC size mismatches, LZMA with or without end markers, empty and short zero streams, bounded dictionary/output growth, oversized dictionary properties, and truncated or trailing compressed bytes. | | Standalone LZMA budgets | Check declared output before decoding and bound the internal dictionary to the caller's output budget or the decoder's 4 KiB minimum window. | Public standalone-reader regressions cover large declared sizes, oversized dictionary properties, exact/zero limits and a damaged stream that exceeds a small budget before its tail. Verified source `5da8880d`: [formats tests, fmt and clippy](https://github.com/Afloat16/claude-mem/actions/runs/42636776430/job/129226892150); [layers, locks, secrets, wasm and unchanged Cargo.lock](https://github.com/Afloat16/claude-mem/actions/runs/42640688213/job/129240669663); [unchanged-code regression failures](https://github.com/Afloat16/claude-mem/actions/runs/42636776430/job/129226895582). | | Unity LZ4 match expansion | Long overlapping LZ4 matches copy the repeating run in growing blocks. | Exact output against liblz4 1.9.4 fixtures and release-mode timings on three four-MiB inputs. |