aboutsummaryrefslogtreecommitdiff
path: root/src/convert.rs
blob: a96c80220255783c6a286549a6d45ad7b9ad8c78 (plain) (blame)
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
use std::collections::{BTreeMap, BTreeSet};
use std::cell::RefCell;
use std::rc::Rc;
use crate::itfile::{ITFile, Cell};
use crate::utils::Rational;
use crate::midifile::{MidiEvent, TimedMidiEvent, MidiTrack, MidiFile, lint_track, lint_tempo};
use crate::portmod::Effect;

#[derive(Debug)]
#[derive(Clone)]
struct PlayerState
{
    skip_row: u8,
    skip_ord: u8,
    current_ord: u8,
    current_row: u8,
    current_tick: u8,
    speed: u8,
    tempo: u8,
    rpb: u8,
    force_speed: Option<Rational>,
    loop_start: u8,
    loop_ctr: u8,
    row_extension: u8,
    in_rep: bool
}

type CellHandlerFn<'a> = dyn 'a + FnMut(u8, Cell, PlayerState) -> PlayerState;
type EfxHandlerFn<'a> = dyn 'a + FnMut(u8, Cell, Rc<RefCell<ChannelMemory>>, PlayerState, Rational) -> Vec<(TimedMidiEvent, (u8, u8))>;

struct Player<'a, 'b>
{
    h: Box<RefCell<CellHandlerFn<'b>>>,
    it: &'a ITFile
}

struct ChannelMemory
{
    note: u8,
    postnote: u8,
    inst: u8,
    postinst: u8,
    initvol: u8,
    vol: u8,
    efxmem: [u8; 32],
    pitch: Rational
}

impl Default for ChannelMemory
{
    fn default() -> ChannelMemory
    {
        ChannelMemory {
            note: 0xff,
            postnote: 0xff,
            inst: 0xff,
            postinst: 0xff,
            initvol: 0,
            vol: 0,
            efxmem: Default::default(),
            pitch: 0u32.into()
        }
    }
}

pub struct Converter<'a, 'b> where 'a: 'b
{
    it: &'a ITFile,
    miditick: Rational,
    chmem: Vec<Rc<RefCell<ChannelMemory>>>,
    trks: Vec<MidiTrack>,
    fx_handlers: Vec<Box<RefCell<EfxHandlerFn<'b>>>>
}

