ptcow 0.6.0

Library for editing and playback of PxTone (.ptcop) music
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
use crate::{
    ReadResult, SampleRate, SamplesPerTick, Timing, UnitIdx,
    delay::Delay,
    event::EveList,
    master::Master,
    noise_builder::NoiseTable,
    overdrive::Overdrive,
    result::WriteResult,
    timing::SampleT,
    unit::{Unit, VoiceIdx},
    voice::Voice,
};

mod io;
use arrayvec::ArrayVec;
pub use io::Tag;
pub mod moo;

const MAX_UNITS: u16 = 50;
const MAX_TUNE_VOICE_NAME: u32 = 16;
pub const MAX_TUNE_UNIT_NAME: usize = 16;

/// Song name and comment
#[derive(Default)]
pub struct Text {
    /// Name of the song
    pub name: String,
    /// Comment (short description) for the song
    pub comment: String,
}

/// PxTone format version
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
pub enum FmtVer {
    /// Version 1
    V1,
    /// Version 2
    V2,
    /// Version 3
    V3,
    /// Version 4
    V4,
    /// Version 5
    V5,
}

/// Kind of PxTone format we are dealing with
#[derive(Clone, Copy, Debug)]
pub enum FmtKind {
    /// PxTone collage (.ptcop)
    Collage,
    /// PxTone tune (.pttune)
    Tune,
}

/// Information about what format the song is
#[derive(Clone, Copy, Debug)]
pub struct FmtInfo {
    /// PxTone format version
    pub ver: FmtVer,
    /// Are we a project or a tune?
    pub kind: FmtKind,
    pub(crate) exe_ver: u16,
    pub(crate) dummy: u16,
}

impl Default for FmtInfo {
    fn default() -> Self {
        Self {
            ver: FmtVer::V5,
            kind: FmtKind::Collage,
            exe_ver: 0,
            dummy: 0,
        }
    }
}

/// A PxTone song
#[derive(Default)]
pub struct Song {
    /// The name and the comment of the song
    pub text: Text,
    /// Contains timing related data and the loop points of the song
    pub master: Master,
    /// The events of the song
    pub events: EveList,
    /// Information about the pxtone file format this song has
    pub fmt: FmtInfo,
}

impl Song {
    /// Recalculate the information about the length of the song
    ///
    /// Should be called when you changed the length of the song, or changed
    /// the meas/tick ratio.
    pub fn recalculate_length(&mut self) {
        self.master.adjust_meas_num(std::cmp::max(
            self.master.get_last_tick(),
            self.events.get_max_tick(),
        ));
    }
}

/// How to moo the song
pub struct MooInstructions {
    /// Output sample rate
    pub out_sample_rate: SampleRate,
    /// The voices of the cows
    pub voices: Voices,
    /// How many samples constitute a tick.
    pub samples_per_tick: SamplesPerTick,
}

/// The vocal cords of the cows
#[derive(Default)]
pub struct Voices(ArrayVec<Voice, 100>);

