oxideav-mod 0.0.5

Amiga ProTracker / SoundTracker module (MOD) codec for oxideav
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! MOD codec decoder — ProTracker playback.
//!
//! Consumes the whole-file packet from the MOD container, parses the
//! header + patterns + sample bodies, and drives a `PlayerState` forward,
//! emitting PCM until the song ends.
//!
//! Two output modes are available:
//!
//! - [`ModDecoder`] (codec id [`crate::CODEC_ID_STR`] = `"mod"`) produces
//!   mixed stereo S16 interleaved PCM. One `AudioFrame` every
//!   `CHUNK_FRAMES` samples.
//! - [`ModPlanarDecoder`] (codec id [`crate::CODEC_ID_PLANAR_STR`] =
//!   `"mod_planar"`) produces one planar `AudioFrame` per tick, with one
//!   S16P plane per MOD tracker channel. Downstream consumers that want
//!   to mix / pan / analyse channels independently (DAWs, visualizers,
//!   per-instrument tooling) drive the decoder via this codec id.

use oxideav_core::{
    AudioFrame, CodecCapabilities, CodecId, CodecParameters, Error, Frame, Packet, Result,
    SampleFormat, TimeBase,
};
use oxideav_core::{CodecInfo, CodecRegistry, Decoder};

use crate::container::OUTPUT_SAMPLE_RATE;
use crate::header::parse_header;
use crate::player::{parse_patterns, PlayerState};
use crate::samples::extract_samples;

pub fn register(reg: &mut CodecRegistry) {
    let mixed_caps = CodecCapabilities::audio("mod_sw")
        .with_lossy(false)
        .with_lossless(true)
        .with_intra_only(false)
        .with_max_channels(32)
        .with_max_sample_rate(OUTPUT_SAMPLE_RATE);
    reg.register(
        CodecInfo::new(CodecId::new(crate::CODEC_ID_STR))
            .capabilities(mixed_caps)
            .decoder(make_mixed_decoder),
    );

    let planar_caps = CodecCapabilities::audio("mod_sw_planar")
        .with_lossy(false)
        .with_lossless(true)
        .with_intra_only(false)
        .with_max_channels(32)
        .with_max_sample_rate(OUTPUT_SAMPLE_RATE);
    reg.register(
        CodecInfo::new(CodecId::new(crate::CODEC_ID_PLANAR_STR))
            .capabilities(planar_caps)
            .decoder(make_planar_decoder),
    );

    // STM — parsing-only decoder. Emits a clear `unsupported` error on
    // `send_packet`; structural inspection (title, patterns, instruments)
    // is available through `oxideav_mod::stm::parse_header` etc.
    let stm_caps = CodecCapabilities::audio("stm_sw")
        .with_lossy(false)
        .with_lossless(true)
        .with_intra_only(false)
        .with_max_channels(4)
        .with_max_sample_rate(OUTPUT_SAMPLE_RATE);
    reg.register(
        CodecInfo::new(CodecId::new(crate::CODEC_ID_STM_STR))
            .capabilities(stm_caps)
            .decoder(make_stm_stub_decoder),
    );

    // XM — parsing-only decoder. Same rationale as STM: playback
    // requires a broader pitch/envelope model than the MOD mixer, so
    // the decoder validates the packet then returns an explicit
    // `unsupported` error. Callers use `oxideav_mod::xm::parse_header`
    // / `parse_patterns` / `parse_instruments` / `extract_sample_bodies`
    // directly on the packet payload.
    let xm_caps = CodecCapabilities::audio("xm_sw")
        .with_lossy(false)
        .with_lossless(true)
        .with_intra_only(false)
        .with_max_channels(32)
        .with_max_sample_rate(OUTPUT_SAMPLE_RATE);
    reg.register(
        CodecInfo::new(CodecId::new(crate::CODEC_ID_XM_STR))
            .capabilities(xm_caps)
            .decoder(make_xm_stub_decoder),
    );
}

fn make_mixed_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
    Ok(Box::new(ModDecoder {
        codec_id: CodecId::new(crate::CODEC_ID_STR),
        state: DecoderState::AwaitingPacket,
    }))
}

fn make_planar_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
    Ok(Box::new(ModPlanarDecoder {
        codec_id: CodecId::new(crate::CODEC_ID_PLANAR_STR),
        state: DecoderState::AwaitingPacket,
    }))
}

fn make_stm_stub_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
    Ok(Box::new(StmStubDecoder {
        codec_id: CodecId::new(crate::CODEC_ID_STM_STR),
    }))
}

