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.

451 lines
13KB

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