Skip to main content

openblood/
cdaudio.rs

1//! Red Book CD audio: extracts music tracks from the user's own disc image (CUE/BIN)
2//! into TRACKnn.WAV files, which OpenBlood then plays as level music.
3
4use std::io::{self, Write};
5use std::path::{Path, PathBuf};
6
7const SECTOR: u64 = 2352;
8
9#[derive(Debug, Clone)]
10pub struct CueTrack {
11    pub number: u32,
12    pub audio: bool,
13    /// INDEX 00 (pregap start) and INDEX 01 (track start), in sectors.
14    pub index0: Option<u64>,
15    pub index1: u64,
16}
17
18fn msf(s: &str) -> Option<u64> {
19    let p: Vec<u64> = s.split(':').filter_map(|x| x.trim().parse().ok()).collect();
20    (p.len() == 3).then(|| (p[0] * 60 + p[1]) * 75 + p[2])
21}
22
23/// Parses a single-file CUE sheet. Returns the BIN path and the tracks.
24pub fn parse_cue(path: &Path) -> io::Result<(PathBuf, Vec<CueTrack>)> {
25    let text = std::fs::read_to_string(path)?;
26    let mut bin = None;
27    let mut tracks: Vec<CueTrack> = Vec::new();
28    for line in text.lines() {
29        let l = line.trim();
30        let up = l.to_ascii_uppercase();
31        if up.starts_with("FILE") {
32            let name = l.split('"').nth(1).unwrap_or("").to_string();
33            bin = Some(path.parent().unwrap_or(Path::new(".")).join(name));
34        } else if up.starts_with("TRACK") {
35            let mut it = l.split_whitespace().skip(1);
36            let number = it.next().and_then(|n| n.parse().ok()).unwrap_or(0);
37            let audio = it.next().is_some_and(|m| m.eq_ignore_ascii_case("AUDIO"));
38            tracks.push(CueTrack {
39                number,
40                audio,
41                index0: None,
42                index1: 0,
43            });
44        } else if up.starts_with("INDEX") {
45            let mut it = l.split_whitespace().skip(1);
46            let idx: u32 = it.next().and_then(|n| n.parse().ok()).unwrap_or(1);
47            let pos = it.next().and_then(msf).unwrap_or(0);
48            if let Some(t) = tracks.last_mut() {
49                if idx == 0 {
50                    t.index0 = Some(pos);
51                } else if idx == 1 {
52                    t.index1 = pos;
53                }
54            }
55        }
56    }
57    let bin = bin.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "CUE has no FILE line"))?;
58    Ok((bin, tracks))
59}
60
61/// Writes 16-bit stereo 44.1 kHz PCM bytes as a WAV file.
62pub fn write_wav(path: &Path, pcm: &[u8]) -> io::Result<()> {
63    let mut f = io::BufWriter::new(std::fs::File::create(path)?);
64    let data_len = pcm.len() as u32;
65    f.write_all(b"RIFF")?;
66    f.write_all(&(36 + data_len).to_le_bytes())?;
67    f.write_all(b"WAVEfmt ")?;
68    f.write_all(&16u32.to_le_bytes())?;
69    f.write_all(&1u16.to_le_bytes())?; // PCM
70    f.write_all(&2u16.to_le_bytes())?; // stereo
71    f.write_all(&44100u32.to_le_bytes())?;
72    f.write_all(&(44100u32 * 4).to_le_bytes())?;
73    f.write_all(&4u16.to_le_bytes())?;
74    f.write_all(&16u16.to_le_bytes())?;
75    f.write_all(b"data")?;
76    f.write_all(&data_len.to_le_bytes())?;
77    f.write_all(pcm)?;
78    Ok(())
79}
80
81pub fn extract(cue: &Path, out: &Path) -> io::Result<usize> {
82    use std::io::{Read, Seek, SeekFrom};
83    let (bin, tracks) = parse_cue(cue)?;
84    let total = std::fs::metadata(&bin)?.len() / SECTOR;
85    std::fs::create_dir_all(out)?;
86    let mut f = std::fs::File::open(&bin)?;
87    let mut n = 0;
88    for (i, t) in tracks.iter().enumerate() {
89        if !t.audio {
90            continue;
91        }
92        let end = tracks.get(i + 1).map_or(total, |nt| nt.index0.unwrap_or(nt.index1));
93        let len = (end.saturating_sub(t.index1) * SECTOR) as usize;
94        let mut pcm = vec![0u8; len];
95        f.seek(SeekFrom::Start(t.index1 * SECTOR))?;
96        f.read_exact(&mut pcm)?;
97        write_wav(&out.join(format!("TRACK{:02}.WAV", t.number)), &pcm)?;
98        n += 1;
99    }
100    Ok(n)
101}
102
103/// Loads a 16-bit stereo 44.1 kHz WAV as interleaved f32 samples.
104/// Streams the PCM data of a 16-bit WAV file in half-second chunks of interleaved samples,
105/// looping forever, from a background thread. Only a few chunks are buffered (the channel is
106/// bounded), so memory stays small and nothing large is allocated at level start. The thread
107/// exits when the receiver is dropped.
108pub fn stream_wav(path: &Path) -> Option<std::sync::mpsc::Receiver<Vec<i16>>> {
109    use std::io::{Read, Seek, SeekFrom};
110    let mut f = std::fs::File::open(path).ok()?;
111    let mut head = [0u8; 12];
112    f.read_exact(&mut head).ok()?;
113    if &head[0..4] != b"RIFF" || &head[8..12] != b"WAVE" {
114        return None;
115    }
116    // Find the data chunk.
117    let (start, len) = loop {
118        let mut ch = [0u8; 8];
119        f.read_exact(&mut ch).ok()?;
120        let len = u32::from_le_bytes(ch[4..8].try_into().ok()?) as u64;
121        if &ch[0..4] == b"data" {
122            break (f.stream_position().ok()?, len);
123        }
124        f.seek(SeekFrom::Current((len + (len & 1)) as i64)).ok()?;
125    };
126    if len < 4 {
127        return None;
128    }
129    let (tx, rx) = std::sync::mpsc::sync_channel::<Vec<i16>>(6);
130    std::thread::spawn(move || {
131        const CHUNK: usize = 44100 * 2 * 2 / 2; // half a second of 16-bit stereo, in bytes
132        let mut bytes = vec![0u8; CHUNK];
133        let mut left = len;
134        loop {
135            if left == 0 {
136                if f.seek(SeekFrom::Start(start)).is_err() {
137                    return;
138                }
139                left = len;
140            }
141            let n = (CHUNK as u64).min(left) as usize & !3;
142            if n == 0 || f.read_exact(&mut bytes[..n]).is_err() {
143                return;
144            }
145            left -= n as u64;
146            let samples: Vec<i16> = bytes[..n]
147                .as_chunks::<2>()
148                .0
149                .iter()
150                .map(|c| i16::from_le_bytes([c[0], c[1]]))
151                .collect();
152            if tx.send(samples).is_err() {
153                return; // music stopped or changed
154            }
155        }
156    });
157    Some(rx)
158}
159
160/// Reads the ISO 9660 filesystem of the disc's data track (raw 2352-byte sectors) and copies
161/// the files of `dir` (e.g. `MOVIE`, Blood's cutscenes) to `out`. Returns the names copied.
162pub fn extract_dir(cue: &Path, dir: &str, out: &Path) -> io::Result<Vec<String>> {
163    use std::io::{Read, Seek, SeekFrom};
164    let (bin, tracks) = parse_cue(cue)?;
165    let data = tracks
166        .iter()
167        .find(|t| !t.audio)
168        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no data track"))?;
169    let base = data.index1;
170    let mut f = std::fs::File::open(&bin)?;
171    // User data offset inside a raw sector: 16 for mode 1, 24 for mode 2 form 1.
172    let mut read_sector = |lba: u64| -> io::Result<Vec<u8>> {
173        let mut raw = vec![0u8; SECTOR as usize];
174        f.seek(SeekFrom::Start((base + lba) * SECTOR))?;
175        f.read_exact(&mut raw)?;
176        let off = if raw[15] == 2 { 24 } else { 16 };
177        Ok(raw[off..off + 2048].to_vec())
178    };
179    let pvd = read_sector(16)?;
180    if &pvd[1..6] != b"CD001" {
181        return Err(io::Error::new(io::ErrorKind::InvalidData, "no ISO 9660 filesystem"));
182    }
183    let le32 = |b: &[u8], o: usize| u32::from_le_bytes(b[o..o + 4].try_into().unwrap()) as u64;
184    // Directory records: (name, extent, size, is_dir).
185    let mut list = |lba: u64, size: u64| -> io::Result<Vec<(String, u64, u64, bool)>> {
186        let mut out = Vec::new();
187        for k in 0..size.div_ceil(2048) {
188            let sec = read_sector(lba + k)?;
189            let mut p = 0;
190            while p < 2048 && sec[p] != 0 {
191                let len = sec[p] as usize;
192                let nlen = sec[p + 32] as usize;
193                let name = String::from_utf8_lossy(&sec[p + 33..p + 33 + nlen]).to_string();
194                let name = name.split(';').next().unwrap_or("").to_string();
195                out.push((name, le32(&sec, p + 2), le32(&sec, p + 10), sec[p + 25] & 2 != 0));
196                p += len;
197            }
198        }
199        Ok(out)
200    };
201    let root = list(le32(&pvd, 156 + 2), le32(&pvd, 156 + 10))?;
202    let (_, lba, size, _) = root
203        .into_iter()
204        .find(|e| e.3 && e.0.eq_ignore_ascii_case(dir))
205        .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, format!("no {dir} folder on the disc")))?;
206    std::fs::create_dir_all(out)?;
207    let mut copied = Vec::new();
208    for (name, flba, fsize, is_dir) in list(lba, size)? {
209        // Only the videos and their soundtracks (not installer files or AVI duplicates).
210        let up = name.to_ascii_uppercase();
211        if is_dir || !(up.ends_with(".SMK") || up.ends_with(".WAV")) {
212            continue;
213        }
214        let mut bytes = Vec::with_capacity(fsize as usize);
215        for k in 0..fsize.div_ceil(2048) {
216            bytes.extend_from_slice(&read_sector(flba + k)?);
217        }
218        bytes.truncate(fsize as usize);
219        std::fs::write(out.join(&name), &bytes)?;
220        copied.push(name);
221    }
222    Ok(copied)
223}
224
225#[allow(dead_code)]
226pub fn load_wav(path: &Path) -> Option<Vec<f32>> {
227    let b = std::fs::read(path).ok()?;
228    if b.len() < 44 || &b[0..4] != b"RIFF" || &b[8..12] != b"WAVE" {
229        return None;
230    }
231    // Find the data chunk.
232    let mut p = 12;
233    while p + 8 <= b.len() {
234        let id = &b[p..p + 4];
235        let len = u32::from_le_bytes(b[p + 4..p + 8].try_into().ok()?) as usize;
236        if id == b"data" {
237            let data = &b[p + 8..(p + 8 + len).min(b.len())];
238            return Some(
239                data.as_chunks::<2>()
240                    .0
241                    .iter()
242                    .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32 / 32768.0)
243                    .collect(),
244            );
245        }
246        p += 8 + len + (len & 1);
247    }
248    None
249}
250
251#[cfg(test)]
252mod tests {
253    use super::*;
254
255    #[test]
256    fn cue_parsing() {
257        let dir = std::env::temp_dir().join(format!("ob_cue_{}", std::process::id()));
258        std::fs::create_dir_all(&dir).unwrap();
259        let cue = dir.join("d.cue");
260        std::fs::write(&cue, "FILE \"d.img\" BINARY\n TRACK 1 MODE2/2352\n  INDEX 1 00:00:00\n TRACK 2 AUDIO\n  INDEX 1 00:02:00\n TRACK 3 AUDIO\n  INDEX 0 00:03:00\n  INDEX 1 00:03:10\n").unwrap();
261        let (bin, t) = parse_cue(&cue).unwrap();
262        assert!(bin.ends_with("d.img"));
263        assert_eq!(t.len(), 3);
264        assert!(!t[0].audio && t[1].audio);
265        assert_eq!(t[1].index1, 150);
266        assert_eq!((t[2].index0, t[2].index1), (Some(225), 235));
267        // Synthetic image: 300 sectors.
268        std::fs::write(dir.join("d.img"), vec![1u8; 300 * 2352]).unwrap();
269        let out = dir.join("out");
270        assert_eq!(extract(&cue, &out).unwrap(), 2);
271        let w = load_wav(&out.join("TRACK02.WAV")).unwrap();
272        assert_eq!(w.len(), 75 * 2352 / 2);
273    }
274}