Load_mid.cpp 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405
  1. /*
  2. * Load_mid.cpp
  3. * ------------
  4. * Purpose: MIDI file loader
  5. * Notes : (currently none)
  6. * Authors: OpenMPT Devs
  7. * The OpenMPT source code is released under the BSD license. Read LICENSE for more details.
  8. */
  9. #include "stdafx.h"
  10. #include "Loaders.h"
  11. #include "Dlsbank.h"
  12. #include "MIDIEvents.h"
  13. #ifdef MODPLUG_TRACKER
  14. #include "../mptrack/TrackerSettings.h"
  15. #include "../mptrack/Moddoc.h"
  16. #include "../mptrack/Mptrack.h"
  17. #include "../common/mptFileIO.h"
  18. #endif // MODPLUG_TRACKER
  19. OPENMPT_NAMESPACE_BEGIN
  20. #if defined(MODPLUG_TRACKER) || defined(MPT_FUZZ_TRACKER)
  21. #ifdef LIBOPENMPT_BUILD
  22. struct CDLSBank { static int32 DLSMidiVolumeToLinear(uint32) { return 256; } };
  23. #endif // LIBOPENMPT_BUILD
  24. #define MIDI_DRUMCHANNEL 10
  25. const char *szMidiGroupNames[17] =
  26. {
  27. "Piano",
  28. "Chromatic Percussion",
  29. "Organ",
  30. "Guitar",
  31. "Bass",
  32. "Strings",
  33. "Ensemble",
  34. "Brass",
  35. "Reed",
  36. "Pipe",
  37. "Synth Lead",
  38. "Synth Pad",
  39. "Synth Effects",
  40. "Ethnic",
  41. "Percussive",
  42. "Sound Effects",
  43. "Percussions"
  44. };
  45. const char *szMidiProgramNames[128] =
  46. {
  47. // 1-8: Piano
  48. "Acoustic Grand Piano",
  49. "Bright Acoustic Piano",
  50. "Electric Grand Piano",
  51. "Honky-tonk Piano",
  52. "Electric Piano 1",
  53. "Electric Piano 2",
  54. "Harpsichord",
  55. "Clavi",
  56. // 9-16: Chromatic Percussion
  57. "Celesta",
  58. "Glockenspiel",
  59. "Music Box",
  60. "Vibraphone",
  61. "Marimba",
  62. "Xylophone",
  63. "Tubular Bells",
  64. "Dulcimer",
  65. // 17-24: Organ
  66. "Drawbar Organ",
  67. "Percussive Organ",
  68. "Rock Organ",
  69. "Church Organ",
  70. "Reed Organ",
  71. "Accordion",
  72. "Harmonica",
  73. "Tango Accordion",
  74. // 25-32: Guitar
  75. "Acoustic Guitar (nylon)",
  76. "Acoustic Guitar (steel)",
  77. "Electric Guitar (jazz)",
  78. "Electric Guitar (clean)",
  79. "Electric Guitar (muted)",
  80. "Overdriven Guitar",
  81. "Distortion Guitar",
  82. "Guitar harmonics",
  83. // 33-40 Bass
  84. "Acoustic Bass",
  85. "Electric Bass (finger)",
  86. "Electric Bass (pick)",
  87. "Fretless Bass",
  88. "Slap Bass 1",
  89. "Slap Bass 2",
  90. "Synth Bass 1",
  91. "Synth Bass 2",
  92. // 41-48 Strings
  93. "Violin",
  94. "Viola",
  95. "Cello",
  96. "Contrabass",
  97. "Tremolo Strings",
  98. "Pizzicato Strings",
  99. "Orchestral Harp",
  100. "Timpani",
  101. // 49-56 Ensemble
  102. "String Ensemble 1",
  103. "String Ensemble 2",
  104. "SynthStrings 1",
  105. "SynthStrings 2",
  106. "Choir Aahs",
  107. "Voice Oohs",
  108. "Synth Voice",
  109. "Orchestra Hit",
  110. // 57-64 Brass
  111. "Trumpet",
  112. "Trombone",
  113. "Tuba",
  114. "Muted Trumpet",
  115. "French Horn",
  116. "Brass Section",
  117. "SynthBrass 1",
  118. "SynthBrass 2",
  119. // 65-72 Reed
  120. "Soprano Sax",
  121. "Alto Sax",
  122. "Tenor Sax",
  123. "Baritone Sax",
  124. "Oboe",
  125. "English Horn",
  126. "Bassoon",
  127. "Clarinet",
  128. // 73-80 Pipe
  129. "Piccolo",
  130. "Flute",
  131. "Recorder",
  132. "Pan Flute",
  133. "Blown Bottle",
  134. "Shakuhachi",
  135. "Whistle",
  136. "Ocarina",
  137. // 81-88 Synth Lead
  138. "Lead 1 (square)",
  139. "Lead 2 (sawtooth)",
  140. "Lead 3 (calliope)",
  141. "Lead 4 (chiff)",
  142. "Lead 5 (charang)",
  143. "Lead 6 (voice)",
  144. "Lead 7 (fifths)",
  145. "Lead 8 (bass + lead)",
  146. // 89-96 Synth Pad
  147. "Pad 1 (new age)",
  148. "Pad 2 (warm)",
  149. "Pad 3 (polysynth)",
  150. "Pad 4 (choir)",
  151. "Pad 5 (bowed)",
  152. "Pad 6 (metallic)",
  153. "Pad 7 (halo)",
  154. "Pad 8 (sweep)",
  155. // 97-104 Synth Effects
  156. "FX 1 (rain)",
  157. "FX 2 (soundtrack)",
  158. "FX 3 (crystal)",
  159. "FX 4 (atmosphere)",
  160. "FX 5 (brightness)",
  161. "FX 6 (goblins)",
  162. "FX 7 (echoes)",
  163. "FX 8 (sci-fi)",
  164. // 105-112 Ethnic
  165. "Sitar",
  166. "Banjo",
  167. "Shamisen",
  168. "Koto",
  169. "Kalimba",
  170. "Bag pipe",
  171. "Fiddle",
  172. "Shanai",
  173. // 113-120 Percussive
  174. "Tinkle Bell",
  175. "Agogo",
  176. "Steel Drums",
  177. "Woodblock",
  178. "Taiko Drum",
  179. "Melodic Tom",
  180. "Synth Drum",
  181. "Reverse Cymbal",
  182. // 121-128 Sound Effects
  183. "Guitar Fret Noise",
  184. "Breath Noise",
  185. "Seashore",
  186. "Bird Tweet",
  187. "Telephone Ring",
  188. "Helicopter",
  189. "Applause",
  190. "Gunshot"
  191. };
  192. // Notes 25-85
  193. const char *szMidiPercussionNames[61] =
  194. {
  195. "Seq Click",
  196. "Brush Tap",
  197. "Brush Swirl",
  198. "Brush Slap",
  199. "Brush Swirl W/Attack",
  200. "Snare Roll",
  201. "Castanet",
  202. "Snare Lo",
  203. "Sticks",
  204. "Bass Drum Lo",
  205. "Open Rim Shot",
  206. "Acoustic Bass Drum",
  207. "Bass Drum 1",
  208. "Side Stick",
  209. "Acoustic Snare",
  210. "Hand Clap",
  211. "Electric Snare",
  212. "Low Floor Tom",
  213. "Closed Hi-Hat",
  214. "High Floor Tom",
  215. "Pedal Hi-Hat",
  216. "Low Tom",
  217. "Open Hi-Hat",
  218. "Low-Mid Tom",
  219. "Hi Mid Tom",
  220. "Crash Cymbal 1",
  221. "High Tom",
  222. "Ride Cymbal 1",
  223. "Chinese Cymbal",
  224. "Ride Bell",
  225. "Tambourine",
  226. "Splash Cymbal",
  227. "Cowbell",
  228. "Crash Cymbal 2",
  229. "Vibraslap",
  230. "Ride Cymbal 2",
  231. "Hi Bongo",
  232. "Low Bongo",
  233. "Mute Hi Conga",
  234. "Open Hi Conga",
  235. "Low Conga",
  236. "High Timbale",
  237. "Low Timbale",
  238. "High Agogo",
  239. "Low Agogo",
  240. "Cabasa",
  241. "Maracas",
  242. "Short Whistle",
  243. "Long Whistle",
  244. "Short Guiro",
  245. "Long Guiro",
  246. "Claves",
  247. "Hi Wood Block",
  248. "Low Wood Block",
  249. "Mute Cuica",
  250. "Open Cuica",
  251. "Mute Triangle",
  252. "Open Triangle",
  253. "Shaker",
  254. "Jingle Bell",
  255. "Bell Tree",
  256. };
  257. ////////////////////////////////////////////////////////////////////////////////
  258. // Maps a midi instrument - returns the instrument number in the file
  259. uint32 CSoundFile::MapMidiInstrument(uint8 program, uint16 bank, uint8 midiChannel, uint8 note, bool isXG, std::bitset<16> drumChns)
  260. {
  261. ModInstrument *pIns;
  262. program &= 0x7F;
  263. bank &= 0x3FFF;
  264. note &= 0x7F;
  265. // In XG mode, extra drums are on banks with MSB 7F
  266. const bool isDrum = drumChns[midiChannel - 1] || (bank >= 0x3F80 && isXG);
  267. for (uint32 i = 1; i <= m_nInstruments; i++) if (Instruments[i])
  268. {
  269. ModInstrument *p = Instruments[i];
  270. // Drum Kit?
  271. if (isDrum)
  272. {
  273. if (note == p->nMidiDrumKey && bank + 1 == p->wMidiBank) return i;
  274. } else
  275. // Melodic Instrument
  276. {
  277. if (program + 1 == p->nMidiProgram && bank + 1 == p->wMidiBank && p->nMidiDrumKey == 0) return i;
  278. }
  279. }
  280. if(!CanAddMoreInstruments() || !CanAddMoreSamples())
  281. return 0;
  282. pIns = AllocateInstrument(m_nInstruments + 1);
  283. if(pIns == nullptr)
  284. {
  285. return 0;
  286. }
  287. m_nSamples++;
  288. pIns->wMidiBank = bank + 1;
  289. pIns->nMidiProgram = program + 1;
  290. pIns->nFadeOut = 1024;
  291. pIns->nNNA = NewNoteAction::NoteOff;
  292. pIns->nDCT = isDrum ? DuplicateCheckType::Sample : DuplicateCheckType::Note;
  293. pIns->nDNA = DuplicateNoteAction::NoteFade;
  294. if(isDrum)
  295. {
  296. pIns->nMidiChannel = MIDI_DRUMCHANNEL;
  297. pIns->nMidiDrumKey = note;
  298. for(auto &key : pIns->NoteMap)
  299. {
  300. key = NOTE_MIDDLEC;
  301. }
  302. }
  303. pIns->VolEnv.dwFlags.set(ENV_ENABLED);
  304. if (!isDrum) pIns->VolEnv.dwFlags.set(ENV_SUSTAIN);
  305. pIns->VolEnv.reserve(4);
  306. pIns->VolEnv.push_back(EnvelopeNode(0, ENVELOPE_MAX));
  307. pIns->VolEnv.push_back(EnvelopeNode(10, ENVELOPE_MAX));
  308. pIns->VolEnv.push_back(EnvelopeNode(15, (ENVELOPE_MAX + ENVELOPE_MID) / 2));
  309. pIns->VolEnv.push_back(EnvelopeNode(20, ENVELOPE_MIN));
  310. pIns->VolEnv.nSustainStart = pIns->VolEnv.nSustainEnd = 1;
  311. // Set GM program / drum name
  312. if (!isDrum)
  313. {
  314. pIns->name = szMidiProgramNames[program];
  315. } else
  316. {
  317. if (note >= 24 && note <= 84)
  318. pIns->name = szMidiPercussionNames[note - 24];
  319. else
  320. pIns->name = "Percussions";
  321. }
  322. return m_nInstruments;
  323. }
  324. struct MThd
  325. {
  326. uint32be headerLength;
  327. uint16be format; // 0 = single-track, 1 = multi-track, 2 = multi-song
  328. uint16be numTracks; // Number of track chunks
  329. uint16be division; // Delta timing value: positive = units/beat; negative = smpte compatible units
  330. };
  331. MPT_BINARY_STRUCT(MThd, 10)
  332. using tick_t = uint32;
  333. struct TrackState
  334. {
  335. FileReader track;
  336. tick_t nextEvent = 0;
  337. uint8 command = 0;
  338. bool finished = false;
  339. };
  340. struct ModChannelState
  341. {
  342. static constexpr uint8 NOMIDI = 0xFF; // No MIDI channel assigned.
  343. tick_t age = 0; // At which MIDI tick the channel was triggered
  344. int32 porta = 0; // Current portamento position in extra-fine slide units (1/64th of a semitone)
  345. uint8 vol = 100; // MIDI note volume (0...127)
  346. uint8 pan = 128; // MIDI channel panning (0...256)
  347. uint8 midiCh = NOMIDI; // MIDI channel that was last played on this channel
  348. ModCommand::NOTE note = NOTE_NONE; // MIDI note that was last played on this channel
  349. bool sustained = false; // If true, the note was already released by a note-off event, but sustain pedal CC is still active
  350. };
  351. struct MidiChannelState
  352. {
  353. int32 pitchbendMod = 0; // Pre-computed pitchbend in extra-fine slide units (1/64th of a semitone)
  354. int16 pitchbend = MIDIEvents::pitchBendCentre; // 0...16383
  355. uint16 bank = 0; // 0...16383
  356. uint8 program = 0; // 0...127
  357. // -- Controllers ---------------- function ---------- CC# --- range ---- init (midi) ---
  358. uint8 pan = 128; // Channel Panning 10 [0-255] 128 (64)
  359. uint8 expression = 128; // Channel Expression 11 0-128 128 (127)
  360. uint8 volume = 80; // Channel Volume 7 0-128 80 (100)
  361. uint16 rpn = 0x3FFF; // Currently selected RPN 100/101 n/a
  362. uint8 pitchBendRange = 2; // Pitch Bend Range 2
  363. int8 transpose = 0; // Channel transpose 0
  364. bool monoMode = false; // Mono/Poly operation 126/127 n/a Poly
  365. bool sustain = false; // Sustain pedal 64 on/off off
  366. std::array<CHANNELINDEX, 128> noteOn; // Value != CHANNELINDEX_INVALID: Note is active and mapped to mod channel in value
  367. MidiChannelState()
  368. {
  369. noteOn.fill(CHANNELINDEX_INVALID);
  370. }
  371. void SetPitchbend(uint16 value)
  372. {
  373. pitchbend = value;
  374. // Convert from arbitrary MIDI pitchbend to 64th of semitone
  375. pitchbendMod = Util::muldiv(pitchbend - MIDIEvents::pitchBendCentre, pitchBendRange * 64, MIDIEvents::pitchBendCentre);
  376. }
  377. void ResetAllControllers()
  378. {
  379. expression = 128;
  380. pitchBendRange = 2;
  381. SetPitchbend(MIDIEvents::pitchBendCentre);
  382. transpose = 0;
  383. rpn = 0x3FFF;
  384. monoMode = false;
  385. sustain = false;
  386. // Should also reset modulation, pedals (40h-43h), aftertouch
  387. }
  388. void SetRPN(uint8 value)
  389. {
  390. switch(rpn)
  391. {
  392. case 0: // Pitch Bend Range
  393. pitchBendRange = std::max(value, uint8(1));
  394. SetPitchbend(pitchbend);
  395. break;
  396. case 2: // Coarse Tune
  397. transpose = static_cast<int8>(value) - 64;
  398. break;
  399. }
  400. }
  401. void SetRPNRelative(int8 value)
  402. {
  403. switch(rpn)
  404. {
  405. case 0: // Pitch Bend Range
  406. pitchBendRange = static_cast<uint8>(std::clamp(pitchBendRange + value, 1, 0x7F));
  407. break;
  408. case 2: // Coarse Tune
  409. transpose = mpt::saturate_cast<int8>(transpose + value);
  410. break;
  411. }
  412. }
  413. };
  414. static CHANNELINDEX FindUnusedChannel(uint8 midiCh, ModCommand::NOTE note, const std::vector<ModChannelState> &channels, bool monoMode, PatternRow patRow)
  415. {
  416. for(size_t i = 0; i < channels.size(); i++)
  417. {
  418. // Check if this note is already playing, or find any note of the same MIDI channel in case of mono mode
  419. if(channels[i].midiCh == midiCh && (channels[i].note == note || (monoMode && channels[i].note != NOTE_NONE)))
  420. {
  421. return static_cast<CHANNELINDEX>(i);
  422. }
  423. }
  424. CHANNELINDEX anyUnusedChannel = CHANNELINDEX_INVALID;
  425. CHANNELINDEX anyFreeChannel = CHANNELINDEX_INVALID;
  426. CHANNELINDEX oldsetMidiCh = CHANNELINDEX_INVALID;
  427. tick_t oldestMidiChAge = std::numeric_limits<decltype(oldestMidiChAge)>::max();
  428. CHANNELINDEX oldestAnyCh = 0;
  429. tick_t oldestAnyChAge = std::numeric_limits<decltype(oldestAnyChAge)>::max();
  430. for(size_t i = 0; i < channels.size(); i++)
  431. {
  432. if(channels[i].note == NOTE_NONE && !patRow[i].IsNote())
  433. {
  434. // Recycle channel previously used by the same MIDI channel
  435. if(channels[i].midiCh == midiCh)
  436. return static_cast<CHANNELINDEX>(i);
  437. // If we cannot find a channel that was already used for the same MIDI channel, try a completely unused channel next
  438. else if(channels[i].midiCh == ModChannelState::NOMIDI && anyUnusedChannel == CHANNELINDEX_INVALID)
  439. anyUnusedChannel = static_cast<CHANNELINDEX>(i);
  440. // And if that fails, try any channel that currently doesn't play a note.
  441. if(anyFreeChannel == CHANNELINDEX_INVALID)
  442. anyFreeChannel = static_cast<CHANNELINDEX>(i);
  443. }
  444. // If we can't find any free channels, look for the oldest channels
  445. if(channels[i].midiCh == midiCh && channels[i].age < oldestMidiChAge)
  446. {
  447. // Oldest channel matching this MIDI channel
  448. oldestMidiChAge = channels[i].age;
  449. oldsetMidiCh = static_cast<CHANNELINDEX>(i);
  450. } else if(channels[i].age < oldestAnyChAge)
  451. {
  452. // Any oldest channel
  453. oldestAnyChAge = channels[i].age;
  454. oldestAnyCh = static_cast<CHANNELINDEX>(i);
  455. }
  456. }
  457. if(anyUnusedChannel != CHANNELINDEX_INVALID)
  458. return anyUnusedChannel;
  459. if(anyFreeChannel != CHANNELINDEX_INVALID)
  460. return anyFreeChannel;
  461. if(oldsetMidiCh != CHANNELINDEX_INVALID)
  462. return oldsetMidiCh;
  463. return oldestAnyCh;
  464. }
  465. static void MIDINoteOff(MidiChannelState &midiChn, std::vector<ModChannelState> &modChnStatus, uint8 note, uint8 delay, PatternRow patRow, std::bitset<16> drumChns)
  466. {
  467. CHANNELINDEX chn = midiChn.noteOn[note];
  468. if(chn == CHANNELINDEX_INVALID)
  469. return;
  470. if(midiChn.sustain)
  471. {
  472. // Turn this off later
  473. modChnStatus[chn].sustained = true;
  474. return;
  475. }
  476. uint8 midiCh = modChnStatus[chn].midiCh;
  477. modChnStatus[chn].note = NOTE_NONE;
  478. modChnStatus[chn].sustained = false;
  479. midiChn.noteOn[note] = CHANNELINDEX_INVALID;
  480. ModCommand &m = patRow[chn];
  481. if(m.note == NOTE_NONE)
  482. {
  483. m.note = NOTE_KEYOFF;
  484. if(delay != 0)
  485. {
  486. m.command = CMD_S3MCMDEX;
  487. m.param = 0xD0 | delay;
  488. }
  489. } else if(m.IsNote() && !drumChns[midiCh])
  490. {
  491. // Only do note cuts for melodic instruments - they sound weird on drums which should fade out naturally.
  492. if(m.command == CMD_S3MCMDEX && (m.param & 0xF0) == 0xD0)
  493. {
  494. // Already have a note delay
  495. m.command = CMD_DELAYCUT;
  496. m.param = (m.param << 4) | (delay - (m.param & 0x0F));
  497. } else if(m.command == CMD_NONE || m.command == CMD_PANNING8)
  498. {
  499. m.command = CMD_S3MCMDEX;
  500. m.param = 0xC0 | delay;
  501. }
  502. }
  503. }
  504. static void EnterMIDIVolume(ModCommand &m, ModChannelState &modChn, const MidiChannelState &midiChn)
  505. {
  506. m.volcmd = VOLCMD_VOLUME;
  507. int32 vol = CDLSBank::DLSMidiVolumeToLinear(modChn.vol) >> 8;
  508. vol = (vol * midiChn.volume * midiChn.expression) >> 13;
  509. Limit(vol, 4, 256);
  510. m.vol = static_cast<ModCommand::VOL>(vol / 4);
  511. }
  512. CSoundFile::ProbeResult CSoundFile::ProbeFileHeaderMID(MemoryFileReader file, const uint64 *pfilesize)
  513. {
  514. MPT_UNREFERENCED_PARAMETER(pfilesize);
  515. char magic[4];
  516. file.ReadArray(magic);
  517. if(!memcmp(magic, "MThd", 4))
  518. return ProbeSuccess;
  519. if(!memcmp(magic, "RIFF", 4) && file.Skip(4) && file.ReadMagic("RMID"))
  520. return ProbeSuccess;
  521. return ProbeFailure;
  522. }
  523. bool CSoundFile::ReadMID(FileReader &file, ModLoadingFlags loadFlags)
  524. {
  525. file.Rewind();
  526. // Microsoft MIDI files
  527. bool isRIFF = false;
  528. if(file.ReadMagic("RIFF"))
  529. {
  530. file.Skip(4);
  531. if(!file.ReadMagic("RMID"))
  532. {
  533. return false;
  534. } else if(loadFlags == onlyVerifyHeader)
  535. {
  536. return true;
  537. }
  538. do
  539. {
  540. char id[4];
  541. file.ReadArray(id);
  542. uint32 length = file.ReadUint32LE();
  543. if(memcmp(id, "data", 4))
  544. {
  545. file.Skip(length);
  546. } else
  547. {
  548. isRIFF = true;
  549. break;
  550. }
  551. } while(file.CanRead(8));
  552. }
  553. MThd fileHeader;
  554. if(!file.ReadMagic("MThd")
  555. || !file.ReadStruct(fileHeader)
  556. || fileHeader.numTracks == 0
  557. || fileHeader.headerLength < 6
  558. || !file.Skip(fileHeader.headerLength - 6))
  559. {
  560. return false;
  561. } else if(loadFlags == onlyVerifyHeader)
  562. {
  563. return true;
  564. }
  565. InitializeGlobals(MOD_TYPE_MID);
  566. InitializeChannels();
  567. #ifdef MODPLUG_TRACKER
  568. const uint32 quantize = Clamp(TrackerSettings::Instance().midiImportQuantize.Get(), 4u, 256u);
  569. const ROWINDEX patternLen = Clamp(TrackerSettings::Instance().midiImportPatternLen.Get(), ROWINDEX(1), MAX_PATTERN_ROWS);
  570. const uint8 ticksPerRow = Clamp(TrackerSettings::Instance().midiImportTicks.Get(), uint8(2), uint8(16));
  571. #else
  572. const uint32 quantize = 32; // Must be 4 or higher
  573. const ROWINDEX patternLen = 128;
  574. const uint8 ticksPerRow = 16; // Must be in range 2...16
  575. #endif
  576. #ifdef MPT_FUZZ_TRACKER
  577. // Avoid generating test cases that take overly long to evaluate
  578. const ORDERINDEX MPT_MIDI_IMPORT_MAX_ORDERS = 64;
  579. #else
  580. const ORDERINDEX MPT_MIDI_IMPORT_MAX_ORDERS = MAX_ORDERS;
  581. #endif
  582. m_songArtist = U_("MIDI Conversion");
  583. m_modFormat.formatName = U_("Standard MIDI File");
  584. m_modFormat.type = isRIFF ? UL_("rmi") : UL_("mid");
  585. m_modFormat.madeWithTracker = U_("Standard MIDI File");
  586. m_modFormat.charset = mpt::Charset::ISO8859_1;
  587. SetMixLevels(MixLevels::v1_17RC3);
  588. m_nTempoMode = TempoMode::Modern;
  589. m_SongFlags = SONG_LINEARSLIDES;
  590. m_nDefaultTempo.Set(120);
  591. m_nDefaultSpeed = ticksPerRow;
  592. m_nChannels = MAX_BASECHANNELS;
  593. m_nDefaultRowsPerBeat = quantize / 4;
  594. m_nDefaultRowsPerMeasure = 4 * m_nDefaultRowsPerBeat;
  595. m_nSamplePreAmp = m_nVSTiVolume = 32;
  596. TEMPO tempo = m_nDefaultTempo;
  597. uint16 ppqn = fileHeader.division;
  598. if(ppqn & 0x8000)
  599. {
  600. // SMPTE compatible units (approximation)
  601. int frames = 256 - (ppqn >> 8), subFrames = (ppqn & 0xFF);
  602. ppqn = static_cast<uint16>(frames * subFrames / 2);
  603. }
  604. if(!ppqn)
  605. ppqn = 96;
  606. Order().clear();
  607. MidiChannelState midiChnStatus[16];
  608. const CHANNELINDEX tempoChannel = m_nChannels - 2, globalVolChannel = m_nChannels - 1;
  609. const uint16 numTracks = fileHeader.numTracks;
  610. std::vector<TrackState> tracks(numTracks);
  611. std::vector<ModChannelState> modChnStatus(m_nChannels);
  612. std::bitset<16> drumChns;
  613. drumChns.set(MIDI_DRUMCHANNEL - 1);
  614. tick_t timeShift = 0;
  615. for(auto &track : tracks)
  616. {
  617. if(!file.ReadMagic("MTrk"))
  618. return false;
  619. track.track = file.ReadChunk(file.ReadUint32BE());
  620. tick_t delta = 0;
  621. track.track.ReadVarInt(delta);
  622. // Work-around for some MID files that assume that negative deltas exist (they don't according to the standard)
  623. if(delta > int32_max)
  624. timeShift = std::max(static_cast<tick_t>(~delta + 1), timeShift);
  625. track.nextEvent = delta;
  626. }
  627. if(timeShift != 0)
  628. {
  629. for(auto &track : tracks)
  630. {
  631. if(track.nextEvent > int32_max)
  632. track.nextEvent = timeShift - static_cast<tick_t>(~track.nextEvent + 1);
  633. else
  634. track.nextEvent += timeShift;
  635. }
  636. }
  637. uint16 finishedTracks = 0;
  638. PATTERNINDEX emptyPattern = PATTERNINDEX_INVALID;
  639. ORDERINDEX lastOrd = 0, loopEndOrd = ORDERINDEX_INVALID;
  640. ROWINDEX lastRow = 0, loopEndRow = ROWINDEX_INVALID;
  641. ROWINDEX restartRow = ROWINDEX_INVALID;
  642. int8 masterTranspose = 0;
  643. bool isXG = false;
  644. bool isEMIDI = false;
  645. bool isEMIDILoop = false;
  646. const bool isType2 = (fileHeader.format == 2);
  647. const auto ModPositionFromTick = [&](const tick_t tick, const tick_t offset = 0)
  648. {
  649. tick_t modTicks = Util::muldivr_unsigned(tick, quantize * ticksPerRow, ppqn * 4u) - offset;
  650. ORDERINDEX ord = static_cast<ORDERINDEX>((modTicks / ticksPerRow) / patternLen);
  651. ROWINDEX row = (modTicks / ticksPerRow) % patternLen;
  652. uint8 delay = static_cast<uint8>(modTicks % ticksPerRow);
  653. return std::make_tuple(ord, row, delay);
  654. };
  655. while(finishedTracks < numTracks)
  656. {
  657. uint16 t = 0;
  658. tick_t tick = std::numeric_limits<decltype(tick)>::max();
  659. for(uint16 track = 0; track < numTracks; track++)
  660. {
  661. if(!tracks[track].finished && tracks[track].nextEvent < tick)
  662. {
  663. tick = tracks[track].nextEvent;
  664. t = track;
  665. if(isType2)
  666. break;
  667. }
  668. }
  669. FileReader &track = tracks[t].track;
  670. const auto [ord, row, delay] = ModPositionFromTick(tick);
  671. if(ord >= Order().GetLength())
  672. {
  673. if(ord > MPT_MIDI_IMPORT_MAX_ORDERS)
  674. break;
  675. ORDERINDEX curSize = Order().GetLength();
  676. // If we need to extend the order list by more than one pattern, this means that we
  677. // will be filling in empty patterns. Just recycle one empty pattern for this job.
  678. // We read events in chronological order, so it is never possible for the loader to
  679. // "jump back" to one of those empty patterns and write into it.
  680. if(ord > curSize && emptyPattern == PATTERNINDEX_INVALID)
  681. {
  682. if((emptyPattern = Patterns.InsertAny(patternLen)) == PATTERNINDEX_INVALID)
  683. break;
  684. }
  685. Order().resize(ord + 1, emptyPattern);
  686. if((Order()[ord] = Patterns.InsertAny(patternLen)) == PATTERNINDEX_INVALID)
  687. break;
  688. }
  689. // Keep track of position of last event for resizing the last pattern
  690. if(ord > lastOrd)
  691. {
  692. lastOrd = ord;
  693. lastRow = row;
  694. } else if(ord == lastOrd)
  695. {
  696. lastRow = std::max(lastRow, row);
  697. }
  698. PATTERNINDEX pat = Order()[ord];
  699. PatternRow patRow = Patterns[pat].GetRow(row);
  700. uint8 data1 = track.ReadUint8();
  701. if(data1 == 0xFF)
  702. {
  703. // Meta events
  704. data1 = track.ReadUint8();
  705. size_t len = 0;
  706. track.ReadVarInt(len);
  707. FileReader chunk = track.ReadChunk(len);
  708. switch(data1)
  709. {
  710. case 1: // Text
  711. case 2: // Copyright
  712. m_songMessage.Read(chunk, len, SongMessage::leAutodetect);
  713. break;
  714. case 3: // Track Name
  715. if(len > 0)
  716. {
  717. std::string s;
  718. chunk.ReadString<mpt::String::maybeNullTerminated>(s, len);
  719. if(!m_songMessage.empty())
  720. m_songMessage.append(1, SongMessage::InternalLineEnding);
  721. m_songMessage += s;
  722. if(m_songName.empty())
  723. m_songName = s;
  724. }
  725. break;
  726. case 4: // Instrument
  727. case 5: // Lyric
  728. break;
  729. case 6: // Marker
  730. case 7: // Cue point
  731. {
  732. std::string s;
  733. chunk.ReadString<mpt::String::maybeNullTerminated>(s, len);
  734. Patterns[pat].SetName(s);
  735. if(!mpt::CompareNoCaseAscii(s, "loopStart"))
  736. {
  737. Order().SetRestartPos(ord);
  738. restartRow = row;
  739. } else if(!mpt::CompareNoCaseAscii(s, "loopEnd"))
  740. {
  741. std::tie(loopEndOrd, loopEndRow, std::ignore) = ModPositionFromTick(tick, 1);
  742. }
  743. }
  744. break;
  745. case 8: // Patch name
  746. case 9: // Port name
  747. break;
  748. case 0x2F: // End Of Track
  749. tracks[t].finished = true;
  750. break;
  751. case 0x51: // Tempo
  752. {
  753. uint32 tempoInt = chunk.ReadUint24BE();
  754. if(tempoInt == 0)
  755. break;
  756. TEMPO newTempo(60000000.0 / tempoInt);
  757. if(!tick)
  758. {
  759. m_nDefaultTempo = newTempo;
  760. } else if(newTempo != tempo)
  761. {
  762. patRow[tempoChannel].command = CMD_TEMPO;
  763. patRow[tempoChannel].param = mpt::saturate_round<ModCommand::PARAM>(std::max(32.0, newTempo.ToDouble()));
  764. }
  765. tempo = newTempo;
  766. }
  767. break;
  768. default:
  769. break;
  770. }
  771. } else
  772. {
  773. uint8 command = tracks[t].command;
  774. if(data1 & 0x80)
  775. {
  776. // Command byte (if not present, use running status for channel messages)
  777. command = data1;
  778. if(data1 < 0xF0)
  779. {
  780. tracks[t].command = data1;
  781. data1 = track.ReadUint8();
  782. }
  783. }
  784. uint8 midiCh = command & 0x0F;
  785. switch(command & 0xF0)
  786. {
  787. case 0x80: // Note Off
  788. case 0x90: // Note On
  789. {
  790. data1 &= 0x7F;
  791. ModCommand::NOTE note = static_cast<ModCommand::NOTE>(Clamp(data1 + NOTE_MIN, NOTE_MIN, NOTE_MAX));
  792. uint8 data2 = track.ReadUint8();
  793. if(data2 > 0 && (command & 0xF0) == 0x90)
  794. {
  795. // Note On
  796. CHANNELINDEX chn = FindUnusedChannel(midiCh, note, modChnStatus, midiChnStatus[midiCh].monoMode, patRow);
  797. if(chn != CHANNELINDEX_INVALID)
  798. {
  799. modChnStatus[chn].age = tick;
  800. modChnStatus[chn].note = note;
  801. modChnStatus[chn].midiCh = midiCh;
  802. modChnStatus[chn].vol = data2;
  803. modChnStatus[chn].sustained = false;
  804. midiChnStatus[midiCh].noteOn[data1] = chn;
  805. int32 pitchOffset = 0;
  806. if(midiChnStatus[midiCh].pitchbendMod != 0)
  807. {
  808. pitchOffset = (midiChnStatus[midiCh].pitchbendMod + (midiChnStatus[midiCh].pitchbendMod > 0 ? 32 : -32)) / 64;
  809. modChnStatus[chn].porta = pitchOffset * 64;
  810. } else
  811. {
  812. modChnStatus[chn].porta = 0;
  813. }
  814. patRow[chn].note = static_cast<ModCommand::NOTE>(Clamp(note + pitchOffset + midiChnStatus[midiCh].transpose + masterTranspose, NOTE_MIN, NOTE_MAX));
  815. patRow[chn].instr = mpt::saturate_cast<ModCommand::INSTR>(MapMidiInstrument(midiChnStatus[midiCh].program, midiChnStatus[midiCh].bank, midiCh + 1, data1, isXG, drumChns));
  816. EnterMIDIVolume(patRow[chn], modChnStatus[chn], midiChnStatus[midiCh]);
  817. if(patRow[chn].command == CMD_PORTAMENTODOWN || patRow[chn].command == CMD_PORTAMENTOUP)
  818. {
  819. patRow[chn].command = CMD_NONE;
  820. }
  821. if(delay != 0)
  822. {
  823. patRow[chn].command = CMD_S3MCMDEX;
  824. patRow[chn].param = 0xD0 | delay;
  825. }
  826. if(modChnStatus[chn].pan != midiChnStatus[midiCh].pan && patRow[chn].command == CMD_NONE)
  827. {
  828. patRow[chn].command = CMD_PANNING8;
  829. patRow[chn].param = midiChnStatus[midiCh].pan;
  830. modChnStatus[chn].pan = midiChnStatus[midiCh].pan;
  831. }
  832. }
  833. } else
  834. {
  835. // Note Off
  836. MIDINoteOff(midiChnStatus[midiCh], modChnStatus, data1, delay, patRow, drumChns);
  837. }
  838. }
  839. break;
  840. case 0xA0: // Note Aftertouch
  841. {
  842. track.Skip(1);
  843. }
  844. break;
  845. case 0xB0: // Controller
  846. {
  847. uint8 data2 = track.ReadUint8();
  848. switch(data1)
  849. {
  850. case MIDIEvents::MIDICC_Panposition_Coarse:
  851. midiChnStatus[midiCh].pan = data2 * 2u;
  852. for(auto chn : midiChnStatus[midiCh].noteOn)
  853. {
  854. if(chn != CHANNELINDEX_INVALID && modChnStatus[chn].pan != midiChnStatus[midiCh].pan)
  855. {
  856. if(Patterns[pat].WriteEffect(EffectWriter(CMD_PANNING8, midiChnStatus[midiCh].pan).Channel(chn).Row(row)))
  857. {
  858. modChnStatus[chn].pan = midiChnStatus[midiCh].pan;
  859. }
  860. }
  861. }
  862. break;
  863. case MIDIEvents::MIDICC_DataEntry_Coarse:
  864. midiChnStatus[midiCh].SetRPN(data2);
  865. break;
  866. case MIDIEvents::MIDICC_Volume_Coarse:
  867. midiChnStatus[midiCh].volume = (uint8)(CDLSBank::DLSMidiVolumeToLinear(data2) >> 9);
  868. for(auto chn : midiChnStatus[midiCh].noteOn)
  869. {
  870. if(chn != CHANNELINDEX_INVALID)
  871. {
  872. EnterMIDIVolume(patRow[chn], modChnStatus[chn], midiChnStatus[midiCh]);
  873. }
  874. }
  875. break;
  876. case MIDIEvents::MIDICC_Expression_Coarse:
  877. midiChnStatus[midiCh].expression = (uint8)(CDLSBank::DLSMidiVolumeToLinear(data2) >> 9);
  878. for(auto chn : midiChnStatus[midiCh].noteOn)
  879. {
  880. if(chn != CHANNELINDEX_INVALID)
  881. {
  882. EnterMIDIVolume(patRow[chn], modChnStatus[chn], midiChnStatus[midiCh]);
  883. }
  884. }
  885. break;
  886. case MIDIEvents::MIDICC_BankSelect_Coarse:
  887. midiChnStatus[midiCh].bank &= 0x7F;
  888. midiChnStatus[midiCh].bank |= (data2 << 7);
  889. break;
  890. case MIDIEvents::MIDICC_BankSelect_Fine:
  891. midiChnStatus[midiCh].bank &= (0x7F << 7);
  892. midiChnStatus[midiCh].bank |= data2;
  893. break;
  894. case MIDIEvents::MIDICC_HoldPedal_OnOff:
  895. midiChnStatus[midiCh].sustain = (data2 >= 0x40);
  896. if(data2 < 0x40)
  897. {
  898. // Release notes that are still being held after note-off
  899. for(const auto &chnState : modChnStatus)
  900. {
  901. if(chnState.midiCh == midiCh && chnState.sustained && chnState.note != NOTE_NONE)
  902. {
  903. MIDINoteOff(midiChnStatus[midiCh], modChnStatus, chnState.note - NOTE_MIN, delay, patRow, drumChns);
  904. }
  905. }
  906. }
  907. break;
  908. case MIDIEvents::MIDICC_DataButtonincrement:
  909. case MIDIEvents::MIDICC_DataButtondecrement:
  910. midiChnStatus[midiCh].SetRPNRelative((data1 == MIDIEvents::MIDICC_DataButtonincrement) ? 1 : -1);
  911. break;
  912. case MIDIEvents::MIDICC_NonRegisteredParameter_Fine:
  913. case MIDIEvents::MIDICC_NonRegisteredParameter_Coarse:
  914. midiChnStatus[midiCh].rpn = 0x3FFF;
  915. break;
  916. case MIDIEvents::MIDICC_RegisteredParameter_Fine:
  917. midiChnStatus[midiCh].rpn &= (0x7F << 7);
  918. midiChnStatus[midiCh].rpn |= data2;
  919. break;
  920. case MIDIEvents::MIDICC_RegisteredParameter_Coarse:
  921. midiChnStatus[midiCh].rpn &= 0x7F;
  922. midiChnStatus[midiCh].rpn |= (data2 << 7);
  923. break;
  924. case 110:
  925. isEMIDI = true;
  926. break;
  927. case 111:
  928. // Non-standard MIDI loop point. May conflict with Apogee EMIDI CCs (110/111), which is why we also check if CC 110 is ever used.
  929. if(data2 == 0 && !isEMIDI)
  930. {
  931. Order().SetRestartPos(ord);
  932. restartRow = row;
  933. }
  934. break;
  935. case 118:
  936. // EMIDI Global Loop Start
  937. isEMIDI = true;
  938. isEMIDILoop = false;
  939. Order().SetRestartPos(ord);
  940. restartRow = row;
  941. break;
  942. case 119:
  943. // EMIDI Global Loop End
  944. if(data2 == 0x7F)
  945. {
  946. isEMIDILoop = true;
  947. isEMIDI = true;
  948. std::tie(loopEndOrd, loopEndRow, std::ignore) = ModPositionFromTick(tick, 1);
  949. }
  950. break;
  951. case MIDIEvents::MIDICC_AllControllersOff:
  952. midiChnStatus[midiCh].ResetAllControllers();
  953. break;
  954. // Bn.78.00: All Sound Off (GS)
  955. // Bn.7B.00: All Notes Off (GM)
  956. case MIDIEvents::MIDICC_AllSoundOff:
  957. case MIDIEvents::MIDICC_AllNotesOff:
  958. // All Notes Off
  959. midiChnStatus[midiCh].sustain = false;
  960. for(uint8 note = 0; note < 128; note++)
  961. {
  962. MIDINoteOff(midiChnStatus[midiCh], modChnStatus, note, delay, patRow, drumChns);
  963. }
  964. break;
  965. case MIDIEvents::MIDICC_MonoOperation:
  966. if(data2 == 0)
  967. {
  968. midiChnStatus[midiCh].monoMode = true;
  969. }
  970. break;
  971. case MIDIEvents::MIDICC_PolyOperation:
  972. if(data2 == 0)
  973. {
  974. midiChnStatus[midiCh].monoMode = false;
  975. }
  976. break;
  977. }
  978. }
  979. break;
  980. case 0xC0: // Program Change
  981. midiChnStatus[midiCh].program = data1 & 0x7F;
  982. break;
  983. case 0xD0: // Channel aftertouch
  984. break;
  985. case 0xE0: // Pitch bend
  986. midiChnStatus[midiCh].SetPitchbend(data1 | (track.ReadUint8() << 7));
  987. break;
  988. case 0xF0: // General / Immediate
  989. switch(midiCh)
  990. {
  991. case MIDIEvents::sysExStart: // SysEx
  992. case MIDIEvents::sysExEnd: // SysEx (continued)
  993. {
  994. uint32 len;
  995. track.ReadVarInt(len);
  996. FileReader sysex = track.ReadChunk(len);
  997. if(midiCh == MIDIEvents::sysExEnd)
  998. break;
  999. if(sysex.ReadMagic("\x7F\x7F\x04\x01"))
  1000. {
  1001. // Master volume
  1002. uint8 volumeRaw[2];
  1003. sysex.ReadArray(volumeRaw);
  1004. uint16 globalVol = volumeRaw[0] | (volumeRaw[1] << 7);
  1005. if(tick == 0)
  1006. {
  1007. m_nDefaultGlobalVolume = Util::muldivr_unsigned(globalVol, MAX_GLOBAL_VOLUME, 16383);
  1008. } else
  1009. {
  1010. patRow[globalVolChannel].command = CMD_GLOBALVOLUME;
  1011. patRow[globalVolChannel].param = static_cast<ModCommand::PARAM>(Util::muldivr_unsigned(globalVol, 128, 16383));
  1012. }
  1013. } else
  1014. {
  1015. uint8 xg[7];
  1016. sysex.ReadArray(xg);
  1017. if(!memcmp(xg, "\x43\x10\x4C\x00\x00\x7E\x00", 7))
  1018. {
  1019. // XG System On
  1020. isXG = true;
  1021. } else if(!memcmp(xg, "\x43\x10\x4C\x00\x00\x06", 6))
  1022. {
  1023. // XG Master Transpose
  1024. masterTranspose = static_cast<int8>(xg[6]) - 64;
  1025. } else if(!memcmp(xg, "\x41\x10\x42\x12\x40", 5) && (xg[5] & 0xF0) == 0x10 && xg[6] == 0x15)
  1026. {
  1027. // GS Drum Kit
  1028. uint8 chn = xg[5] & 0x0F;
  1029. if(chn == 0)
  1030. chn = 9;
  1031. else if(chn < 10)
  1032. chn--;
  1033. drumChns.set(chn, sysex.ReadUint8() != 0);
  1034. }
  1035. }
  1036. }
  1037. break;
  1038. case MIDIEvents::sysQuarterFrame:
  1039. track.Skip(1);
  1040. break;
  1041. case MIDIEvents::sysPositionPointer:
  1042. track.Skip(2);
  1043. break;
  1044. case MIDIEvents::sysSongSelect:
  1045. track.Skip(1);
  1046. break;
  1047. case MIDIEvents::sysTuneRequest:
  1048. case MIDIEvents::sysMIDIClock:
  1049. case MIDIEvents::sysMIDITick:
  1050. case MIDIEvents::sysStart:
  1051. case MIDIEvents::sysContinue:
  1052. case MIDIEvents::sysStop:
  1053. case MIDIEvents::sysActiveSense:
  1054. case MIDIEvents::sysReset:
  1055. break;
  1056. default:
  1057. break;
  1058. }
  1059. break;
  1060. default:
  1061. break;
  1062. }
  1063. }
  1064. // Pitch bend any channels that haven't reached their target yet
  1065. // TODO: This is currently not called on any rows without events!
  1066. for(size_t chn = 0; chn < modChnStatus.size(); chn++)
  1067. {
  1068. ModChannelState &chnState = modChnStatus[chn];
  1069. ModCommand &m = patRow[chn];
  1070. uint8 midiCh = chnState.midiCh;
  1071. if(chnState.note == NOTE_NONE || m.command == CMD_S3MCMDEX || m.command == CMD_DELAYCUT || midiCh == ModChannelState::NOMIDI)
  1072. continue;
  1073. int32 diff = midiChnStatus[midiCh].pitchbendMod - chnState.porta;
  1074. if(diff == 0)
  1075. continue;
  1076. if(m.command == CMD_PORTAMENTODOWN || m.command == CMD_PORTAMENTOUP)
  1077. {
  1078. // First, undo the effect of an existing portamento command
  1079. int32 porta = 0;
  1080. if(m.param < 0xE0)
  1081. porta = m.param * 4 * (ticksPerRow - 1);
  1082. else if(m.param < 0xF0)
  1083. porta = (m.param & 0x0F);
  1084. else
  1085. porta = (m.param & 0x0F) * 4;
  1086. if(m.command == CMD_PORTAMENTODOWN)
  1087. porta = -porta;
  1088. diff += porta;
  1089. chnState.porta -= porta;
  1090. if(diff == 0)
  1091. {
  1092. m.command = CMD_NONE;
  1093. continue;
  1094. }
  1095. }
  1096. m.command = static_cast<ModCommand::COMMAND>(diff < 0 ? CMD_PORTAMENTODOWN : CMD_PORTAMENTOUP);
  1097. int32 absDiff = std::abs(diff);
  1098. int32 realDiff = 0;
  1099. if(absDiff < 16)
  1100. {
  1101. // Extra-fine slides can do this.
  1102. m.param = 0xE0 | static_cast<uint8>(absDiff);
  1103. realDiff = absDiff;
  1104. } else if(absDiff < 64)
  1105. {
  1106. // Fine slides can do this.
  1107. absDiff = std::min((absDiff + 3) / 4, 0x0F);
  1108. m.param = 0xF0 | static_cast<uint8>(absDiff);
  1109. realDiff = absDiff * 4;
  1110. } else
  1111. {
  1112. // Need a normal slide.
  1113. absDiff /= 4 * (ticksPerRow - 1);
  1114. LimitMax(absDiff, 0xDF);
  1115. m.param = static_cast<uint8>(absDiff);
  1116. realDiff = absDiff * 4 * (ticksPerRow - 1);
  1117. }
  1118. chnState.porta += realDiff * mpt::signum(diff);
  1119. }
  1120. tick_t delta = 0;
  1121. if(track.ReadVarInt(delta) && track.CanRead(1))
  1122. {
  1123. tracks[t].nextEvent += delta;
  1124. } else
  1125. {
  1126. finishedTracks++;
  1127. tracks[t].nextEvent = Util::MaxValueOfType(delta);
  1128. tracks[t].finished = true;
  1129. // Add another sub-song for type-2 files
  1130. if(isType2 && finishedTracks < numTracks)
  1131. {
  1132. if(Order.AddSequence() == SEQUENCEINDEX_INVALID)
  1133. break;
  1134. Order().clear();
  1135. }
  1136. }
  1137. }
  1138. if(isEMIDILoop)
  1139. isEMIDI = false;
  1140. if(isEMIDI)
  1141. {
  1142. Order().SetRestartPos(0);
  1143. }
  1144. if(loopEndOrd == ORDERINDEX_INVALID)
  1145. loopEndOrd = lastOrd;
  1146. if(loopEndRow == ROWINDEX_INVALID)
  1147. loopEndRow = lastRow;
  1148. if(Order().IsValidPat(loopEndOrd))
  1149. {
  1150. PATTERNINDEX lastPat = Order()[loopEndOrd];
  1151. if(loopEndOrd == lastOrd)
  1152. Patterns[lastPat].Resize(loopEndRow + 1);
  1153. if(restartRow != ROWINDEX_INVALID && !isEMIDI)
  1154. {
  1155. Patterns[lastPat].WriteEffect(EffectWriter(CMD_PATTERNBREAK, mpt::saturate_cast<ModCommand::PARAM>(restartRow)).Row(loopEndRow));
  1156. if(ORDERINDEX restartPos = Order().GetRestartPos(); loopEndOrd != lastOrd || restartPos <= std::numeric_limits<ModCommand::PARAM>::max())
  1157. Patterns[lastPat].WriteEffect(EffectWriter(CMD_POSITIONJUMP, mpt::saturate_cast<ModCommand::PARAM>(restartPos)).Row(loopEndRow));
  1158. }
  1159. }
  1160. Order.SetSequence(0);
  1161. std::vector<CHANNELINDEX> channels;
  1162. channels.reserve(m_nChannels);
  1163. for(CHANNELINDEX i = 0; i < m_nChannels; i++)
  1164. {
  1165. if(modChnStatus[i].midiCh != ModChannelState::NOMIDI
  1166. #ifdef MODPLUG_TRACKER
  1167. || (GetpModDoc() != nullptr && !GetpModDoc()->IsChannelUnused(i))
  1168. #endif // MODPLUG_TRACKER
  1169. )
  1170. {
  1171. channels.push_back(i);
  1172. if(modChnStatus[i].midiCh != ModChannelState::NOMIDI)
  1173. ChnSettings[i].szName = MPT_AFORMAT("MIDI Ch {}")(1 + modChnStatus[i].midiCh);
  1174. else if(i == tempoChannel)
  1175. ChnSettings[i].szName = "Tempo";
  1176. else if(i == globalVolChannel)
  1177. ChnSettings[i].szName = "Global Volume";
  1178. }
  1179. }
  1180. if(channels.empty())
  1181. return false;
  1182. #ifdef MODPLUG_TRACKER
  1183. if(GetpModDoc() != nullptr)
  1184. {
  1185. // Keep MIDI channels in patterns neatly grouped
  1186. std::sort(channels.begin(), channels.end(), [&modChnStatus] (CHANNELINDEX c1, CHANNELINDEX c2)
  1187. {
  1188. if(modChnStatus[c1].midiCh == modChnStatus[c2].midiCh)
  1189. return c1 < c2;
  1190. return modChnStatus[c1].midiCh < modChnStatus[c2].midiCh;
  1191. });
  1192. GetpModDoc()->ReArrangeChannels(channels, false);
  1193. GetpModDoc()->m_ShowSavedialog = true;
  1194. }
  1195. std::unique_ptr<CDLSBank> cachedBank, embeddedBank;
  1196. if(CDLSBank::IsDLSBank(file.GetOptionalFileName().value_or(P_(""))))
  1197. {
  1198. // Soundfont embedded in MIDI file
  1199. embeddedBank = std::make_unique<CDLSBank>();
  1200. embeddedBank->Open(file.GetOptionalFileName().value_or(P_("")));
  1201. } else
  1202. {
  1203. // Soundfont with same name as MIDI file
  1204. for(const auto &ext : { P_(".sf2"), P_(".sf3"), P_(".sf4"), P_(".sbk"), P_(".dls") })
  1205. {
  1206. mpt::PathString filename = file.GetOptionalFileName().value_or(P_("")).ReplaceExt(ext);
  1207. if(filename.IsFile())
  1208. {
  1209. embeddedBank = std::make_unique<CDLSBank>();
  1210. if(embeddedBank->Open(filename))
  1211. break;
  1212. }
  1213. }
  1214. }
  1215. ChangeModTypeTo(MOD_TYPE_MPT);
  1216. const MidiLibrary &midiLib = CTrackApp::GetMidiLibrary();
  1217. mpt::PathString cachedBankName;
  1218. // Load Instruments
  1219. for (INSTRUMENTINDEX ins = 1; ins <= m_nInstruments; ins++) if (Instruments[ins])
  1220. {
  1221. ModInstrument *pIns = Instruments[ins];
  1222. uint32 midiCode = 0;
  1223. if(pIns->nMidiChannel == MIDI_DRUMCHANNEL)
  1224. midiCode = 0x80 | (pIns->nMidiDrumKey & 0x7F);
  1225. else if(pIns->nMidiProgram)
  1226. midiCode = (pIns->nMidiProgram - 1) & 0x7F;
  1227. if(embeddedBank && embeddedBank->FindAndExtract(*this, ins, midiCode >= 0x80))
  1228. {
  1229. continue;
  1230. }
  1231. const mpt::PathString &midiMapName = midiLib[midiCode];
  1232. if(!midiMapName.empty())
  1233. {
  1234. // Load from DLS/SF2 Bank
  1235. if(CDLSBank::IsDLSBank(midiMapName))
  1236. {
  1237. CDLSBank *dlsBank = nullptr;
  1238. if(cachedBank != nullptr && !mpt::PathString::CompareNoCase(cachedBankName, midiMapName))
  1239. {
  1240. dlsBank = cachedBank.get();
  1241. } else
  1242. {
  1243. cachedBank = std::make_unique<CDLSBank>();
  1244. cachedBankName = midiMapName;
  1245. if(cachedBank->Open(midiMapName)) dlsBank = cachedBank.get();
  1246. }
  1247. if(dlsBank)
  1248. {
  1249. dlsBank->FindAndExtract(*this, ins, midiCode >= 0x80);
  1250. }
  1251. } else
  1252. {
  1253. // Load from Instrument or Sample file
  1254. InputFile f(midiMapName, SettingCacheCompleteFileBeforeLoading());
  1255. if(f.IsValid())
  1256. {
  1257. FileReader insFile = GetFileReader(f);
  1258. if(ReadInstrumentFromFile(ins, insFile, false))
  1259. {
  1260. mpt::PathString filename = midiMapName.GetFullFileName();
  1261. pIns = Instruments[ins];
  1262. if(!pIns->filename[0]) pIns->filename = filename.ToLocale();
  1263. if(!pIns->name[0])
  1264. {
  1265. if(midiCode < 0x80)
  1266. {
  1267. pIns->name = szMidiProgramNames[midiCode];
  1268. } else
  1269. {
  1270. uint32 key = midiCode & 0x7F;
  1271. if((key >= 24) && (key < 24 + std::size(szMidiPercussionNames)))
  1272. pIns->name = szMidiPercussionNames[key - 24];
  1273. }
  1274. }
  1275. }
  1276. }
  1277. }
  1278. }
  1279. }
  1280. #endif // MODPLUG_TRACKER
  1281. return true;
  1282. }
  1283. #else // !MODPLUG_TRACKER && !MPT_FUZZ_TRACKER
  1284. bool CSoundFile::ReadMID(FileReader &/*file*/, ModLoadingFlags /*loadFlags*/)
  1285. {
  1286. return false;
  1287. }
  1288. #endif
  1289. OPENMPT_NAMESPACE_END