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.

454 lines
14KB

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