fn make_xm_stub_decoder(_params: &CodecParameters) -> Result<Box<dyn Decoder>> {
    Ok(Box::new(XmStubDecoder {
        codec_id: CodecId::new(crate::CODEC_ID_XM_STR),
    }))
}

/// Stub XM decoder: like `StmStubDecoder`, validates the packet as an
/// XM file but returns `unsupported` from `send_packet`. XM playback
/// needs an envelope-capable mixer that supports linear + Amiga pitch
/// tables, per-instrument volume/pan envelopes, vibrato/fadeout, etc.
/// Until that lands, structural consumers use
/// `crate::xm::parse_header` / `parse_patterns` / `parse_instruments`
/// / `extract_sample_bodies` on the packet payload directly.
struct XmStubDecoder {
    codec_id: CodecId,
}

impl Decoder for XmStubDecoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn send_packet(&mut self, packet: &Packet) -> Result<()> {
        if !crate::xm::is_xm(&packet.data) {
            return Err(Error::invalid(
                "XM: packet does not start with the 'Extended Module: ' banner",
            ));
        }
        // Perform a structural sanity parse; surface parse errors as
        // `invalid` rather than `unsupported` so callers can distinguish
        // "malformed file" from "playback intentionally not wired".
        crate::xm::parse_header(&packet.data)?;
        Err(Error::unsupported(
            "XM playback is not yet wired through the MOD mixer; use \
             oxideav_mod::xm::parse_header() / parse_patterns() / \
             parse_instruments() / extract_sample_bodies() directly for \
             structural access",
        ))
    }

    fn receive_frame(&mut self) -> Result<Frame> {
        Err(Error::Eof)
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }

    fn reset(&mut self) -> Result<()> {
        Ok(())
    }
}

/// Stub STM decoder: exists so the codec id resolves cleanly, but returns
/// an explicit `unsupported` error on `send_packet` rather than silently
/// emitting zeros. STM uses C3-frequency-based sample pitching rather
/// than the Amiga period model the MOD mixer assumes, so driving the
/// existing `PlayerState` with STM data would produce nonsense — better
/// to fail loudly until the mixer abstraction is broadened. Callers that
/// want to inspect STM files structurally should use
/// [`crate::stm::parse_header`] / [`crate::stm::parse_patterns`] /
/// [`crate::stm::extract_samples`] directly off the packet payload.
struct StmStubDecoder {
    codec_id: CodecId,
}

impl Decoder for StmStubDecoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn send_packet(&mut self, packet: &Packet) -> Result<()> {
        // Light validation so `unsupported` is only returned for otherwise
        // well-formed STM files. If the blob is not recognisable as STM,
        // surface an `invalid` error instead.
        if !crate::stm::is_stm(&packet.data) {
            return Err(Error::invalid(
                "STM: packet does not carry a valid Scream Tracker v1 header",
            ));
        }
        Err(Error::unsupported(
            "STM playback is not yet wired through the MOD mixer; use \
             oxideav_mod::stm::parse_header() / parse_patterns() / extract_samples() \
             directly for structural access",
        ))
    }

    fn receive_frame(&mut self) -> Result<Frame> {
        Err(Error::Eof)
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }

    fn reset(&mut self) -> Result<()> {
        Ok(())
    }
}

struct ModDecoder {
    codec_id: CodecId,
    state: DecoderState,
}

enum DecoderState {
    /// Haven't seen the file yet.
    AwaitingPacket,
    /// File parsed; the player is driving the mixer.
    Playing {
        player: Box<PlayerState>,
        emit_pts: i64,
    },
    /// All samples produced.
    Done,
}

const CHUNK_FRAMES: u32 = 1024;