impl<'a, 'b> Player<'a, 'b>
{
    fn new(handler: Box<RefCell<CellHandlerFn<'b>>>, it: &'a ITFile) -> Player<'a, 'b>
    {
        Player
        {
            h: handler,
            it
        }
    }
    fn process_timingfx(&self, cell: Cell, ps: PlayerState) -> PlayerState
    {
        let e = Effect::from_it_efx((cell.efx, cell.fxp));
        if ps.current_tick == 0
        {
            match e
            {
                Effect::SetSpeed(s) => PlayerState{speed: s, ..ps},
                Effect::PattLoopStart => PlayerState{loop_start: ps.current_row, ..ps},
                Effect::SetTempo(t) => PlayerState{tempo: t, ..ps},
                Effect::RowExtention(t) => PlayerState{row_extension: ps.row_extension + t, ..ps},
                Effect::SetVibWaveform(0xe) => { //it2midi-specific command: enter swing mode
                    let mut ticks = 0;
                    let mut ts = ps.speed;
                    for r in ps.current_row..ps.current_row + ps.rpb
                    {
                        let pat = &self.it.patterns[self.it.orders[ps.current_ord as usize] as usize];
                        for c in 0..pat.nch
                        {
                            let rcell = pat.cell_at(r, c);
                            if rcell.mask & 0x88 != 0
                            {
                                let fx = Effect::from_it_efx((rcell.efx, rcell.fxp));
                                match fx
                                {
                                    Effect::SetSpeed(a) => ts = a,
                                    _ => ()
                                }
                            }
                        }
                        ticks += ts;
                    }
                    let swing_speed = Some(Rational::from(ticks) / Rational::from(ps.rpb));
                    PlayerState{force_speed: swing_speed, ..ps}
                },
                Effect::SetTremWaveform(0x4) => { //it2midi-specific command: force current speed
                    PlayerState{force_speed: Some(Rational::from(ps.speed)), ..ps}
                },
                Effect::SetTremWaveform(x @ 0x5..=0xf) => { //it2midi-specific command: force speed
                    PlayerState{force_speed: Some(Rational::from(x - 0x3)), ..ps}
                },
                Effect::SetVibWaveform(0xf) => PlayerState{force_speed: None, ..ps}, //it2midi-specific command: exit swing mode
                _ => ps
            }
        }
        else if ps.current_tick == ps.speed - 1
        {
            match e
            {
                Effect::PosJump(p) => self.skip_to(!0, p, ps),
                Effect::PattBreak(r) => self.skip_to(r, !0, ps),
                Effect::PattLoop(c) =>
                    match ps.loop_ctr
                    {
                        u8::MAX => PlayerState{loop_ctr: 1, .. self.skip_to(ps.loop_start, ps.current_ord, ps)},
                        _ if ps.loop_ctr >= c => PlayerState{loop_ctr: !0, ..ps},
                        _ => PlayerState{loop_ctr: ps.loop_start + 1, .. self.skip_to(ps.loop_start, ps.current_ord, ps)}
                    },
                Effect::PattDelay(c) =>
                    match ps.loop_ctr
                    {
                        u8::MAX => PlayerState{loop_ctr: 1, in_rep: true, .. self.skip_to(ps.current_row, ps.current_ord, ps)},
                        _ if ps.loop_ctr >= c => PlayerState{loop_ctr: !0, in_rep: false, ..ps},
                        _ => PlayerState{loop_ctr: ps.loop_start + 1, .. self.skip_to(ps.current_row, ps.current_ord, ps)}
                    },
                Effect::TempoSlideDown(v) => PlayerState{tempo: ps.tempo - v, ..ps},
                Effect::TempoSlideUp(v) => PlayerState{tempo: ps.tempo + v, ..ps},
                _ => ps
            }
        }
        else {
            match e
            {
                Effect::TempoSlideDown(v) => PlayerState{tempo: ps.tempo - v, ..ps},
                Effect::TempoSlideUp(v) => PlayerState{tempo: ps.tempo + v, ..ps},
                _ => ps
            }
        }
    }
    fn process_pattern(&self, pat: usize, st: PlayerState) -> PlayerState
    {
        let skip_row = if !st.skip_row == 0 { 0 } else { st.skip_row };
        let mut ret = PlayerState{skip_row: !0, ..st};
        for r in skip_row..self.it.patterns[pat].nrows
        {
            ret.current_row = r;
            ret.current_tick = 0;
            while ret.current_tick < ret.speed + ret.row_extension
            {
                for c in 0..64
                {
                        let cell = *self.it.patterns[pat].cell_at(r, c);
                        ret = (self.h.borrow_mut())(c as u8, cell, ret);
                        ret = self.process_timingfx(cell, ret);
                }
                ret.current_tick += 1;
            }
            ret = (self.h.borrow_mut())(!0, Cell::default(), ret);
            ret.row_extension = 0;
            if (!ret.skip_row) != 0 || (!ret.skip_ord) != 0 { return ret; }
        }
        ret
    }
    /// Used for effects Bxx, Cxx and SBx
    ///
    /// passing !0 to row or ord if it's unused
    fn skip_to(&self, row: u8, ord: u8, ps: PlayerState) -> PlayerState
    {
        println!("skip to row {} of ord #{}", row, ord);
        PlayerState {
            skip_row: if !row != 0 { row } else { ps.skip_row },
            skip_ord: if !ord != 0 { ord } else {
                          if (!row != 0) && (!ps.skip_ord == 0) { ps.current_ord + 1 } else { ps.skip_ord }
                      },
            ..ps
        }
    }
    fn process_orders(&self)
    {
        let mut ps = PlayerState {
            skip_row: !0,
            skip_ord: !0,
            current_ord: 0,
            current_row: 0,
            current_tick: 0,
            speed: self.it.header.speed,
            tempo: self.it.header.tempo,
            rpb: self.it.time_signature().unwrap_or((4, 16)).0 as u8,
            force_speed: None,
            loop_start: 0,
            loop_ctr: !0,
            row_extension: 0,
            in_rep: false
        };

        let mut oid = 0;
        loop
        {
            if oid >= self.it.orders.len() { break; }
            if self.it.orders[oid] == 0xff { break; }
            if self.it.orders[oid] == 0xfe { continue; }
            ps.current_ord = oid as u8;
            ps = self.process_pattern(self.it.orders[oid].into(), ps);
            if !ps.skip_ord != 0
            {
                if ps.skip_ord as usize <= oid && !ps.loop_ctr == 0
                { println!("loop?"); }
                else { oid = ps.skip_ord as usize; }
                ps.skip_ord = !0;
            }
            else { oid += 1; }
        }
    }
}

