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.

MidiFile.cpp 14KB

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