Skip to main content

unbanished_formats/types/
sound.rs

1//! Sound buffers: the wave format and the xWMA data of a sound.
2
3use super::*;
4
5/// `WAVEFORMATEX` header carried by every sound. All shipped audio is xWMA (`tag == 0x161`).
6#[derive(Debug, Clone, Copy)]
7pub struct WaveFormat {
8    /// The format tag: `0x161`, WMA v2, for every sound of the game.
9    pub tag: u16,
10    /// The number of channels.
11    pub channels: u16,
12    /// The sample rate.
13    pub sample_rate: u32,
14    /// The average data rate, in bytes per second.
15    pub avg_bytes_per_sec: u32,
16    /// The packet size in bytes.
17    pub block_align: u16,
18    /// The bits per sample.
19    pub bits_per_sample: u16,
20}
21
22/// A sound: its format, its loop flag, its length, and its data in xWMA (or the entry of its
23/// stream).
24#[derive(Debug, Clone)]
25pub struct SoundBuffer {
26    /// Whether the sound loops.
27    pub looping: bool,
28    /// Streamed sounds keep their packets in a raw `.str` package entry named by `stream_entry`.
29    pub streamed: bool,
30    /// Original source file, e.g. `Audio\Animal\Chicken0.wav`.
31    pub source: String,
32    /// The package entry of a streamed sound's packets.
33    pub stream_entry: String,
34    /// The length in seconds.
35    pub length_seconds: f32,
36    /// The format header.
37    pub format: WaveFormat,
38    /// Raw `WAVEFORMATEX(TENSIBLE)` bytes (40).
39    pub format_bytes: Vec<u8>,
40    /// xWMA `dpds` table: cumulative decoded bytes per packet, u32 LE.
41    pub packet_table: Vec<u8>,
42    /// xWMA packets (empty when streamed).
43    pub data: Vec<u8>,
44}
45
46impl SoundBuffer {
47    /// The resource class name.
48    pub const CLASS: &'static str = "SoundBuffer";
49
50    /// `Audio::SoundBuffer::Serialize` + `PlatformSerialize`.
51    ///
52    /// Original: Runtime `0x1800e2cd0`, Runtime `0x1800e2e10`.
53    pub fn read(r: &mut Reader) -> Result<Self> {
54        r.block(|r, _| {
55            let looping = r.bool()?;
56            let streamed = r.bool()?;
57            let source = r.string()?;
58            let stream_entry = r.string()?;
59            let length_seconds = r.f32()?;
60            let data_len = r.count()?;
61            let table_len = r.count()?;
62            let packet_table = r.bytes(table_len)?.to_vec();
63            let format_bytes = r.bytes(0x28)?.to_vec();
64            let data = r.bytes(data_len)?.to_vec();
65            let u16_at = |o: usize| u16::from_le_bytes([format_bytes[o], format_bytes[o + 1]]);
66            let u32_at = |o: usize| u32::from_le_bytes(format_bytes[o..o + 4].try_into().unwrap());
67            let format = WaveFormat {
68                tag: u16_at(0),
69                channels: u16_at(2),
70                sample_rate: u32_at(4),
71                avg_bytes_per_sec: u32_at(8),
72                block_align: u16_at(12),
73                bits_per_sample: u16_at(14),
74            };
75            Ok(SoundBuffer {
76                looping,
77                streamed,
78                source,
79                stream_entry,
80                length_seconds,
81                format,
82                format_bytes,
83                packet_table,
84                data,
85            })
86        })
87    }
88
89    /// Wrap as a standard xWMA RIFF file (`RIFF/XWMA` with `fmt `, `dpds`, `data`), which FFmpeg
90    /// and XAudio2 tooling read. `stream` supplies the packets for streamed sounds.
91    pub fn to_xwma(&self, stream: Option<&[u8]>) -> Vec<u8> {
92        fn chunk(out: &mut Vec<u8>, tag: &[u8; 4], body: &[u8]) {
93            out.extend_from_slice(tag);
94            out.extend_from_slice(&(body.len() as u32).to_le_bytes());
95            out.extend_from_slice(body);
96            if body.len() % 2 == 1 {
97                out.push(0);
98            }
99        }
100        let data = stream.unwrap_or(&self.data);
101        let mut body = b"XWMA".to_vec();
102        chunk(&mut body, b"fmt ", &self.format_bytes[..18]);
103        chunk(&mut body, b"dpds", &self.packet_table);
104        chunk(&mut body, b"data", data);
105        let mut out = b"RIFF".to_vec();
106        out.extend_from_slice(&(body.len() as u32).to_le_bytes());
107        out.extend_from_slice(&body);
108        out
109    }
110}