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.

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