1use std::collections::HashMap;
12use std::hash::Hash;
13
14use crate::defaults::{FloatType, IntegerType};
15use crate::error::{Error, Result};
16use crate::instrument::{Instrument, SearchLanguage};
17
18use super::base::{
19 CHANNEL_VOICE_MESSAGES, EventType, Param, ReadEvent, file_header_bytes, put_number,
20 put_variable_length_number,
21};
22
23pub const TICKS_PER_QUARTER: i64 = 10080;
25
26pub const TICKS_AT_START: i64 = TICKS_PER_QUARTER;
29
30pub const PERCUSSION_CHANNEL: u8 = 10;
32
33const PULSES_PER_CLICK: u8 = 24;
35const THIRTY_SECONDS_PER_QUARTER: u8 = 8;
37const MICROSECONDS_PER_MINUTE: FloatType = 60_000_000.0;
39const TEMPO_BYTES: usize = 3;
41pub const DEFAULT_STROKE_KEY: u8 = 60;
43
44const NOTE_ON: u8 = 0x90;
45const NOTE_OFF: u8 = 0x80;
46const PROGRAM_CHANGE: u8 = 0xC0;
47const SEQUENCE_TRACK_NAME: u8 = 0x03;
48const INSTRUMENT_NAME: u8 = 0x04;
49const LYRIC: u8 = 0x05;
50const END_OF_TRACK: u8 = 0x2F;
51const SET_TEMPO: u8 = 0x51;
52const TIME_SIGNATURE: u8 = 0x58;
53const KEY_SIGNATURE: u8 = 0x59;
54
55#[derive(Clone, Copy, Debug, PartialEq, Eq)]
57pub enum StartDelay {
58 Without,
60 Quarter,
62}
63
64#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum EndDelay {
68 Without,
70 Quarter,
72}
73
74#[derive(Clone, Copy, Debug, PartialEq, Eq)]
77pub enum Deltas {
78 Included,
80 Omitted,
82}
83
84#[derive(Clone, Copy, Debug, PartialEq, Eq)]
86pub enum Mode {
87 Major,
89 Minor,
91}
92
93#[derive(Clone, Debug, PartialEq)]
95pub enum Laid {
96 Delta {
99 ticks: i64,
101 channel: Option<u8>,
103 },
104 Event {
107 event: ReadEvent,
109 cent_shift: Option<IntegerType>,
111 },
112}
113
114impl Laid {
115 fn delta(ticks: i64, channel: Option<u8>) -> Self {
116 Self::Delta { ticks, channel }
117 }
118
119 fn event(event_type: EventType, channel: Option<u8>, data: Param) -> Self {
120 Self::Event {
121 event: ReadEvent {
122 event_type,
123 channel,
124 parameter1: data,
125 parameter2: None,
126 },
127 cent_shift: None,
128 }
129 }
130
131 fn meta(kind: u8, data: Vec<u8>) -> Self {
132 Self::event(EventType::Meta(kind), None, Param::Bytes(data))
133 }
134
135 fn note(message: u8, channel: u8, sounding: &Sounding, velocity: u8) -> Self {
136 Self::Event {
137 event: ReadEvent {
138 event_type: EventType::ChannelVoice(message),
139 channel: Some(channel),
140 parameter1: Param::Int(i64::from(sounding.key)),
141 parameter2: Some(velocity),
142 },
143 cent_shift: sounding.cent_shift,
144 }
145 }
146}
147
148#[derive(Clone, Copy, Debug, PartialEq, Eq)]
150pub struct Sounding {
151 pub key: u8,
153 pub cent_shift: Option<IntegerType>,
155 pub velocity: u8,
157}
158
159pub fn offset_ticks(offset: FloatType, delay: StartDelay) -> i64 {
169 let ticks = duration_ticks(offset);
170 match delay {
171 StartDelay::Without => ticks,
172 StartDelay::Quarter => ticks + TICKS_AT_START,
173 }
174}
175
176pub fn duration_ticks(quarter_length: FloatType) -> i64 {
178 (quarter_length * TICKS_PER_QUARTER as FloatType).round_ties_even() as i64
179}
180
181pub fn meter_data(numerator: u32, denominator: u32) -> Option<[u8; 4]> {
191 let numerator = u8::try_from(numerator).ok()?;
192 let power = FloatType::from(denominator).log2() as u8;
193 Some([
194 numerator,
195 power,
196 PULSES_PER_CLICK,
197 THIRTY_SECONDS_PER_QUARTER,
198 ])
199}
200
201pub fn meter_of(data: &[u8]) -> Option<(u32, u32)> {
205 let [numerator, power, ..] = data else {
206 return None;
207 };
208 let denominator = 2_u32.checked_pow(u32::from(*power))?;
209 Some((u32::from(*numerator), denominator))
210}
211
212pub fn key_data(sharps: IntegerType, mode: Mode) -> [u8; 2] {
220 [sharps.rem_euclid(256) as u8, u8::from(mode == Mode::Minor)]
221}
222
223pub fn key_of(data: &[u8]) -> Option<(IntegerType, Mode)> {
226 let [sharps, mode, ..] = data else {
227 return None;
228 };
229 let sharps = if *sharps > 12 {
230 IntegerType::from(*sharps) - 256
231 } else {
232 IntegerType::from(*sharps)
233 };
234 let mode = if *mode == 1 { Mode::Minor } else { Mode::Major };
235 Some((sharps, mode))
236}
237
238pub fn tempo_data(quarter_bpm: FloatType) -> [u8; 3] {
247 let micros = (MICROSECONDS_PER_MINUTE / quarter_bpm).round_ties_even() as i128;
248 let written = put_number(micros, TEMPO_BYTES);
249 [written[0], written[1], written[2]]
250}
251
252pub fn tempo_of(data: &[u8]) -> Option<FloatType> {
256 let bytes = data.get(..TEMPO_BYTES)?;
257 let micros = bytes
258 .iter()
259 .fold(0_u64, |total, byte| (total << 8) | u64::from(*byte));
260 if micros == 0 {
261 return None;
262 }
263 Some((MICROSECONDS_PER_MINUTE / micros as FloatType * 100.0).round_ties_even() / 100.0)
264}
265
266fn timed(out: &mut Vec<Laid>, deltas: Deltas, ticks: i64, channel: Option<u8>) {
268 if deltas == Deltas::Included {
269 out.push(Laid::delta(ticks, channel));
270 }
271}
272
273pub fn note_events(
276 sounding: &Sounding,
277 lyric: &[u8],
278 ticks: i64,
279 channel: u8,
280 deltas: Deltas,
281) -> Vec<Laid> {
282 let mut out = Vec::new();
283 if !lyric.is_empty() {
284 timed(&mut out, deltas, 0, Some(channel));
285 out.push(Laid::meta(LYRIC, lyric.to_vec()));
286 }
287 timed(&mut out, deltas, 0, None);
288 out.push(Laid::note(NOTE_ON, channel, sounding, sounding.velocity));
289 timed(&mut out, deltas, ticks, Some(channel));
290 out.push(Laid::note(NOTE_OFF, channel, sounding, 0));
291 out
292}
293
294pub fn chord_events(
298 members: &[Sounding],
299 lyric: &[u8],
300 ticks: i64,
301 channel: u8,
302 deltas: Deltas,
303) -> Vec<Laid> {
304 let mut out = Vec::new();
305 if !lyric.is_empty() {
306 timed(&mut out, deltas, 0, None);
307 out.push(Laid::meta(LYRIC, lyric.to_vec()));
308 }
309 for member in members {
310 timed(&mut out, deltas, 0, None);
311 out.push(Laid::note(NOTE_ON, 1, member, member.velocity));
312 }
313 for (index, member) in members.iter().enumerate() {
314 let wait = if index == 0 { ticks } else { 0 };
315 timed(&mut out, deltas, wait, None);
316 out.push(Laid::note(NOTE_OFF, channel, member, 0));
317 }
318 out
319}
320
321pub fn program_events(program: u8, channel: u8, deltas: Deltas) -> Vec<Laid> {
323 let mut out = Vec::new();
324 timed(&mut out, deltas, 0, Some(channel));
325 out.push(Laid::event(
326 EventType::ChannelVoice(PROGRAM_CHANGE),
327 Some(channel),
328 Param::Int(i64::from(program)),
329 ));
330 out
331}
332
333pub fn start_events(name: &[u8], program: Option<u8>, channel: u8) -> Vec<Laid> {
336 let mut out = vec![Laid::delta(0, Some(channel))];
337 out.push(Laid::event(
338 EventType::Meta(SEQUENCE_TRACK_NAME),
339 Some(channel),
340 Param::Bytes(name.to_vec()),
341 ));
342 if let Some(program) = program {
343 out.extend(program_events(program, channel, Deltas::Included));
344 }
345 out
346}
347
348pub fn end_events(delay: EndDelay) -> Vec<Laid> {
350 let ticks = match delay {
351 EndDelay::Without => 0,
352 EndDelay::Quarter => TICKS_AT_START,
353 };
354 vec![
355 Laid::delta(ticks, None),
356 Laid::meta(END_OF_TRACK, Vec::new()),
357 ]
358}
359
360fn one_meta(kind: u8, data: Vec<u8>, deltas: Deltas) -> Vec<Laid> {
362 let mut out = Vec::new();
363 timed(&mut out, deltas, 0, None);
364 out.push(Laid::Event {
365 event: ReadEvent {
366 event_type: EventType::Meta(kind),
367 channel: Some(1),
368 parameter1: Param::Bytes(data),
369 parameter2: None,
370 },
371 cent_shift: None,
372 });
373 out
374}
375
376pub fn meter_events(numerator: u32, denominator: u32, deltas: Deltas) -> Vec<Laid> {
378 match meter_data(numerator, denominator) {
379 Some(data) => one_meta(TIME_SIGNATURE, data.to_vec(), deltas),
380 None => Vec::new(),
381 }
382}
383
384pub fn key_events(sharps: IntegerType, mode: Mode, deltas: Deltas) -> Vec<Laid> {
386 let mut out = Vec::new();
387 timed(&mut out, deltas, 0, None);
388 out.push(Laid::meta(KEY_SIGNATURE, key_data(sharps, mode).to_vec()));
389 out
390}
391
392pub fn tempo_events(quarter_bpm: FloatType, deltas: Deltas) -> Vec<Laid> {
394 one_meta(SET_TEMPO, tempo_data(quarter_bpm).to_vec(), deltas)
395}
396
397#[derive(Clone, Copy, Debug, PartialEq, Eq)]
399pub enum Source<'a> {
400 Program(u8),
402 TrackName(&'a str),
404 InstrumentName(&'a str),
406 OtherName(&'a str),
408 Nothing,
410}
411
412pub fn percussion_instrument(key: u8) -> Instrument {
418 let mut made = crate::instrument::for_percussion_key_or_unmapped(key);
419 made.set_headless(true);
420 made
421}
422
423fn is_placeholder(name: &str) -> bool {
426 let lower = name.to_lowercase();
427 let numbered = |prefix: &str| {
428 let rest = lower.replace(prefix, "");
429 !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit())
430 };
431 lower == "instrument" || lower == "inst" || numbered("instrument ") || numbered("inst ")
432}
433
434pub fn instrument_of(source: Source<'_>, channel: u8) -> Instrument {
439 let name = match source {
440 Source::TrackName(name) | Source::InstrumentName(name) | Source::OtherName(name) => {
441 name.split('\0').next().unwrap_or("").trim()
442 }
443 _ => "",
444 };
445 let mut instrument = match source {
446 Source::Program(program) if channel == PERCUSSION_CHANNEL => {
447 let mut made = Instrument::of_kind("UnpitchedPercussion").unwrap_or_default();
448 made.set_midi_program(Some(program));
449 made
450 }
451 Source::Program(program) => {
452 Instrument::from_midi_program(program).unwrap_or_else(|_| Instrument::new())
453 }
454 Source::Nothing => Instrument::new(),
455 _ => Instrument::from_name(name, SearchLanguage::All).unwrap_or_else(|_| Instrument::new()),
456 };
457 instrument.set_midi_channel(channel.checked_sub(1));
459 if name.is_empty() || is_placeholder(name) {
460 return instrument;
461 }
462 match source {
463 Source::TrackName(_) => instrument.set_part_name(Some(name.to_string())),
464 Source::InstrumentName(_) => instrument.set_name(Some(name.to_string())),
465 _ => {}
466 }
467 instrument
468}
469
470pub fn source_of(event_type: EventType, text: &str) -> Source<'_> {
472 match event_type {
473 EventType::Meta(SEQUENCE_TRACK_NAME) => Source::TrackName(text),
474 EventType::Meta(INSTRUMENT_NAME) => Source::InstrumentName(text),
475 _ => Source::OtherName(text),
476 }
477}
478
479pub fn event_ticks(deltas: &[Option<u64>]) -> Vec<(u64, usize)> {
484 let mut out = Vec::new();
485 let mut now: u64 = 0;
486 let mut index = 0;
487 while index + 1 < deltas.len() {
488 let (Some(wait), None) = (deltas[index], deltas[index + 1]) else {
489 index += 1;
490 continue;
491 };
492 now = now.saturating_add(wait);
493 out.push((now, index + 1));
494 index += 2;
495 }
496 out
497}
498
499#[derive(Clone, Copy, Debug, PartialEq, Eq)]
502pub enum NoteMark<K> {
503 On(K),
505 Off(K),
507 Other,
509}
510
511#[derive(Clone, Copy, Debug, PartialEq, Eq)]
513pub struct TimedNote {
514 pub on: u64,
516 pub off: u64,
518 pub index: usize,
520}
521
522pub fn notes_of<K: Eq + Hash + Copy>(events: &[(u64, NoteMark<K>)]) -> Vec<TimedNote> {
526 let mut waiting: HashMap<K, u64> = HashMap::new();
527 let mut notes = Vec::new();
528 for (index, (time, mark)) in events.iter().enumerate().rev() {
529 match mark {
530 NoteMark::Off(key) => {
531 waiting.insert(*key, *time);
532 }
533 NoteMark::On(key) => {
534 if let Some(off) = waiting.get(key) {
535 notes.push(TimedNote {
536 on: *time,
537 off: *off,
538 index,
539 });
540 }
541 }
542 NoteMark::Other => {}
543 }
544 }
545 notes.reverse();
546 notes
547}
548
549#[derive(Clone, Copy, Debug, PartialEq, Eq)]
552pub struct Played {
553 pub program: Option<u8>,
555 pub channel: Option<u8>,
557}
558
559#[derive(Clone, Debug, PartialEq, Eq)]
562pub struct Misplaced {
563 pub part: usize,
565 pub instrument: usize,
567 pub channel: u8,
569 pub acceptable: Vec<u8>,
571}
572
573#[derive(Clone, Debug, Default, PartialEq, Eq)]
576pub struct ChannelPlan {
577 pub by_program: Vec<(Option<u8>, u8)>,
580 pub dynamic: Vec<u8>,
582 pub misplaced: Vec<Misplaced>,
584}
585
586impl ChannelPlan {
587 pub fn channel(&self, program: Option<u8>) -> Option<u8> {
589 self.by_program
590 .iter()
591 .find(|(held, _)| *held == program)
592 .map(|(_, channel)| *channel)
593 }
594}
595
596pub fn plan_channels(parts: &[Vec<Played>], acceptable: Option<&[u8]>) -> ChannelPlan {
604 let mut free: Vec<u8> = acceptable
605 .map(<[u8]>::to_vec)
606 .unwrap_or_else(|| (1..PERCUSSION_CHANNEL).chain(11..=16).collect());
607 let mut plan = ChannelPlan::default();
608 let mut programs: Vec<Option<u8>> = Vec::new();
609 let mut assigned: Vec<u8> = Vec::new();
610
611 for (part, instruments) in parts.iter().enumerate() {
613 for (index, played) in instruments.iter().enumerate() {
614 if let Some(named) = played.channel
615 && plan.channel(played.program).is_none()
616 {
617 let mut channel = named.saturating_add(1);
618 if let Some(place) = free.iter().position(|ok| *ok == channel) {
619 free.remove(place);
620 } else if channel != PERCUSSION_CHANNEL {
621 plan.misplaced.push(Misplaced {
622 part,
623 instrument: index,
624 channel,
625 acceptable: free.clone(),
626 });
627 channel = 1;
628 }
629 if !assigned.contains(&channel) {
630 assigned.push(channel);
631 }
632 plan.by_program.push((played.program, channel));
633 }
634 if !programs.contains(&played.program) {
635 programs.push(played.program);
636 }
637 }
638 if instruments.is_empty() && !programs.contains(&None) {
639 programs.push(None);
640 }
641 }
642
643 let needed: Vec<Option<u8>> = programs
645 .into_iter()
646 .filter(|program| plan.channel(*program).is_none())
647 .collect();
648 for (index, program) in needed.into_iter().enumerate() {
649 let channel = if index + 1 < free.len() {
650 free[index]
651 } else {
652 free.first().copied().unwrap_or(1)
653 };
654 if !assigned.contains(&channel) {
655 assigned.push(channel);
656 }
657 plan.by_program.push((program, channel));
658 }
659 plan.dynamic = free
660 .into_iter()
661 .filter(|channel| !assigned.contains(channel))
662 .collect();
663 plan
664}
665
666#[derive(Clone, Debug, PartialEq, Eq)]
669pub enum Unsupported {
670 Meta(String),
672 Channel(String),
674}
675
676pub fn ascii_file(
698 format: i128,
699 ticks_per_quarter: i128,
700 tracks: &[Vec<String>],
701) -> Result<(Vec<u8>, Vec<Unsupported>)> {
702 let format = if tracks.len() == 1 { 1 } else { format };
703 let mut out = file_header_bytes(format, tracks.len(), ticks_per_quarter).map_err(midi_error)?;
704 let mut unsupported = Vec::new();
705 for (index, track) in tracks.iter().enumerate() {
706 let channel = u8::try_from(index % 16).unwrap_or(0);
707 let mut data = Vec::new();
708 for line in track {
709 let fields: Vec<&str> = line.split(' ').collect();
710 let [delta, status, key, velocity, ..] = fields[..] else {
711 return Err(Error::midi(format!("an event of too few fields: {line:?}")));
712 };
713 let delta: i128 = parsed(delta, 10)?;
714 let key = parsed(key, 16)?;
715 let velocity = parsed(velocity, 10)?;
716 let message = match status.chars().next() {
717 _ if status == "FF" => {
718 unsupported.push(Unsupported::Meta(status.to_string()));
719 continue;
720 }
721 Some('8') => NOTE_OFF,
722 Some('9') => NOTE_ON,
723 _ => {
724 unsupported.push(Unsupported::Channel(status.to_string()));
725 continue;
726 }
727 };
728 data.extend(put_variable_length_number(delta).map_err(midi_error)?);
729 let bytes = [message + channel, byte(key)?, byte(velocity)?];
730 data.extend_from_slice(&bytes);
731 }
732 out.extend_from_slice(super::base::TRACK_HEADER);
733 out.extend(put_number(data.len() as i128, 4));
734 out.extend(data);
735 }
736 Ok((out, unsupported))
737}
738
739fn parsed(field: &str, radix: u32) -> Result<i128> {
741 i128::from_str_radix(field, radix)
742 .map_err(|_| Error::midi(format!("not a number in base {radix}: {field:?}")))
743}
744
745fn byte(value: i128) -> Result<u8> {
747 u8::try_from(value).map_err(|_| Error::midi(format!("not a byte: {value}")))
748}
749
750fn midi_error(error: super::base::MidiDataError) -> Error {
751 Error::midi(error.to_string())
752}
753
754pub fn status_name(status: u8) -> Option<&'static str> {
756 super::base::name_of(CHANNEL_VOICE_MESSAGES, status & 0xF0)
757}
758
759#[cfg(test)]
760mod tests {
761 use super::*;
762
763 #[test]
764 fn a_meter_round_trips_through_its_bytes() {
765 let data = meter_data(3, 16).unwrap();
766 assert_eq!(meter_of(&data), Some((3, 16)));
767 assert_eq!(meter_of(&[3]), None);
768 }
769
770 #[test]
771 fn a_key_of_flats_reads_back_negative() {
772 assert_eq!(key_of(&key_data(-2, Mode::Minor)), Some((-2, Mode::Minor)));
773 assert_eq!(key_of(&[2, 0]), Some((2, Mode::Major)));
774 }
775
776 #[test]
777 fn a_tempo_reads_back_to_two_places() {
778 assert_eq!(tempo_of(&tempo_data(90.0)), Some(90.0));
779 assert_eq!(tempo_of(&[0, 0, 0]), None);
780 }
781
782 #[test]
783 fn a_note_is_four_entries_and_two_without_deltas() {
784 let sounding = Sounding {
785 key: 61,
786 cent_shift: None,
787 velocity: 90,
788 };
789 let laid = note_events(&sounding, b"", 25200, 1, Deltas::Included);
790 assert_eq!(laid.len(), 4);
791 assert_eq!(
792 laid[2],
793 Laid::Delta {
794 ticks: 25200,
795 channel: Some(1)
796 }
797 );
798 assert_eq!(
799 note_events(&sounding, b"la", 0, 9, Deltas::Omitted).len(),
800 3
801 );
802 }
803
804 #[test]
805 fn a_chord_turns_every_note_on_before_any_off() {
806 let member = |key| Sounding {
807 key,
808 cent_shift: None,
809 velocity: 90,
810 };
811 let laid = chord_events(&[member(48), member(68)], b"", 10080, 3, Deltas::Omitted);
812 let kinds: Vec<_> = laid
813 .iter()
814 .map(|entry| match entry {
815 Laid::Event { event, .. } => (event.event_type, event.channel),
816 Laid::Delta { .. } => unreachable!(),
817 })
818 .collect();
819 assert_eq!(
820 kinds,
821 [
822 (EventType::ChannelVoice(NOTE_ON), Some(1)),
823 (EventType::ChannelVoice(NOTE_ON), Some(1)),
824 (EventType::ChannelVoice(NOTE_OFF), Some(3)),
825 (EventType::ChannelVoice(NOTE_OFF), Some(3)),
826 ]
827 );
828 }
829
830 #[test]
831 fn events_are_timed_only_after_a_delta() {
832 let ticks = event_ticks(&[Some(5), None, None, Some(3), Some(2), None]);
833 assert_eq!(ticks, [(5, 1), (7, 5)]);
834 }
835
836 #[test]
837 fn a_note_on_takes_the_nearest_note_off_after_it() {
838 let events = [
839 (0, NoteMark::On(60)),
840 (1, NoteMark::On(62)),
841 (2, NoteMark::Off(62)),
842 (3, NoteMark::Off(60)),
843 (4, NoteMark::On(64)),
844 ];
845 let notes = notes_of(&events);
846 assert_eq!(
847 notes,
848 [
849 TimedNote {
850 on: 0,
851 off: 3,
852 index: 0
853 },
854 TimedNote {
855 on: 1,
856 off: 2,
857 index: 1
858 },
859 ]
860 );
861 }
862
863 #[test]
864 fn a_placeholder_name_names_nothing() {
865 let named = instrument_of(Source::TrackName("Inst 3"), 2);
866 assert_eq!(named.part_name(), None);
867 assert_eq!(named.midi_channel(), Some(1));
868 }
869
870 #[test]
871 fn a_named_channel_is_kept_and_one_left_free() {
872 let played = |program, channel| Played { program, channel };
873 let parts = [
874 vec![played(Some(0), Some(4))],
875 vec![played(Some(40), None)],
876 vec![],
877 ];
878 let plan = plan_channels(&parts, Some(&[1, 2, 4]));
879 assert_eq!(plan.by_program, [(Some(0), 1), (Some(40), 1), (None, 2)]);
880 assert_eq!(plan.misplaced.len(), 1);
881 assert_eq!(plan.dynamic, [4]);
882
883 let plan = plan_channels(&parts[1..], None);
884 assert_eq!(plan.by_program, [(Some(40), 1), (None, 2)]);
885 assert_eq!(plan.dynamic.len(), 13);
886 }
887
888 #[test]
889 fn text_notation_leaves_out_what_is_no_note() {
890 let tracks = [vec!["0 FF 2F 0".to_string(), "0 C0 05 0".to_string()]];
891 let (_, unsupported) = ascii_file(1, 960, &tracks).unwrap();
892 assert_eq!(
893 unsupported,
894 [
895 Unsupported::Meta("FF".into()),
896 Unsupported::Channel("C0".into())
897 ]
898 );
899 }
900}