impl Decoder for ModDecoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn send_packet(&mut self, packet: &Packet) -> Result<()> {
        // The MOD "container" delivers the whole file in one packet.
        if !matches!(self.state, DecoderState::AwaitingPacket) {
            return Err(Error::other(
                "MOD decoder received a second packet; only one is expected per song",
            ));
        }
        let header = parse_header(&packet.data)?;
        let samples = extract_samples(&header, &packet.data);
        let patterns = parse_patterns(&header, &packet.data);
        let player = PlayerState::new(&header, samples, patterns, OUTPUT_SAMPLE_RATE);
        self.state = DecoderState::Playing {
            player: Box::new(player),
            emit_pts: 0,
        };
        Ok(())
    }

    fn receive_frame(&mut self) -> Result<Frame> {
        match &mut self.state {
            DecoderState::AwaitingPacket => Err(Error::NeedMore),
            DecoderState::Done => Err(Error::Eof),
            DecoderState::Playing { player, emit_pts } => {
                // Allocate stereo interleaved buffer.
                let mut pcm = vec![0i16; CHUNK_FRAMES as usize * 2];
                let produced = player.render(&mut pcm);
                if produced == 0 {
                    self.state = DecoderState::Done;
                    return Err(Error::Eof);
                }
                // Truncate to what we actually produced.
                pcm.truncate(produced * 2);

                // Convert to little-endian S16 byte buffer.
                let mut bytes = Vec::with_capacity(pcm.len() * 2);
                for s in &pcm {
                    bytes.extend_from_slice(&s.to_le_bytes());
                }

                let pts = *emit_pts;
                *emit_pts += produced as i64;
                Ok(Frame::Audio(AudioFrame {
                    format: SampleFormat::S16,
                    channels: 2,
                    sample_rate: OUTPUT_SAMPLE_RATE,
                    samples: produced as u32,
                    pts: Some(pts),
                    time_base: TimeBase::new(1, OUTPUT_SAMPLE_RATE as i64),
                    data: vec![bytes],
                }))
            }
        }
    }

    fn flush(&mut self) -> Result<()> {
        if let DecoderState::Playing { .. } = self.state {
            // Draining is implicit — `receive_frame` will return Eof once
            // the player reports no more samples.
        }
        Ok(())
    }

    fn reset(&mut self) -> Result<()> {
        // The entire PlayerState (pattern-order cursor, per-channel mixer
        // state with sample position, volume/period history, arpeggio /
        // vibrato phases, BPM + tick counter) is dropped. The MOD
        // container delivers the whole file in one packet, so after a
        // reset we go back to `AwaitingPacket` and the container is
        // expected to re-send the file from the top of the song.
        self.state = DecoderState::AwaitingPacket;
        Ok(())
    }
}

/// Planar per-channel decoder. Emits one `AudioFrame` per render chunk,
/// with `AudioFrame.channels` equal to the MOD tracker channel count and
/// `AudioFrame.data` holding one S16P plane per channel (post-volume,
/// pre-pan, pre-mix).
struct ModPlanarDecoder {
    codec_id: CodecId,
    state: DecoderState,
}

impl Decoder for ModPlanarDecoder {
    fn codec_id(&self) -> &CodecId {
        &self.codec_id
    }

    fn send_packet(&mut self, packet: &Packet) -> Result<()> {
        if !matches!(self.state, DecoderState::AwaitingPacket) {
            return Err(Error::other(
                "MOD decoder received a second packet; only one is expected per song",
            ));
        }
        let header = parse_header(&packet.data)?;
        let samples = extract_samples(&header, &packet.data);
        let patterns = parse_patterns(&header, &packet.data);
        let player = PlayerState::new(&header, samples, patterns, OUTPUT_SAMPLE_RATE);
        self.state = DecoderState::Playing {
            player: Box::new(player),
            emit_pts: 0,
        };
        Ok(())
    }

    fn receive_frame(&mut self) -> Result<Frame> {
        match &mut self.state {
            DecoderState::AwaitingPacket => Err(Error::NeedMore),
            DecoderState::Done => Err(Error::Eof),
            DecoderState::Playing { player, emit_pts } => {
                let n_ch = player.channels.len();
                let n_frames = CHUNK_FRAMES as usize;

                // One i16 buffer per MOD channel, pre-sized to the chunk.
                let mut bufs: Vec<Vec<i16>> = (0..n_ch).map(|_| vec![0i16; n_frames]).collect();
                let produced = {
                    let mut views: Vec<&mut [i16]> =
                        bufs.iter_mut().map(|b| b.as_mut_slice()).collect();
                    player.render_per_channel(&mut views, n_frames)
                };
                if produced == 0 {
                    self.state = DecoderState::Done;
                    return Err(Error::Eof);
                }

                // Truncate each plane and convert to little-endian bytes.
                let mut planes: Vec<Vec<u8>> = Vec::with_capacity(n_ch);
                for buf in &bufs {
                    let mut bytes = Vec::with_capacity(produced * 2);
                    for &s in &buf[..produced] {
                        bytes.extend_from_slice(&s.to_le_bytes());
                    }
                    planes.push(bytes);
                }

                let pts = *emit_pts;
                *emit_pts += produced as i64;
                Ok(Frame::Audio(AudioFrame {
                    format: SampleFormat::S16P,
                    channels: n_ch as u16,
                    sample_rate: OUTPUT_SAMPLE_RATE,
                    samples: produced as u32,
                    pts: Some(pts),
                    time_base: TimeBase::new(1, OUTPUT_SAMPLE_RATE as i64),
                    data: planes,
                }))
            }
        }
    }