impl std::ops::Deref for Voices {
    type Target = ArrayVec<Voice, 100>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for Voices {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl std::ops::Index<VoiceIdx> for Voices {
    type Output = Voice;

    fn index(&self, index: VoiceIdx) -> &Self::Output {
        &self.0[usize::from(index.0)]
    }
}

impl std::ops::IndexMut<VoiceIdx> for Voices {
    fn index_mut(&mut self, index: VoiceIdx) -> &mut Self::Output {
        &mut self.0[usize::from(index.0)]
    }
}

impl Voices {
    /// The current number of voices
    #[must_use]
    pub const fn len(&self) -> u8 {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "50 is the max unit number, so this always succeeds"
        )]
        (self.0.len() as u8)
    }
    /// Whether there are no voices
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Immutably iterate over the voices, along with their indices
    pub fn enumerated(&self) -> impl Iterator<Item = (VoiceIdx, &Voice)> {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "50 is the max unit number, so this always succeeds"
        )]
        self.iter().enumerate().map(|(idx, item)| (VoiceIdx(idx as u8), item))
    }
    /// Mutably iterate over the voices, along with their indices
    pub fn enumerated_mut(&mut self) -> impl Iterator<Item = (VoiceIdx, &mut Voice)> {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "50 is the max unit number, so this always succeeds"
        )]
        self.iter_mut().enumerate().map(|(idx, item)| (VoiceIdx(idx as u8), item))
    }
    /// Immutably get the voice at `idx`.
    ///
    /// If `idx` is 100 or larger, it will get the voice from `extra_voices` instead.
    ///
    /// Returns `None` on out of bounds indexing
    #[must_use]
    pub fn get<'a>(&'a self, idx: VoiceIdx, extra_voices: &'a [Voice]) -> Option<&'a Voice> {
        if idx.0 < 100 {
            self.0.get(idx.usize())
        } else {
            extra_voices.get(idx.usize() - 100)
        }
    }
    /// Mutably get the voice at `idx`, returning `None` on out of bounds indexing
    ///
    /// NOTE: This (currently) doesn't have the same behavior as [`Self::get`].
    #[must_use]
    pub fn get_mut(&mut self, idx: VoiceIdx) -> Option<&mut Voice> {
        self.0.get_mut(idx.usize())
    }
}

impl MooInstructions {
    /// Create a new [`MooInstructions`] with the provided sample rate
    #[must_use]
    pub fn new(out_sample_rate: SampleRate) -> Self {
        Self {
            out_sample_rate,
            voices: Voices::default(),
            samples_per_tick: 1.0,
        }
    }
}

/// Adjust voice and effect tones to output sample rate
pub fn rebuild_tones(
    ins: &mut MooInstructions,
    out_sample_rate: SampleRate,
    delays: &mut [Delay],
    overdrives: &mut [Overdrive],
    master: &Master,
) {
    for delay in delays {
        delay.rebuild(
            master.timing.beats_per_meas,
            master.timing.bpm,
            ins.out_sample_rate,
        );
    }
    for ovr in overdrives {
        ovr.rebuild();
    }
    let builder = NoiseTable::generate();
    for voice in ins.voices.iter_mut() {
        voice.recalculate(&builder, out_sample_rate);
    }
}

/// The glorious cows that are going to moo your song
#[derive(Default)]
pub struct Herd {
    /// If true, [`Self::moo`] won't do anything
    ///
    /// Usually set after a song without `loop` finished playing.
    pub moo_end: bool,
    loop_: bool,
    smp_smooth: SampleRate,
    /// Counter variable for what sample we are at
    pub smp_count: SampleT,
    smp_start: SampleT,
    /// The song will end at this sample
    pub smp_end: SampleT,
    /// The song will repeat from here
    pub smp_repeat: SampleT,
    smp_stride: f32,
    time_pan_index: usize,
    /// What event to play next
    pub evt_idx: usize,
    /// The 🐄 cow units that drive music synthesis. Each one outputs a PCM stream that's mixed
    /// together for a final result.
    pub units: Box<Units>,
    /// Delay (reverb) effects
    pub delays: Delays,
    /// Overdrive (amplify + clip) effects
    pub overdrives: Overdrives,
}

pub type Delays = ArrayVec<Delay, 4>;
pub type Overdrives = ArrayVec<Overdrive, 2>;
/// The 🐄[cow](Unit)s that moo the song.
///
/// The maximum number of them is 50.
#[derive(Default)]
pub struct Units(pub(crate) ArrayVec<Unit, 50>);

