Skip to main content

rpfm_lib/files/sound_bank/
mod.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! Wwise SoundBank (`.bnk`) file support.
12//!
13//! This module handles Audiokinetic Wwise SoundBank files used in modern Total War games.
14//! SoundBanks contain audio event definitions, hierarchies, and metadata that control
15//! how sounds are played in the game.
16//!
17//! For more info about the Wwise format, check <https://github.com/bnnm/wwiser/>.
18//!
19//! # Supported Sections
20//!
21//! Currently only partial support is implemented:
22//! - `BKHD` (Bank Header) - Contains version and bank metadata
23//! - `HIRC` (Hierarchy) - Contains audio object definitions and event actions
24//!
25//! Other sections like `DATA`, `DIDX`, `STID`, etc. are recognized but not yet supported.
26
27use getset::*;
28use serde_derive::{Serialize, Deserialize};
29
30use crate::binary::{ReadBytes, WriteBytes};
31use crate::error::{Result, RLibError};
32use crate::files::{Decodeable, EncodeableExtraData, Encodeable};
33use crate::utils::check_size_mismatch;
34
35use self::sections::bkhd::Bkhd;
36use self::sections::hirc::Hirc;
37
38use super::DecodeableExtraData;
39
40pub use crate::files::detection::sound_bank::EXTENSION;
41
42// Hash type identifiers for FNV hashing (used internally by Wwise).
43const FNV_NO: &str = "none";        // Special value, no hashname allowed
44const FNV_BNK: &str = "bank";
45const FNV_LNG: &str = "language";
46const FNV_EVT: &str = "event";
47const FNV_BUS: &str = "bus";
48const FNV_SFX: &str = "sfx";
49const FNV_TRG: &str = "trigger";
50const FNV_GME: &str = "rtpc/game-variable";
51const FNV_VAR: &str = "variable";   // Switches/states names
52const FNV_VAL: &str = "value";      // Switches/states values
53const FNV_UNK: &str = "???";
54
55const FNV_ORDER: [&str; 10] = [
56  FNV_BNK, FNV_LNG, FNV_EVT, FNV_BUS, FNV_SFX, FNV_TRG, FNV_GME, FNV_VAR, FNV_VAL, FNV_UNK
57];
58
59const FNV_ORDER_JOIN: [&str; 3] = [
60  FNV_BNK, FNV_LNG, FNV_BUS
61];
62
63// Section signature constants (4-byte ASCII identifiers).
64const SIGNATURE_AKBK: &str = "AKBK"; // Audiokinetic Bank (container format)
65const SIGNATURE_BKHD: &str = "BKHD"; // Bank Header
66const SIGNATURE_HIRC: &str = "HIRC"; // Hierarchy
67const SIGNATURE_DATA: &str = "DATA"; // Embedded audio data
68const SIGNATURE_FXPR: &str = "FXPR"; // FX Parameters
69const SIGNATURE_ENVS: &str = "ENVS"; // Environment Settings
70const SIGNATURE_STID: &str = "STID"; // String Mappings
71const SIGNATURE_STMG: &str = "STMG"; // Global Settings
72const SIGNATURE_DIDX: &str = "DIDX"; // Media Index
73const SIGNATURE_PLAT: &str = "PLAT"; // Custom Platform
74const SIGNATURE_INIT: &str = "INIT"; // Plugin
75
76mod common;
77mod sections;
78
79#[cfg(test)] mod test_soundbank;
80
81//---------------------------------------------------------------------------//
82//                              Enum & Structs
83//---------------------------------------------------------------------------//
84
85/// A decoded Wwise SoundBank file.
86///
87/// SoundBanks are container files that hold audio events, hierarchies, and optionally
88/// embedded audio data. They are identified by their `.bnk` extension.
89///
90/// The file consists of multiple sections, each with a 4-byte signature and size prefix.
91/// The first section must always be `BKHD` (Bank Header).
92#[derive(Default, PartialEq, Clone, Debug, Getters, MutGetters, Setters, Serialize, Deserialize)]
93#[getset(get = "pub", get_mut = "pub", set = "pub")]
94pub struct SoundBank {
95    /// Sections contained in this SoundBank.
96    sections: Vec<Section>,
97}
98
99/// A section within a SoundBank file.
100///
101/// Each section type contains different data:
102/// - `BKHD`: Bank header with version info (always first)
103/// - `HIRC`: Hierarchy of audio objects and events
104#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
105pub enum Section {
106    /// Bank Header section containing version and metadata.
107    BKHD(Bkhd),
108    /// Hierarchy section containing audio object definitions.
109    HIRC(Hirc),
110}
111
112//---------------------------------------------------------------------------//
113//                        Implementation of SoundBank
114//---------------------------------------------------------------------------//
115
116impl Decodeable for SoundBank {
117
118    fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
119        let mut decoded = Self::default();
120        let data_len = data.len()?;
121
122        while let Ok(section_signature) = data.read_string_u8(4) {
123            let section_size = data.read_u32()? as u64;
124            //let section_start = data.stream_position()?;
125            //let section_end = section_start + section_size;
126
127            dbg!(&section_signature);
128            dbg!(&section_size);
129            decoded.sections.push(match &*section_signature {
130                SIGNATURE_AKBK => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_AKBK.to_string())),
131
132                // First node is always a BKHD (BanK HeaDer?).
133                SIGNATURE_BKHD => Section::BKHD(Bkhd::read(data, section_size as usize)?),
134                SIGNATURE_HIRC => {
135                    let header = match decoded.sections.first() {
136                        Some(Section::BKHD(section)) => section,
137                        _ => return Err(RLibError::SoundBankBKHDNotFound),
138                    };
139
140                    Section::HIRC(Hirc::read(data, *header.version())?)
141                },
142                SIGNATURE_DATA => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_DATA.to_string())),
143                SIGNATURE_FXPR => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_FXPR.to_string())),
144                SIGNATURE_ENVS => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_ENVS.to_string())),
145                SIGNATURE_STID => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_STID.to_string())),
146                SIGNATURE_STMG => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_STMG.to_string())),
147                SIGNATURE_DIDX => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_DIDX.to_string())),
148                SIGNATURE_PLAT => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_PLAT.to_string())),
149                SIGNATURE_INIT => return Err(RLibError::SoundBankUnsupportedSectionFound(SIGNATURE_INIT.to_string())),
150                _ => return Err(RLibError::SoundBankUnsupportedSectionFound(section_signature)),
151            });
152        }
153
154        check_size_mismatch(data.stream_position()? as usize, data_len as usize)?;
155
156        Ok(decoded)
157    }
158}
159
160impl Encodeable for SoundBank {
161
162    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
163        let header = match self.sections.first() {
164            Some(Section::BKHD(section)) => section,
165            _ => return Err(RLibError::SoundBankBKHDNotFound),
166        };
167
168        for section in self.sections() {
169            match section {
170                Section::BKHD(data) => data.write(buffer)?,
171                Section::HIRC(data) => data.write(buffer, *header.version())?,
172            }
173        }
174
175        Ok(())
176    }
177}