    fn flush(&mut self) -> Result<()> {
        Ok(())
    }

    fn reset(&mut self) -> Result<()> {
        self.state = DecoderState::AwaitingPacket;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::player::tests::synth_square_mod;
    use oxideav_core::TimeBase;

    #[test]
    fn decoder_emits_nonsilent_pcm() {
        let bytes = synth_square_mod();
        let params = CodecParameters::audio(CodecId::new(crate::CODEC_ID_STR));
        let mut dec = make_mixed_decoder(&params).unwrap();
        let pkt = Packet::new(0, TimeBase::new(1, OUTPUT_SAMPLE_RATE as i64), bytes);
        dec.send_packet(&pkt).unwrap();

        let mut total_samples = 0u64;
        let mut total_nonzero = 0u64;
        loop {
            match dec.receive_frame() {
                Ok(Frame::Audio(a)) => {
                    assert_eq!(a.channels, 2);
                    assert_eq!(a.sample_rate, OUTPUT_SAMPLE_RATE);
                    assert_eq!(a.format, SampleFormat::S16);
                    total_samples += a.samples as u64;
                    // Count non-zero bytes in the PCM plane.
                    let plane = &a.data[0];
                    for chunk in plane.chunks_exact(2) {
                        let s = i16::from_le_bytes([chunk[0], chunk[1]]);
                        if s != 0 {
                            total_nonzero += 1;
                        }
                    }
                }
                Ok(_) => unreachable!("MOD emits audio only"),
                Err(Error::Eof) => break,
                Err(e) => panic!("unexpected decode error: {e:?}"),
            }
        }
        assert!(
            total_samples > 1000,
            "expected substantial sample output, got {total_samples}"
        );
        assert!(
            total_nonzero > 100,
            "expected non-silent PCM, got {total_nonzero} non-zero samples"
        );
    }

    #[test]
    fn planar_decoder_emits_one_plane_per_channel() {
        let bytes = synth_square_mod();
        let params = CodecParameters::audio(CodecId::new(crate::CODEC_ID_PLANAR_STR));
        let mut dec = make_planar_decoder(&params).unwrap();
        let pkt = Packet::new(0, TimeBase::new(1, OUTPUT_SAMPLE_RATE as i64), bytes);
        dec.send_packet(&pkt).unwrap();

        let mut got_frame = false;
        let mut ch0_nonzero = 0u64;
        let mut other_nonzero = 0u64;
        loop {
            match dec.receive_frame() {
                Ok(Frame::Audio(a)) => {
                    got_frame = true;
                    // synth_square_mod uses the 4-channel "M.K." layout.
                    assert_eq!(a.channels, 4);
                    assert_eq!(a.format, SampleFormat::S16P);
                    assert_eq!(a.sample_rate, OUTPUT_SAMPLE_RATE);
                    assert_eq!(a.data.len(), 4, "one plane per MOD channel");
                    let expected_plane_len = a.samples as usize * 2;
                    for plane in &a.data {
                        assert_eq!(plane.len(), expected_plane_len);
                    }
                    for (idx, plane) in a.data.iter().enumerate() {
                        for chunk in plane.chunks_exact(2) {
                            let s = i16::from_le_bytes([chunk[0], chunk[1]]);
                            if s != 0 {
                                if idx == 0 {
                                    ch0_nonzero += 1;
                                } else {
                                    other_nonzero += 1;
                                }
                            }
                        }
                    }
                }
                Ok(_) => unreachable!("MOD emits audio only"),
                Err(Error::Eof) => break,
                Err(e) => panic!("unexpected decode error: {e:?}"),
            }
        }
        assert!(got_frame, "planar decoder produced no frames");
        // synth_square_mod triggers notes only on channel 0; other
        // channels must be pure silence.
        assert!(
            ch0_nonzero > 100,
            "expected channel-0 signal, got {ch0_nonzero} non-zero samples"
        );
        assert_eq!(
            other_nonzero, 0,
            "expected silence on channels 1..=3 (got {other_nonzero} non-zero samples)"
        );
    }
}