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.

447 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  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, uint32 v)
  22. {
  23. auto 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. auto 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. auto 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 (double time,
  74. const MidiMessageSequence& tempoEvents,
  75. int timeFormat)
  76. {
  77. if (timeFormat < 0)
  78. return time / (-(timeFormat >> 8) * (timeFormat & 0xff));
  79. double lastTime = 0, correctedTime = 0;
  80. auto tickLen = 1.0 / (timeFormat & 0x7fff);
  81. auto secsPerTick = 0.5 * tickLen;
  82. auto numEvents = tempoEvents.getNumEvents();
  83. for (int i = 0; i < numEvents; ++i)
  84. {
  85. auto& m = tempoEvents.getEventPointer(i)->message;
  86. auto 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. auto& 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. template <typename MethodType>
  106. static void findAllMatchingEvents (const OwnedArray<MidiMessageSequence>& tracks,
  107. MidiMessageSequence& results,
  108. MethodType method)
  109. {
  110. for (auto* track : tracks)
  111. {
  112. auto numEvents = track->getNumEvents();
  113. for (int j = 0; j < numEvents; ++j)
  114. {
  115. auto& m = track->getEventPointer(j)->message;
  116. if ((m.*method)())
  117. results.addEvent (m);
  118. }
  119. }
  120. }
  121. }
  122. //==============================================================================
  123. MidiFile::MidiFile() : timeFormat ((short) (unsigned short) 0xe728) {}
  124. MidiFile::~MidiFile() {}
  125. MidiFile::MidiFile (const MidiFile& other) : timeFormat (other.timeFormat)
  126. {
  127. tracks.addCopiesOf (other.tracks);
  128. }
  129. MidiFile& MidiFile::operator= (const MidiFile& other)
  130. {
  131. tracks.clear();
  132. tracks.addCopiesOf (other.tracks);
  133. timeFormat = other.timeFormat;
  134. return *this;
  135. }
  136. MidiFile::MidiFile (MidiFile&& other)
  137. : tracks (std::move (other.tracks)),
  138. timeFormat (other.timeFormat)
  139. {
  140. }
  141. MidiFile& MidiFile::operator= (MidiFile&& other)
  142. {
  143. tracks = std::move (other.tracks);
  144. timeFormat = other.timeFormat;
  145. return *this;
  146. }
  147. void MidiFile::clear()
  148. {
  149. tracks.clear();
  150. }
  151. //==============================================================================
  152. int MidiFile::getNumTracks() const noexcept
  153. {
  154. return tracks.size();
  155. }
  156. const MidiMessageSequence* MidiFile::getTrack (int index) const noexcept
  157. {
  158. return tracks[index];
  159. }
  160. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  161. {
  162. tracks.add (new MidiMessageSequence (trackSequence));
  163. }
  164. //==============================================================================
  165. short MidiFile::getTimeFormat() const noexcept
  166. {
  167. return timeFormat;
  168. }
  169. void MidiFile::setTicksPerQuarterNote (int ticks) noexcept
  170. {
  171. timeFormat = (short) ticks;
  172. }
  173. void MidiFile::setSmpteTimeFormat (int framesPerSecond, int subframeResolution) noexcept
  174. {
  175. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  176. }
  177. //==============================================================================
  178. void MidiFile::findAllTempoEvents (MidiMessageSequence& results) const
  179. {
  180. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTempoMetaEvent);
  181. }
  182. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& results) const
  183. {
  184. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTimeSignatureMetaEvent);
  185. }
  186. void MidiFile::findAllKeySigEvents (MidiMessageSequence& results) const
  187. {
  188. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isKeySignatureMetaEvent);
  189. }
  190. double MidiFile::getLastTimestamp() const
  191. {
  192. double t = 0.0;
  193. for (auto* ms : tracks)
  194. t = jmax (t, ms->getEndTime());
  195. return t;
  196. }
  197. //==============================================================================
  198. bool MidiFile::readFrom (InputStream& sourceStream, bool createMatchingNoteOffs)
  199. {
  200. clear();
  201. MemoryBlock data;
  202. const int maxSensibleMidiFileSize = 200 * 1024 * 1024;
  203. // (put a sanity-check on the file size, as midi files are generally small)
  204. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  205. {
  206. auto size = data.getSize();
  207. auto d = static_cast<const uint8*> (data.getData());
  208. short fileType, expectedTracks;
  209. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  210. {
  211. size -= (size_t) (d - static_cast<const uint8*> (data.getData()));
  212. int track = 0;
  213. for (;;)
  214. {
  215. auto chunkType = (int) ByteOrder::bigEndianInt (d);
  216. d += 4;
  217. auto chunkSize = (int) ByteOrder::bigEndianInt (d);
  218. d += 4;
  219. if (chunkSize <= 0 || (size_t) chunkSize > size)
  220. break;
  221. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  222. readNextTrack (d, chunkSize, createMatchingNoteOffs);
  223. if (++track >= expectedTracks)
  224. break;
  225. size -= (size_t) chunkSize + 8;
  226. d += chunkSize;
  227. }
  228. return true;
  229. }
  230. }
  231. return false;
  232. }
  233. void MidiFile::readNextTrack (const uint8* data, int size, bool createMatchingNoteOffs)
  234. {
  235. double time = 0;
  236. uint8 lastStatusByte = 0;
  237. MidiMessageSequence result;
  238. while (size > 0)
  239. {
  240. int bytesUsed;
  241. auto delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  242. data += bytesUsed;
  243. size -= bytesUsed;
  244. time += delay;
  245. int messSize = 0;
  246. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  247. if (messSize <= 0)
  248. break;
  249. size -= messSize;
  250. data += messSize;
  251. result.addEvent (mm);
  252. auto firstByte = *(mm.getRawData());
  253. if ((firstByte & 0xf0) != 0xf0)
  254. lastStatusByte = firstByte;
  255. }
  256. // sort so that we put all the note-offs before note-ons that have the same time
  257. std::stable_sort (result.list.begin(), result.list.end(),
  258. [] (const MidiMessageSequence::MidiEventHolder* a,
  259. const MidiMessageSequence::MidiEventHolder* b)
  260. {
  261. auto t1 = a->message.getTimeStamp();
  262. auto t2 = b->message.getTimeStamp();
  263. if (t1 < t2) return true;
  264. if (t2 < t1) return false;
  265. return a->message.isNoteOff() && b->message.isNoteOn();
  266. });
  267. addTrack (result);
  268. if (createMatchingNoteOffs)
  269. tracks.getLast()->updateMatchedPairs();
  270. }
  271. //==============================================================================
  272. void MidiFile::convertTimestampTicksToSeconds()
  273. {
  274. MidiMessageSequence tempoEvents;
  275. findAllTempoEvents (tempoEvents);
  276. findAllTimeSigEvents (tempoEvents);
  277. if (timeFormat != 0)
  278. {
  279. for (auto* ms : tracks)
  280. {
  281. for (int j = ms->getNumEvents(); --j >= 0;)
  282. {
  283. auto& m = ms->getEventPointer(j)->message;
  284. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(), tempoEvents, timeFormat));
  285. }
  286. }
  287. }
  288. }
  289. //==============================================================================
  290. bool MidiFile::writeTo (OutputStream& out, int midiFileType) const
  291. {
  292. jassert (midiFileType >= 0 && midiFileType <= 2);
  293. if (! out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"))) return false;
  294. if (! out.writeIntBigEndian (6)) return false;
  295. if (! out.writeShortBigEndian ((short) midiFileType)) return false;
  296. if (! out.writeShortBigEndian ((short) tracks.size())) return false;
  297. if (! out.writeShortBigEndian (timeFormat)) return false;
  298. for (auto* ms : tracks)
  299. if (! writeTrack (out, *ms))
  300. return false;
  301. out.flush();
  302. return true;
  303. }
  304. bool MidiFile::writeTrack (OutputStream& mainOut, const MidiMessageSequence& ms) const
  305. {
  306. MemoryOutputStream out;
  307. int lastTick = 0;
  308. uint8 lastStatusByte = 0;
  309. bool endOfTrackEventWritten = false;
  310. for (int i = 0; i < ms.getNumEvents(); ++i)
  311. {
  312. auto& mm = ms.getEventPointer(i)->message;
  313. if (mm.isEndOfTrackMetaEvent())
  314. endOfTrackEventWritten = true;
  315. auto tick = roundToInt (mm.getTimeStamp());
  316. auto delta = jmax (0, tick - lastTick);
  317. MidiFileHelpers::writeVariableLengthInt (out, (uint32) delta);
  318. lastTick = tick;
  319. auto* data = mm.getRawData();
  320. auto dataSize = mm.getRawDataSize();
  321. auto statusByte = data[0];
  322. if (statusByte == lastStatusByte
  323. && (statusByte & 0xf0) != 0xf0
  324. && dataSize > 1
  325. && i > 0)
  326. {
  327. ++data;
  328. --dataSize;
  329. }
  330. else if (statusByte == 0xf0) // Write sysex message with length bytes.
  331. {
  332. out.writeByte ((char) statusByte);
  333. ++data;
  334. --dataSize;
  335. MidiFileHelpers::writeVariableLengthInt (out, (uint32) dataSize);
  336. }
  337. out.write (data, (size_t) dataSize);
  338. lastStatusByte = statusByte;
  339. }
  340. if (! endOfTrackEventWritten)
  341. {
  342. out.writeByte (0); // (tick delta)
  343. auto m = MidiMessage::endOfTrack();
  344. out.write (m.getRawData(), (size_t) m.getRawDataSize());
  345. }
  346. if (! mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"))) return false;
  347. if (! mainOut.writeIntBigEndian ((int) out.getDataSize())) return false;
  348. mainOut << out;
  349. return true;
  350. }
  351. } // namespace juce