impl<'a, 'b> Converter<'a, 'b>
{
    pub fn new(it: &'a ITFile) -> Converter<'a, 'b>
    {
        let mut ret = Converter
        {
            it,
            miditick: 0u32.into(),
            chmem: Vec::new(),
            trks: Vec::new(),
            fx_handlers: Vec::new()
        };
        for _ in 0..256
        { ret.chmem.push(Rc::new(RefCell::new(Default::default()))); }
        ret.setup_fx_handlers();
        ret
    }
    fn setup_fx_handlers<'x, 'y>(&mut self)
    {
        let nonfx = |ch: u8, cell, chmem: Rc<RefCell<ChannelMemory>>, ps: PlayerState, t: Rational| {
            if !ch == 0 || ps.in_rep { return Vec::new(); }
            let mut ret = Vec::new();
            let Cell { mask, note, mut inst, vol, .. } = cell;
            let vole = Effect::from_it_vol(vol);
            let mut vel = 0xffu8;
            if mask & 0x44 != 0
            {
                match vole
                {
                    Effect::SetVolume(vol) => vel = vol,
                    _ => ()
                }
            }
            if mask & 0x11 != 0 && ps.current_tick == 0
            {
                if mask & 0x22 == 0
                {
                    inst = chmem.borrow().postinst;
                }
                match note
                {
                    0x78..=0xff =>
                        if chmem.borrow().postnote != 0xff
                        {
                            ret.push((TimedMidiEvent{t: t.as_int_trunc() as u32, e: MidiEvent::NoteOff{ch: 0, key: chmem.borrow().postnote, vel: 0x40}}, (ch, inst)));
                            chmem.borrow_mut().postnote = 0xff;
                        },
                    _ =>
                    {
                        if chmem.borrow().postnote != 0xff
                        {
                            ret.push((TimedMidiEvent{t: t.as_int_trunc() as u32, e: MidiEvent::NoteOff{ch: 0, key: chmem.borrow().postnote, vel: 0x40}}, (ch, chmem.borrow().postinst)));
                        }
                        if vel == 0xff
                        {
                            let samp = if self.it.inst_mode() { self.it.insts[(inst - 1) as usize].samp_for_key(note) } else { inst };
                            if samp != 0
                            { vel = self.it.samps[(samp - 1) as usize].default_vol(); }
                        }
                        ret.push((TimedMidiEvent{t: t.as_int_trunc() as u32, e: MidiEvent::NoteOn{ch: 0, key: note, vel}}, (ch, inst)));
                        chmem.borrow_mut().postnote = note;
                        chmem.borrow_mut().postinst = inst;
                        chmem.borrow_mut().initvol = vol;
                        chmem.borrow_mut().vol = vol;
                    }
                }
            }
            ret
        };
        let tempofx = |ch: u8, cell, _chmem: Rc<RefCell<ChannelMemory>>, ps: PlayerState, t: Rational| {
            if !ch == 0 || ps.in_rep { return Vec::new(); }
            let mut ret = Vec::new();
            let Cell { mask, efx, fxp, .. } = cell;
            let fx = Effect::from_it_efx((efx, fxp));
            if mask & 0x88 != 0
            {
                match fx
                {
                    Effect::SetSpeed(_) | Effect::SetTempo(_) |
                    Effect::TempoSlideDown(_) | Effect::TempoSlideUp(_) |
                    Effect::SetVibWaveform(0xe) | Effect::SetVibWaveform(0xf) |
                    Effect::SetTremWaveform(0x4..=0xf) =>
                    {
                        match ps.force_speed
                        {
                            None => ret.push((TimedMidiEvent{ t: t.as_int_trunc() as u32, e: MidiEvent::MetaTempo(ps.tempo as f64 * 24. / ps.rpb as f64 / ps.speed as f64)}, (!0, !0))),
                            Some(ss) => ret.push((TimedMidiEvent{ t: t.as_int_trunc() as u32, e: MidiEvent::MetaTempo((Rational::from(ps.tempo as u16 * 24) / Rational::from(ps.rpb) / ss).into())}, (!0, !0)))
                        }
                    }
                    _ => ()
                }
            }
            ret
        };

        self.fx_handlers.push(Box::new(RefCell::new(tempofx)));
        self.fx_handlers.push(Box::new(RefCell::new(nonfx)));
    }
    fn pre_pass(it: &ITFile) -> BTreeMap<(u8, u8), usize>
    {
        let mut chinst = [0u8; 64];
        let mut instchmap: BTreeSet<(u8, u8)> = BTreeSet::new();
        {
            let h = |ch, cell, ps: PlayerState| {
                if (ch == 0xff) || (ps.current_tick != 0) { return ps; }
                let Cell{mask, mut inst, ..} = cell;
                if mask & 0x22 != 0
                { chinst[ch as usize] = inst; }
                else
                { inst = chinst[ch as usize]; }
                if mask & 0x11 != 0
                { instchmap.insert((inst, ch)); }
                ps
            };
            let p = Player::new(Box::new(RefCell::new(h)), it);
            p.process_orders();
        }
        let mut instch: BTreeMap<(u8, u8), usize> = BTreeMap::new();
        instchmap.iter().enumerate().for_each(
            |(i, p)| { instch.insert(*p, i + 1); } );
        instch
    }
    pub fn convert(&mut self)
    {
        let it = self.it;
        let instch = Converter::pre_pass(it);
        println!("{:?}", instch);
        self.trks.resize_with(instch.len() + 1, Default::default);
        self.trks[0].push(TimedMidiEvent{ t: 0, e: MidiEvent::MetaTimeSig { n: 1, d_pot: 2 }});
        let initspd = it.header.speed as f64;
        let inittpo = it.header.tempo as f64;
        let rpb = it.time_signature().unwrap_or((4, 4)).0 as f64;
        self.trks[0].push(TimedMidiEvent{ t: 0, e: MidiEvent::MetaTempo(inittpo * 24. / rpb / initspd)});
        for ((inst, ch), trkn) in instch.iter()
        {
            let tn = format!("{} (instr #{}) @ ch{}", it.insts[(inst - 1) as usize].inst_name() , *inst, *ch);
            self.trks[*trkn].push(TimedMidiEvent{ t:0, e: MidiEvent::MetaTrackName(tn) });
        }

        {
            let h = |ch:u8, cell, ps: PlayerState|
            {
                let Cell{mask, note, inst, vol: _, efx: _, fxp: _} = cell;
                if !ch == 0
                {
                    match ps.force_speed
                    {
                        None => self.miditick += Rational::from(960u32) / (ps.rpb as u16).into(),
                        Some(ss) => self.miditick += Rational::from(960u32) / (ps.rpb as u16).into() * (Rational::from(ps.speed) / ss)
                    }
                }
                if mask & 0x11 != 0 { self.chmem[ch as usize].borrow_mut().note = note; }
                if mask & 0x22 != 0 { self.chmem[ch as usize].borrow_mut().inst = inst; }
                self.fx_handlers.iter().for_each(
                    |h| {
                        let ev = (h.borrow_mut())(ch, cell, self.chmem[ch as usize].clone(), ps.clone(), self.miditick);
                        ev.iter().for_each(
                            |(e, (ch, inst))| {
                                let target_track = instch.get(&(*inst, *ch)).unwrap_or(&0);
                                self.trks[*target_track].push(e.clone());
                            }
                        );
                    });
                ps
            };
            let p = Player::new(Box::new(RefCell::new(h)), it);
            p.process_orders();
        }

        self.trks.iter_mut().for_each(|t| t.push(TimedMidiEvent{
            t: t.last().unwrap_or(&TimedMidiEvent{t: 0, e: MidiEvent::MetaEndOfTrack}).t,
            e: MidiEvent::MetaEndOfTrack}));

        self.trks[0] = lint_tempo(&self.trks[0]);
        self.trks.iter().for_each(|t| { lint_track(t); });
    }
    pub fn result(self) -> MidiFile
    {
        MidiFile{div: 960, tracks: self.trks}
    }
}