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.

juce_MidiFile.cpp 13KB

9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
10 years ago
10 years ago
10 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. namespace MidiFileHelpers
  18. {
  19. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  20. {
  21. unsigned int buffer = v & 0x7f;
  22. while ((v >>= 7) != 0)
  23. {
  24. buffer <<= 8;
  25. buffer |= ((v & 0x7f) | 0x80);
  26. }
  27. for (;;)
  28. {
  29. out.writeByte ((char) buffer);
  30. if (buffer & 0x80)
  31. buffer >>= 8;
  32. else
  33. break;
  34. }
  35. }
  36. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) noexcept
  37. {
  38. unsigned int ch = ByteOrder::bigEndianInt (data);
  39. data += 4;
  40. if (ch != ByteOrder::bigEndianInt ("MThd"))
  41. {
  42. bool ok = false;
  43. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  44. {
  45. for (int i = 0; i < 8; ++i)
  46. {
  47. ch = ByteOrder::bigEndianInt (data);
  48. data += 4;
  49. if (ch == ByteOrder::bigEndianInt ("MThd"))
  50. {
  51. ok = true;
  52. break;
  53. }
  54. }
  55. }
  56. if (! ok)
  57. return false;
  58. }
  59. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  60. data += 4;
  61. fileType = (short) ByteOrder::bigEndianShort (data);
  62. data += 2;
  63. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  64. data += 2;
  65. timeFormat = (short) ByteOrder::bigEndianShort (data);
  66. data += 2;
  67. bytesRemaining -= 6;
  68. data += bytesRemaining;
  69. return true;
  70. }
  71. static double convertTicksToSeconds (const double time,
  72. const MidiMessageSequence& tempoEvents,
  73. const int timeFormat)
  74. {
  75. if (timeFormat < 0)
  76. return time / (-(timeFormat >> 8) * (timeFormat & 0xff));
  77. double lastTime = 0.0, correctedTime = 0.0;
  78. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  79. double secsPerTick = 0.5 * tickLen;
  80. const int numEvents = tempoEvents.getNumEvents();
  81. for (int i = 0; i < numEvents; ++i)
  82. {
  83. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  84. const double eventTime = m.getTimeStamp();
  85. if (eventTime >= time)
  86. break;
  87. correctedTime += (eventTime - lastTime) * secsPerTick;
  88. lastTime = eventTime;
  89. if (m.isTempoMetaEvent())
  90. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  91. while (i + 1 < numEvents)
  92. {
  93. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  94. if (m2.getTimeStamp() != eventTime)
  95. break;
  96. if (m2.isTempoMetaEvent())
  97. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  98. ++i;
  99. }
  100. }
  101. return correctedTime + (time - lastTime) * secsPerTick;
  102. }
  103. // a comparator that puts all the note-offs before note-ons that have the same time
  104. struct Sorter
  105. {
  106. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  107. const MidiMessageSequence::MidiEventHolder* const second) noexcept
  108. {
  109. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  110. if (diff > 0) return 1;
  111. if (diff < 0) return -1;
  112. if (first->message.isNoteOff() && second->message.isNoteOn()) return -1;
  113. if (first->message.isNoteOn() && second->message.isNoteOff()) return 1;
  114. return 0;
  115. }
  116. };
  117. template <typename MethodType>
  118. static void findAllMatchingEvents (const OwnedArray<MidiMessageSequence>& tracks,
  119. MidiMessageSequence& results,
  120. MethodType method)
  121. {
  122. for (int i = 0; i < tracks.size(); ++i)
  123. {
  124. const MidiMessageSequence& track = *tracks.getUnchecked(i);
  125. const int numEvents = track.getNumEvents();
  126. for (int j = 0; j < numEvents; ++j)
  127. {
  128. const MidiMessage& m = track.getEventPointer(j)->message;
  129. if ((m.*method)())
  130. results.addEvent (m);
  131. }
  132. }
  133. }
  134. }
  135. //==============================================================================
  136. MidiFile::MidiFile()
  137. : timeFormat ((short) (unsigned short) 0xe728)
  138. {
  139. }
  140. MidiFile::~MidiFile()
  141. {
  142. }
  143. void MidiFile::clear()
  144. {
  145. tracks.clear();
  146. }
  147. //==============================================================================
  148. int MidiFile::getNumTracks() const noexcept
  149. {
  150. return tracks.size();
  151. }
  152. const MidiMessageSequence* MidiFile::getTrack (const int index) const noexcept
  153. {
  154. return tracks [index];
  155. }
  156. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  157. {
  158. tracks.add (new MidiMessageSequence (trackSequence));
  159. }
  160. //==============================================================================
  161. short MidiFile::getTimeFormat() const noexcept
  162. {
  163. return timeFormat;
  164. }
  165. void MidiFile::setTicksPerQuarterNote (const int ticks) noexcept
  166. {
  167. timeFormat = (short) ticks;
  168. }
  169. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  170. const int subframeResolution) noexcept
  171. {
  172. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  173. }
  174. //==============================================================================
  175. void MidiFile::findAllTempoEvents (MidiMessageSequence& results) const
  176. {
  177. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTempoMetaEvent);
  178. }
  179. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& results) const
  180. {
  181. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTimeSignatureMetaEvent);
  182. }
  183. void MidiFile::findAllKeySigEvents (MidiMessageSequence& results) const
  184. {
  185. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isKeySignatureMetaEvent);
  186. }
  187. double MidiFile::getLastTimestamp() const
  188. {
  189. double t = 0.0;
  190. for (int i = tracks.size(); --i >= 0;)
  191. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  192. return t;
  193. }
  194. //==============================================================================
  195. bool MidiFile::readFrom (InputStream& sourceStream)
  196. {
  197. clear();
  198. MemoryBlock data;
  199. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  200. // (put a sanity-check on the file size, as midi files are generally small)
  201. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  202. {
  203. size_t size = data.getSize();
  204. const uint8* d = static_cast <const uint8*> (data.getData());
  205. short fileType, expectedTracks;
  206. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  207. {
  208. size -= (size_t) (d - static_cast <const uint8*> (data.getData()));
  209. int track = 0;
  210. while (size > 0 && track < expectedTracks)
  211. {
  212. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  213. d += 4;
  214. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  215. d += 4;
  216. if (chunkSize <= 0)
  217. break;
  218. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  219. readNextTrack (d, chunkSize);
  220. size -= (size_t) chunkSize + 8;
  221. d += chunkSize;
  222. ++track;
  223. }
  224. return true;
  225. }
  226. }
  227. return false;
  228. }
  229. void MidiFile::readNextTrack (const uint8* data, int size)
  230. {
  231. double time = 0;
  232. uint8 lastStatusByte = 0;
  233. MidiMessageSequence result;
  234. while (size > 0)
  235. {
  236. int bytesUsed;
  237. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  238. data += bytesUsed;
  239. size -= bytesUsed;
  240. time += delay;
  241. int messSize = 0;
  242. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  243. if (messSize <= 0)
  244. break;
  245. size -= messSize;
  246. data += messSize;
  247. result.addEvent (mm);
  248. const uint8 firstByte = *(mm.getRawData());
  249. if ((firstByte & 0xf0) != 0xf0)
  250. lastStatusByte = firstByte;
  251. }
  252. // use a sort that puts all the note-offs before note-ons that have the same time
  253. MidiFileHelpers::Sorter sorter;
  254. result.list.sort (sorter, true);
  255. addTrack (result);
  256. tracks.getLast()->updateMatchedPairs();
  257. }
  258. //==============================================================================
  259. void MidiFile::convertTimestampTicksToSeconds()
  260. {
  261. MidiMessageSequence tempoEvents;
  262. findAllTempoEvents (tempoEvents);
  263. findAllTimeSigEvents (tempoEvents);
  264. if (timeFormat != 0)
  265. {
  266. for (int i = 0; i < tracks.size(); ++i)
  267. {
  268. const MidiMessageSequence& ms = *tracks.getUnchecked(i);
  269. for (int j = ms.getNumEvents(); --j >= 0;)
  270. {
  271. MidiMessage& m = ms.getEventPointer(j)->message;
  272. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(), tempoEvents, timeFormat));
  273. }
  274. }
  275. }
  276. }
  277. //==============================================================================
  278. bool MidiFile::writeTo (OutputStream& out, int midiFileType)
  279. {
  280. jassert (midiFileType >= 0 && midiFileType <= 2);
  281. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  282. out.writeIntBigEndian (6);
  283. out.writeShortBigEndian ((short) midiFileType);
  284. out.writeShortBigEndian ((short) tracks.size());
  285. out.writeShortBigEndian (timeFormat);
  286. for (int i = 0; i < tracks.size(); ++i)
  287. writeTrack (out, i);
  288. out.flush();
  289. return true;
  290. }
  291. void MidiFile::writeTrack (OutputStream& mainOut, const int trackNum)
  292. {
  293. MemoryOutputStream out;
  294. const MidiMessageSequence& ms = *tracks.getUnchecked (trackNum);
  295. int lastTick = 0;
  296. uint8 lastStatusByte = 0;
  297. bool endOfTrackEventWritten = false;
  298. for (int i = 0; i < ms.getNumEvents(); ++i)
  299. {
  300. const MidiMessage& mm = ms.getEventPointer(i)->message;
  301. if (mm.isEndOfTrackMetaEvent())
  302. endOfTrackEventWritten = true;
  303. const int tick = roundToInt (mm.getTimeStamp());
  304. const int delta = jmax (0, tick - lastTick);
  305. MidiFileHelpers::writeVariableLengthInt (out, (uint32) delta);
  306. lastTick = tick;
  307. const uint8* data = mm.getRawData();
  308. int dataSize = mm.getRawDataSize();
  309. const uint8 statusByte = data[0];
  310. if (statusByte == lastStatusByte
  311. && (statusByte & 0xf0) != 0xf0
  312. && dataSize > 1
  313. && i > 0)
  314. {
  315. ++data;
  316. --dataSize;
  317. }
  318. else if (statusByte == 0xf0) // Write sysex message with length bytes.
  319. {
  320. out.writeByte ((char) statusByte);
  321. ++data;
  322. --dataSize;
  323. MidiFileHelpers::writeVariableLengthInt (out, (uint32) dataSize);
  324. }
  325. out.write (data, (size_t) dataSize);
  326. lastStatusByte = statusByte;
  327. }
  328. if (! endOfTrackEventWritten)
  329. {
  330. out.writeByte (0); // (tick delta)
  331. const MidiMessage m (MidiMessage::endOfTrack());
  332. out.write (m.getRawData(), (size_t) m.getRawDataSize());
  333. }
  334. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  335. mainOut.writeIntBigEndian ((int) out.getDataSize());
  336. mainOut << out;
  337. }