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.

juce_MidiFile.cpp 24KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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. template <typename Integral>
  39. struct ReadTrait;
  40. template <>
  41. struct ReadTrait<uint32> { static constexpr auto read = ByteOrder::bigEndianInt; };
  42. template <>
  43. struct ReadTrait<uint16> { static constexpr auto read = ByteOrder::bigEndianShort; };
  44. template <typename Integral>
  45. Optional<Integral> tryRead (const uint8*& data, size_t& remaining)
  46. {
  47. using Trait = ReadTrait<Integral>;
  48. constexpr auto size = sizeof (Integral);
  49. if (remaining < size)
  50. return {};
  51. const Optional<Integral> result { Trait::read (data) };
  52. data += size;
  53. remaining -= size;
  54. return result;
  55. }
  56. struct HeaderDetails
  57. {
  58. size_t bytesRead = 0;
  59. short timeFormat = 0;
  60. short fileType = 0;
  61. short numberOfTracks = 0;
  62. };
  63. static Optional<HeaderDetails> parseMidiHeader (const uint8* const initialData,
  64. const size_t maxSize)
  65. {
  66. auto* data = initialData;
  67. auto remaining = maxSize;
  68. auto ch = tryRead<uint32> (data, remaining);
  69. if (! ch.hasValue())
  70. return {};
  71. if (*ch != ByteOrder::bigEndianInt ("MThd"))
  72. {
  73. auto ok = false;
  74. if (*ch == ByteOrder::bigEndianInt ("RIFF"))
  75. {
  76. for (int i = 0; i < 8; ++i)
  77. {
  78. ch = tryRead<uint32> (data, remaining);
  79. if (! ch.hasValue())
  80. return {};
  81. if (*ch == ByteOrder::bigEndianInt ("MThd"))
  82. {
  83. ok = true;
  84. break;
  85. }
  86. }
  87. }
  88. if (! ok)
  89. return {};
  90. }
  91. const auto bytesRemaining = tryRead<uint32> (data, remaining);
  92. if (! bytesRemaining.hasValue() || *bytesRemaining > remaining)
  93. return {};
  94. const auto optFileType = tryRead<uint16> (data, remaining);
  95. if (! optFileType.hasValue() || 2 < *optFileType)
  96. return {};
  97. const auto optNumTracks = tryRead<uint16> (data, remaining);
  98. if (! optNumTracks.hasValue() || (*optFileType == 0 && *optNumTracks != 1))
  99. return {};
  100. const auto optTimeFormat = tryRead<uint16> (data, remaining);
  101. if (! optTimeFormat.hasValue())
  102. return {};
  103. HeaderDetails result;
  104. result.fileType = (short) *optFileType;
  105. result.timeFormat = (short) *optTimeFormat;
  106. result.numberOfTracks = (short) *optNumTracks;
  107. result.bytesRead = maxSize - remaining;
  108. return { result };
  109. }
  110. static double convertTicksToSeconds (double time,
  111. const MidiMessageSequence& tempoEvents,
  112. int timeFormat)
  113. {
  114. if (timeFormat < 0)
  115. return time / (-(timeFormat >> 8) * (timeFormat & 0xff));
  116. double lastTime = 0, correctedTime = 0;
  117. auto tickLen = 1.0 / (timeFormat & 0x7fff);
  118. auto secsPerTick = 0.5 * tickLen;
  119. auto numEvents = tempoEvents.getNumEvents();
  120. for (int i = 0; i < numEvents; ++i)
  121. {
  122. auto& m = tempoEvents.getEventPointer(i)->message;
  123. auto eventTime = m.getTimeStamp();
  124. if (eventTime >= time)
  125. break;
  126. correctedTime += (eventTime - lastTime) * secsPerTick;
  127. lastTime = eventTime;
  128. if (m.isTempoMetaEvent())
  129. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  130. while (i + 1 < numEvents)
  131. {
  132. auto& m2 = tempoEvents.getEventPointer(i + 1)->message;
  133. if (m2.getTimeStamp() != eventTime)
  134. break;
  135. if (m2.isTempoMetaEvent())
  136. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  137. ++i;
  138. }
  139. }
  140. return correctedTime + (time - lastTime) * secsPerTick;
  141. }
  142. template <typename MethodType>
  143. static void findAllMatchingEvents (const OwnedArray<MidiMessageSequence>& tracks,
  144. MidiMessageSequence& results,
  145. MethodType method)
  146. {
  147. for (auto* track : tracks)
  148. {
  149. auto numEvents = track->getNumEvents();
  150. for (int j = 0; j < numEvents; ++j)
  151. {
  152. auto& m = track->getEventPointer(j)->message;
  153. if ((m.*method)())
  154. results.addEvent (m);
  155. }
  156. }
  157. }
  158. static MidiMessageSequence readTrack (const uint8* data, int size)
  159. {
  160. double time = 0;
  161. uint8 lastStatusByte = 0;
  162. MidiMessageSequence result;
  163. while (size > 0)
  164. {
  165. const auto delay = MidiMessage::readVariableLengthValue (data, (int) size);
  166. if (! delay.isValid())
  167. break;
  168. data += delay.bytesUsed;
  169. size -= delay.bytesUsed;
  170. time += delay.value;
  171. if (size <= 0)
  172. break;
  173. int messSize = 0;
  174. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  175. if (messSize <= 0)
  176. break;
  177. size -= messSize;
  178. data += messSize;
  179. result.addEvent (mm);
  180. auto firstByte = *(mm.getRawData());
  181. if ((firstByte & 0xf0) != 0xf0)
  182. lastStatusByte = firstByte;
  183. }
  184. return result;
  185. }
  186. }
  187. //==============================================================================
  188. MidiFile::MidiFile() : timeFormat ((short) (unsigned short) 0xe728) {}
  189. MidiFile::MidiFile (const MidiFile& other) : timeFormat (other.timeFormat)
  190. {
  191. tracks.addCopiesOf (other.tracks);
  192. }
  193. MidiFile& MidiFile::operator= (const MidiFile& other)
  194. {
  195. tracks.clear();
  196. tracks.addCopiesOf (other.tracks);
  197. timeFormat = other.timeFormat;
  198. return *this;
  199. }
  200. MidiFile::MidiFile (MidiFile&& other)
  201. : tracks (std::move (other.tracks)),
  202. timeFormat (other.timeFormat)
  203. {
  204. }
  205. MidiFile& MidiFile::operator= (MidiFile&& other)
  206. {
  207. tracks = std::move (other.tracks);
  208. timeFormat = other.timeFormat;
  209. return *this;
  210. }
  211. void MidiFile::clear()
  212. {
  213. tracks.clear();
  214. }
  215. //==============================================================================
  216. int MidiFile::getNumTracks() const noexcept
  217. {
  218. return tracks.size();
  219. }
  220. const MidiMessageSequence* MidiFile::getTrack (int index) const noexcept
  221. {
  222. return tracks[index];
  223. }
  224. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  225. {
  226. tracks.add (new MidiMessageSequence (trackSequence));
  227. }
  228. //==============================================================================
  229. short MidiFile::getTimeFormat() const noexcept
  230. {
  231. return timeFormat;
  232. }
  233. void MidiFile::setTicksPerQuarterNote (int ticks) noexcept
  234. {
  235. timeFormat = (short) ticks;
  236. }
  237. void MidiFile::setSmpteTimeFormat (int framesPerSecond, int subframeResolution) noexcept
  238. {
  239. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  240. }
  241. //==============================================================================
  242. void MidiFile::findAllTempoEvents (MidiMessageSequence& results) const
  243. {
  244. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTempoMetaEvent);
  245. }
  246. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& results) const
  247. {
  248. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isTimeSignatureMetaEvent);
  249. }
  250. void MidiFile::findAllKeySigEvents (MidiMessageSequence& results) const
  251. {
  252. MidiFileHelpers::findAllMatchingEvents (tracks, results, &MidiMessage::isKeySignatureMetaEvent);
  253. }
  254. double MidiFile::getLastTimestamp() const
  255. {
  256. double t = 0.0;
  257. for (auto* ms : tracks)
  258. t = jmax (t, ms->getEndTime());
  259. return t;
  260. }
  261. //==============================================================================
  262. bool MidiFile::readFrom (InputStream& sourceStream,
  263. bool createMatchingNoteOffs,
  264. int* fileType)
  265. {
  266. clear();
  267. MemoryBlock data;
  268. const int maxSensibleMidiFileSize = 200 * 1024 * 1024;
  269. // (put a sanity-check on the file size, as midi files are generally small)
  270. if (! sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  271. return false;
  272. auto size = data.getSize();
  273. auto d = static_cast<const uint8*> (data.getData());
  274. const auto optHeader = MidiFileHelpers::parseMidiHeader (d, size);
  275. if (! optHeader.hasValue())
  276. return false;
  277. const auto header = *optHeader;
  278. timeFormat = header.timeFormat;
  279. d += header.bytesRead;
  280. size -= (size_t) header.bytesRead;
  281. for (int track = 0; track < header.numberOfTracks; ++track)
  282. {
  283. const auto optChunkType = MidiFileHelpers::tryRead<uint32> (d, size);
  284. if (! optChunkType.hasValue())
  285. return false;
  286. const auto optChunkSize = MidiFileHelpers::tryRead<uint32> (d, size);
  287. if (! optChunkSize.hasValue())
  288. return false;
  289. const auto chunkSize = *optChunkSize;
  290. if (size < chunkSize)
  291. return false;
  292. if (*optChunkType == ByteOrder::bigEndianInt ("MTrk"))
  293. readNextTrack (d, (int) chunkSize, createMatchingNoteOffs);
  294. size -= chunkSize;
  295. d += chunkSize;
  296. }
  297. const auto successful = (size == 0);
  298. if (successful && fileType != nullptr)
  299. *fileType = header.fileType;
  300. return successful;
  301. }
  302. void MidiFile::readNextTrack (const uint8* data, int size, bool createMatchingNoteOffs)
  303. {
  304. auto sequence = MidiFileHelpers::readTrack (data, size);
  305. // sort so that we put all the note-offs before note-ons that have the same time
  306. std::stable_sort (sequence.list.begin(), sequence.list.end(),
  307. [] (const MidiMessageSequence::MidiEventHolder* a,
  308. const MidiMessageSequence::MidiEventHolder* b)
  309. {
  310. auto t1 = a->message.getTimeStamp();
  311. auto t2 = b->message.getTimeStamp();
  312. if (t1 < t2) return true;
  313. if (t2 < t1) return false;
  314. return a->message.isNoteOff() && b->message.isNoteOn();
  315. });
  316. if (createMatchingNoteOffs)
  317. sequence.updateMatchedPairs();
  318. addTrack (sequence);
  319. }
  320. //==============================================================================
  321. void MidiFile::convertTimestampTicksToSeconds()
  322. {
  323. MidiMessageSequence tempoEvents;
  324. findAllTempoEvents (tempoEvents);
  325. findAllTimeSigEvents (tempoEvents);
  326. if (timeFormat != 0)
  327. {
  328. for (auto* ms : tracks)
  329. {
  330. for (int j = ms->getNumEvents(); --j >= 0;)
  331. {
  332. auto& m = ms->getEventPointer(j)->message;
  333. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(), tempoEvents, timeFormat));
  334. }
  335. }
  336. }
  337. }
  338. //==============================================================================
  339. bool MidiFile::writeTo (OutputStream& out, int midiFileType) const
  340. {
  341. jassert (midiFileType >= 0 && midiFileType <= 2);
  342. if (! out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"))) return false;
  343. if (! out.writeIntBigEndian (6)) return false;
  344. if (! out.writeShortBigEndian ((short) midiFileType)) return false;
  345. if (! out.writeShortBigEndian ((short) tracks.size())) return false;
  346. if (! out.writeShortBigEndian (timeFormat)) return false;
  347. for (auto* ms : tracks)
  348. if (! writeTrack (out, *ms))
  349. return false;
  350. out.flush();
  351. return true;
  352. }
  353. bool MidiFile::writeTrack (OutputStream& mainOut, const MidiMessageSequence& ms) const
  354. {
  355. MemoryOutputStream out;
  356. int lastTick = 0;
  357. uint8 lastStatusByte = 0;
  358. bool endOfTrackEventWritten = false;
  359. for (int i = 0; i < ms.getNumEvents(); ++i)
  360. {
  361. auto& mm = ms.getEventPointer(i)->message;
  362. if (mm.isEndOfTrackMetaEvent())
  363. endOfTrackEventWritten = true;
  364. auto tick = roundToInt (mm.getTimeStamp());
  365. auto delta = jmax (0, tick - lastTick);
  366. MidiFileHelpers::writeVariableLengthInt (out, (uint32) delta);
  367. lastTick = tick;
  368. auto* data = mm.getRawData();
  369. auto dataSize = mm.getRawDataSize();
  370. auto statusByte = data[0];
  371. if (statusByte == lastStatusByte
  372. && (statusByte & 0xf0) != 0xf0
  373. && dataSize > 1
  374. && i > 0)
  375. {
  376. ++data;
  377. --dataSize;
  378. }
  379. else if (statusByte == 0xf0) // Write sysex message with length bytes.
  380. {
  381. out.writeByte ((char) statusByte);
  382. ++data;
  383. --dataSize;
  384. MidiFileHelpers::writeVariableLengthInt (out, (uint32) dataSize);
  385. }
  386. out.write (data, (size_t) dataSize);
  387. lastStatusByte = statusByte;
  388. }
  389. if (! endOfTrackEventWritten)
  390. {
  391. out.writeByte (0); // (tick delta)
  392. auto m = MidiMessage::endOfTrack();
  393. out.write (m.getRawData(), (size_t) m.getRawDataSize());
  394. }
  395. if (! mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"))) return false;
  396. if (! mainOut.writeIntBigEndian ((int) out.getDataSize())) return false;
  397. mainOut << out;
  398. return true;
  399. }
  400. //==============================================================================
  401. //==============================================================================
  402. #if JUCE_UNIT_TESTS
  403. struct MidiFileTest : public UnitTest
  404. {
  405. MidiFileTest()
  406. : UnitTest ("MidiFile", UnitTestCategories::midi)
  407. {}
  408. void runTest() override
  409. {
  410. beginTest ("ReadTrack respects running status");
  411. {
  412. const auto sequence = parseSequence ([] (OutputStream& os)
  413. {
  414. MidiFileHelpers::writeVariableLengthInt (os, 100);
  415. writeBytes (os, { 0x90, 0x40, 0x40 });
  416. MidiFileHelpers::writeVariableLengthInt (os, 200);
  417. writeBytes (os, { 0x40, 0x40 });
  418. MidiFileHelpers::writeVariableLengthInt (os, 300);
  419. writeBytes (os, { 0xff, 0x2f, 0x00 });
  420. });
  421. expectEquals (sequence.getNumEvents(), 3);
  422. expect (sequence.getEventPointer (0)->message.isNoteOn());
  423. expect (sequence.getEventPointer (1)->message.isNoteOn());
  424. expect (sequence.getEventPointer (2)->message.isEndOfTrackMetaEvent());
  425. }
  426. beginTest ("ReadTrack returns available messages if input is truncated");
  427. {
  428. {
  429. const auto sequence = parseSequence ([] (OutputStream& os)
  430. {
  431. // Incomplete delta time
  432. writeBytes (os, { 0xff });
  433. });
  434. expectEquals (sequence.getNumEvents(), 0);
  435. }
  436. {
  437. const auto sequence = parseSequence ([] (OutputStream& os)
  438. {
  439. // Complete delta with no following event
  440. MidiFileHelpers::writeVariableLengthInt (os, 0xffff);
  441. });
  442. expectEquals (sequence.getNumEvents(), 0);
  443. }
  444. {
  445. const auto sequence = parseSequence ([] (OutputStream& os)
  446. {
  447. // Complete delta with malformed following event
  448. MidiFileHelpers::writeVariableLengthInt (os, 0xffff);
  449. writeBytes (os, { 0x90, 0x40 });
  450. });
  451. expectEquals (sequence.getNumEvents(), 1);
  452. expect (sequence.getEventPointer (0)->message.isNoteOff());
  453. expectEquals (sequence.getEventPointer (0)->message.getNoteNumber(), 0x40);
  454. expectEquals (sequence.getEventPointer (0)->message.getVelocity(), (uint8) 0x00);
  455. }
  456. }
  457. beginTest ("Header parsing works");
  458. {
  459. {
  460. // No data
  461. const auto header = parseHeader ([] (OutputStream&) {});
  462. expect (! header.hasValue());
  463. }
  464. {
  465. // Invalid initial byte
  466. const auto header = parseHeader ([] (OutputStream& os)
  467. {
  468. writeBytes (os, { 0xff });
  469. });
  470. expect (! header.hasValue());
  471. }
  472. {
  473. // Type block, but no header data
  474. const auto header = parseHeader ([] (OutputStream& os)
  475. {
  476. writeBytes (os, { 'M', 'T', 'h', 'd' });
  477. });
  478. expect (! header.hasValue());
  479. }
  480. {
  481. // We (ll-formed header, but track type is 0 and channels != 1
  482. const auto header = parseHeader ([] (OutputStream& os)
  483. {
  484. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 0, 0, 16, 0, 1 });
  485. });
  486. expect (! header.hasValue());
  487. }
  488. {
  489. // Well-formed header, but track type is 5
  490. const auto header = parseHeader ([] (OutputStream& os)
  491. {
  492. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 5, 0, 16, 0, 1 });
  493. });
  494. expect (! header.hasValue());
  495. }
  496. {
  497. // Well-formed header
  498. const auto header = parseHeader ([] (OutputStream& os)
  499. {
  500. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 16, 0, 1 });
  501. });
  502. expect (header.hasValue());
  503. expectEquals (header->fileType, (short) 1);
  504. expectEquals (header->numberOfTracks, (short) 16);
  505. expectEquals (header->timeFormat, (short) 1);
  506. expectEquals ((int) header->bytesRead, 14);
  507. }
  508. }
  509. beginTest ("Read from stream");
  510. {
  511. {
  512. // Empty input
  513. const auto file = parseFile ([] (OutputStream&) {});
  514. expect (! file.hasValue());
  515. }
  516. {
  517. // Malformed header
  518. const auto file = parseFile ([] (OutputStream& os)
  519. {
  520. writeBytes (os, { 'M', 'T', 'h', 'd' });
  521. });
  522. expect (! file.hasValue());
  523. }
  524. {
  525. // Header, no channels
  526. const auto file = parseFile ([] (OutputStream& os)
  527. {
  528. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 0, 0, 1 });
  529. });
  530. expect (file.hasValue());
  531. expectEquals (file->getNumTracks(), 0);
  532. }
  533. {
  534. // Header, one malformed channel
  535. const auto file = parseFile ([] (OutputStream& os)
  536. {
  537. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
  538. writeBytes (os, { 'M', 'T', 'r', '?' });
  539. });
  540. expect (! file.hasValue());
  541. }
  542. {
  543. // Header, one channel with malformed message
  544. const auto file = parseFile ([] (OutputStream& os)
  545. {
  546. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
  547. writeBytes (os, { 'M', 'T', 'r', 'k', 0, 0, 0, 1, 0xff });
  548. });
  549. expect (file.hasValue());
  550. expectEquals (file->getNumTracks(), 1);
  551. expectEquals (file->getTrack (0)->getNumEvents(), 0);
  552. }
  553. {
  554. // Header, one channel with incorrect length message
  555. const auto file = parseFile ([] (OutputStream& os)
  556. {
  557. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
  558. writeBytes (os, { 'M', 'T', 'r', 'k', 0x0f, 0, 0, 0, 0xff });
  559. });
  560. expect (! file.hasValue());
  561. }
  562. {
  563. // Header, one channel, all well-formed
  564. const auto file = parseFile ([] (OutputStream& os)
  565. {
  566. writeBytes (os, { 'M', 'T', 'h', 'd', 0, 0, 0, 6, 0, 1, 0, 1, 0, 1 });
  567. writeBytes (os, { 'M', 'T', 'r', 'k', 0, 0, 0, 4 });
  568. MidiFileHelpers::writeVariableLengthInt (os, 0x0f);
  569. writeBytes (os, { 0x80, 0x00, 0x00 });
  570. });
  571. expect (file.hasValue());
  572. expectEquals (file->getNumTracks(), 1);
  573. auto& track = *file->getTrack (0);
  574. expectEquals (track.getNumEvents(), 1);
  575. expect (track.getEventPointer (0)->message.isNoteOff());
  576. expectEquals (track.getEventPointer (0)->message.getTimeStamp(), (double) 0x0f);
  577. }
  578. }
  579. }
  580. template <typename Fn>
  581. static MidiMessageSequence parseSequence (Fn&& fn)
  582. {
  583. MemoryOutputStream os;
  584. fn (os);
  585. return MidiFileHelpers::readTrack (reinterpret_cast<const uint8*> (os.getData()),
  586. (int) os.getDataSize());
  587. }
  588. template <typename Fn>
  589. static Optional<MidiFileHelpers::HeaderDetails> parseHeader (Fn&& fn)
  590. {
  591. MemoryOutputStream os;
  592. fn (os);
  593. return MidiFileHelpers::parseMidiHeader (reinterpret_cast<const uint8*> (os.getData()),
  594. os.getDataSize());
  595. }
  596. template <typename Fn>
  597. static Optional<MidiFile> parseFile (Fn&& fn)
  598. {
  599. MemoryOutputStream os;
  600. fn (os);
  601. MemoryInputStream is (os.getData(), os.getDataSize(), false);
  602. MidiFile mf;
  603. int fileType = 0;
  604. if (mf.readFrom (is, true, &fileType))
  605. return mf;
  606. return {};
  607. }
  608. static void writeBytes (OutputStream& os, const std::vector<uint8>& bytes)
  609. {
  610. for (const auto& byte : bytes)
  611. os.writeByte ((char) byte);
  612. }
  613. };
  614. static MidiFileTest midiFileTests;
  615. #endif
  616. } // namespace juce