Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

355 lines
11KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2022 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #include "MidiFile.h"
  21. #include "../memory/ByteOrder.h"
  22. #include "../streams/InputStream.h"
  23. #include "../streams/MemoryOutputStream.h"
  24. namespace water {
  25. namespace MidiFileHelpers
  26. {
  27. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) noexcept
  28. {
  29. unsigned int ch = ByteOrder::bigEndianInt (data);
  30. data += 4;
  31. if (ch != ByteOrder::bigEndianInt ("MThd"))
  32. {
  33. bool ok = false;
  34. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  35. {
  36. for (int i = 0; i < 8; ++i)
  37. {
  38. ch = ByteOrder::bigEndianInt (data);
  39. data += 4;
  40. if (ch == ByteOrder::bigEndianInt ("MThd"))
  41. {
  42. ok = true;
  43. break;
  44. }
  45. }
  46. }
  47. if (! ok)
  48. return false;
  49. }
  50. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  51. data += 4;
  52. fileType = (short) ByteOrder::bigEndianShort (data);
  53. data += 2;
  54. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  55. data += 2;
  56. timeFormat = (short) ByteOrder::bigEndianShort (data);
  57. data += 2;
  58. bytesRemaining -= 6;
  59. data += bytesRemaining;
  60. return true;
  61. }
  62. static double convertTicksToSeconds (const double time,
  63. const MidiMessageSequence& tempoEvents,
  64. const int timeFormat)
  65. {
  66. if (timeFormat < 0)
  67. return time / (-(timeFormat >> 8) * (timeFormat & 0xff));
  68. double lastTime = 0.0, correctedTime = 0.0;
  69. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  70. double secsPerTick = 0.5 * tickLen;
  71. const int numEvents = tempoEvents.getNumEvents();
  72. for (int i = 0; i < numEvents; ++i)
  73. {
  74. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  75. const double eventTime = m.getTimeStamp();
  76. if (eventTime >= time)
  77. break;
  78. correctedTime += (eventTime - lastTime) * secsPerTick;
  79. lastTime = eventTime;
  80. if (m.isTempoMetaEvent())
  81. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  82. while (i + 1 < numEvents)
  83. {
  84. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  85. if (m2.getTimeStamp() != eventTime)
  86. break;
  87. if (m2.isTempoMetaEvent())
  88. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  89. ++i;
  90. }
  91. }
  92. return correctedTime + (time - lastTime) * secsPerTick;
  93. }
  94. // a comparator that puts all the note-offs before note-ons that have the same time
  95. struct Sorter
  96. {
  97. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  98. const MidiMessageSequence::MidiEventHolder* const second) noexcept
  99. {
  100. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  101. if (diff > 0) return 1;
  102. if (diff < 0) return -1;
  103. if (first->message.isNoteOff() && second->message.isNoteOn()) return -1;
  104. if (first->message.isNoteOn() && second->message.isNoteOff()) return 1;
  105. return 0;
  106. }
  107. };
  108. template <typename MethodType>
  109. static void findAllMatchingEvents (const OwnedArray<MidiMessageSequence>& tracks,
  110. MidiMessageSequence& results,
  111. MethodType method)
  112. {
  113. for (size_t i = 0; i < tracks.size(); ++i)
  114. {
  115. const MidiMessageSequence& track = *tracks.getUnchecked(i);
  116. const int numEvents = track.getNumEvents();
  117. for (int j = 0; j < numEvents; ++j)
  118. {
  119. const MidiMessage& m = track.getEventPointer(j)->message;
  120. if ((m.*method)())
  121. results.addEvent (m);
  122. }
  123. }
  124. }
  125. }
  126. //==============================================================================
  127. MidiFile::MidiFile()
  128. : timeFormat ((short) (unsigned short) 0xe728)
  129. {
  130. }
  131. MidiFile::~MidiFile()
  132. {
  133. }
  134. MidiFile::MidiFile (const MidiFile& other)
  135. : timeFormat (other.timeFormat)
  136. {
  137. tracks.addCopiesOf (other.tracks);
  138. }
  139. MidiFile& MidiFile::operator= (const MidiFile& other)
  140. {
  141. timeFormat = other.timeFormat;
  142. tracks.clear();
  143. tracks.addCopiesOf (other.tracks);
  144. return *this;
  145. }
  146. void MidiFile::clear()
  147. {
  148. tracks.clear();
  149. }
  150. //==============================================================================
  151. size_t MidiFile::getNumTracks() const noexcept
  152. {
  153. return tracks.size();
  154. }
  155. const MidiMessageSequence* MidiFile::getTrack (const size_t index) const noexcept
  156. {
  157. return tracks [index];
  158. }
  159. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  160. {
  161. tracks.add (new MidiMessageSequence (trackSequence));
  162. }
  163. //==============================================================================
  164. short MidiFile::getTimeFormat() const noexcept
  165. {
  166. return timeFormat;
  167. }
  168. void MidiFile::setTicksPerQuarterNote (const int ticks) noexcept
  169. {
  170. timeFormat = (short) ticks;
  171. }
  172. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  173. const int subframeResolution) noexcept
  174. {
  175. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  176. }
  177. //==============================================================================
  178. void MidiFile::findAllTempoEvents (MidiMessageSequence& results) const
  179. {
  180. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTempoMetaEvent);
  181. }
  182. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& results) const
  183. {
  184. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTimeSignatureMetaEvent);
  185. }
  186. void MidiFile::findAllKeySigEvents (MidiMessageSequence& results) const
  187. {
  188. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isKeySignatureMetaEvent);
  189. }
  190. double MidiFile::getLastTimestamp() const
  191. {
  192. double t = 0.0;
  193. for (size_t i=0; i < tracks.size(); ++i)
  194. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  195. return t;
  196. }
  197. //==============================================================================
  198. bool MidiFile::readFrom (InputStream& sourceStream)
  199. {
  200. clear();
  201. MemoryBlock data;
  202. const int maxSensibleMidiFileSize = 200 * 1024 * 1024;
  203. // (put a sanity-check on the file size, as midi files are generally small)
  204. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  205. {
  206. size_t size = data.getSize();
  207. const uint8* d = static_cast<const uint8*> (data.getData());
  208. short fileType, expectedTracks;
  209. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  210. {
  211. size -= (size_t) (d - static_cast<const uint8*> (data.getData()));
  212. int track = 0;
  213. while (size > 0 && track < expectedTracks)
  214. {
  215. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  216. d += 4;
  217. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  218. d += 4;
  219. if (chunkSize <= 0)
  220. break;
  221. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  222. readNextTrack (d, chunkSize);
  223. size -= (size_t) chunkSize + 8;
  224. d += chunkSize;
  225. ++track;
  226. }
  227. return true;
  228. }
  229. }
  230. return false;
  231. }
  232. void MidiFile::readNextTrack (const uint8* data, int size)
  233. {
  234. double time = 0;
  235. uint8 lastStatusByte = 0;
  236. MidiMessageSequence result;
  237. while (size > 0)
  238. {
  239. int bytesUsed;
  240. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  241. data += bytesUsed;
  242. size -= bytesUsed;
  243. time += delay;
  244. int messSize = 0;
  245. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  246. if (messSize <= 0)
  247. break;
  248. size -= messSize;
  249. data += messSize;
  250. result.addEvent (mm);
  251. const uint8 firstByte = *(mm.getRawData());
  252. if ((firstByte & 0xf0) != 0xf0)
  253. lastStatusByte = firstByte;
  254. }
  255. // use a sort that puts all the note-offs before note-ons that have the same time
  256. MidiFileHelpers::Sorter sorter;
  257. result.list.sort (sorter, true);
  258. addTrack (result);
  259. tracks.getLast()->updateMatchedPairs();
  260. }
  261. //==============================================================================
  262. void MidiFile::convertTimestampTicksToSeconds()
  263. {
  264. MidiMessageSequence tempoEvents;
  265. findAllTempoEvents (tempoEvents);
  266. findAllTimeSigEvents (tempoEvents);
  267. if (timeFormat != 0)
  268. {
  269. for (size_t i = 0; i < tracks.size(); ++i)
  270. {
  271. const MidiMessageSequence& ms = *tracks.getUnchecked(i);
  272. for (int j = ms.getNumEvents(); --j >= 0;)
  273. {
  274. MidiMessage& m = ms.getEventPointer(j)->message;
  275. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(), tempoEvents, timeFormat));
  276. }
  277. }
  278. }
  279. }
  280. }