impl Units {
    /// The current number of cows
    #[must_use]
    pub const fn len(&self) -> u8 {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "50 is the max unit number, so this always succeeds"
        )]
        (self.0.len() as u8)
    }
    /// Whether there are no cows
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Immutably iterate over the units, along with their indices
    pub fn enumerated(&self) -> impl Iterator<Item = (UnitIdx, &Unit)> {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "50 is the max unit number, so this always succeeds"
        )]
        self.iter().enumerate().map(|(idx, item)| (UnitIdx(idx as u8), item))
    }
    /// Mutably iterate over the units, along with their indices
    pub fn enumerated_mut(&mut self) -> impl Iterator<Item = (UnitIdx, &mut Unit)> {
        #[expect(
            clippy::cast_possible_truncation,
            reason = "50 is the max unit number, so this always succeeds"
        )]
        self.iter_mut().enumerate().map(|(idx, item)| (UnitIdx(idx as u8), item))
    }
    /// Immutably get the unit at `idx`, returning `None` on out of bounds indexing
    #[must_use]
    pub fn get(&self, idx: UnitIdx) -> Option<&Unit> {
        self.0.get(idx.usize())
    }
    /// Mutably get the unit at `idx`, returning `None` on out of bounds indexing
    #[must_use]
    pub fn get_mut(&mut self, idx: UnitIdx) -> Option<&mut Unit> {
        self.0.get_mut(idx.usize())
    }
}

impl std::ops::Deref for Units {
    type Target = ArrayVec<Unit, 50>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for Units {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<T: Into<UnitIdx>> std::ops::Index<T> for Units {
    type Output = Unit;

    fn index(&self, index: T) -> &Self::Output {
        &self.0[usize::from(index.into().0)]
    }
}

impl<T: Into<UnitIdx>> std::ops::IndexMut<T> for Units {
    fn index_mut(&mut self, index: T) -> &mut Self::Output {
        &mut self.0[usize::from(index.into().0)]
    }
}

impl Herd {
    /// Seek to sample count
    pub const fn seek_to_sample(&mut self, sample: SampleT) {
        self.smp_count = sample;
        // If we set the event index to zero, the correct event index will be found when we moo
        self.evt_idx = 0;
    }
    /// Make sure all the cows' voices are ready for playback
    pub fn tune_cow_voices(
        &mut self,
        ins: &MooInstructions,
        timing: Timing,
        extra_voices: &[Voice],
    ) {
        for unit in self.units.iter_mut() {
            unit.tone_init();
            unit.reset_voice(ins, VoiceIdx(0), timing, extra_voices);
        }
    }
}

/// Read a PxTone song from a byte array.
///
/// Returns a tuple of:
/// - The [`Song`]: Mostly static song data that doesn't change during playback
/// - The [`Herd`]: The cows (units), and other data that keeps track of playback state
/// - The [`MooInstructions`]: Contains the [`Voice`]s of the cows, and some other data required
///   for mooing.
///
/// The current organization structure is a bit arbitrary, reached after a lot of refactoring
/// of various parts of the codebase. It will probably change in future releases to a cleaner API.
///
/// ## Playback
///
/// If your goal is to play the song, you should call [`moo_prepare`](crate::moo_prepare) next,
/// after which you can get samples to output with [`Herd::moo`].
#[expect(clippy::missing_errors_doc)]
pub fn read_song(
    data: &[u8],
    out_sample_rate: SampleRate,
) -> ReadResult<(Song, Herd, MooInstructions)> {
    let mut song = Song {
        text: Text::default(),
        master: Master::default(),
        events: EveList::default(),
        fmt: FmtInfo {
            ver: FmtVer::V5,
            kind: FmtKind::Collage,
            exe_ver: 0,
            dummy: 0,
        },
    };
    let mut ins = MooInstructions {
        out_sample_rate,
        voices: Voices::default(),
        samples_per_tick: 0.0,
    };
    let mut herd = Herd::default();

    io::read(&mut song, &mut herd, &mut ins, data)?;
    song.recalculate_length();
    rebuild_tones(
        &mut ins,
        out_sample_rate,
        &mut herd.delays,
        &mut herd.overdrives,
        &song.master,
    );
    Ok((song, herd, ins))
}

/// Serialize the project into the PxTone file format
pub fn serialize_project(song: &Song, herd: &Herd, ins: &MooInstructions) -> WriteResult<Vec<u8>> {
    io::write(song, herd, ins)
}