unbanished_formats/types/
sound.rs1use super::*;
4
5#[derive(Debug, Clone, Copy)]
7pub struct WaveFormat {
8 pub tag: u16,
10 pub channels: u16,
12 pub sample_rate: u32,
14 pub avg_bytes_per_sec: u32,
16 pub block_align: u16,
18 pub bits_per_sample: u16,
20}
21
22#[derive(Debug, Clone)]
25pub struct SoundBuffer {
26 pub looping: bool,
28 pub streamed: bool,
30 pub source: String,
32 pub stream_entry: String,
34 pub length_seconds: f32,
36 pub format: WaveFormat,
38 pub format_bytes: Vec<u8>,
40 pub packet_table: Vec<u8>,
42 pub data: Vec<u8>,
44}
45
46impl SoundBuffer {
47 pub const CLASS: &'static str = "SoundBuffer";
49
50 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 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}