The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

1328 lines
50KB

  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 MidiHelpers
  20. {
  21. inline uint8 initialByte (const int type, const int channel) noexcept
  22. {
  23. return (uint8) (type | jlimit (0, 15, channel - 1));
  24. }
  25. inline uint8 validVelocity (const int v) noexcept
  26. {
  27. return (uint8) jlimit (0, 127, v);
  28. }
  29. }
  30. //==============================================================================
  31. uint8 MidiMessage::floatValueToMidiByte (const float v) noexcept
  32. {
  33. jassert (v >= 0 && v <= 1.0f); // if your value is > 1, maybe you're passing an
  34. // integer value to a float method by mistake?
  35. return MidiHelpers::validVelocity (roundToInt (v * 127.0f));
  36. }
  37. uint16 MidiMessage::pitchbendToPitchwheelPos (const float pitchbend,
  38. const float pitchbendRange) noexcept
  39. {
  40. // can't translate a pitchbend value that is outside of the given range!
  41. jassert (std::abs (pitchbend) <= pitchbendRange);
  42. return static_cast<uint16> (pitchbend > 0.0f
  43. ? jmap (pitchbend, 0.0f, pitchbendRange, 8192.0f, 16383.0f)
  44. : jmap (pitchbend, -pitchbendRange, 0.0f, 0.0f, 8192.0f));
  45. }
  46. //==============================================================================
  47. MidiMessage::VariableLengthValue MidiMessage::readVariableLengthValue (const uint8* data, int maxBytesToUse) noexcept
  48. {
  49. uint32 v = 0;
  50. // The largest allowable variable-length value is 0x0f'ff'ff'ff which is
  51. // represented by the 4-byte stream 0xff 0xff 0xff 0x7f.
  52. // Longer bytestreams risk overflowing a 32-bit signed int.
  53. const auto limit = jmin (maxBytesToUse, 4);
  54. for (int numBytesUsed = 0; numBytesUsed < limit; ++numBytesUsed)
  55. {
  56. const auto i = data[numBytesUsed];
  57. v = (v << 7) + (i & 0x7f);
  58. if (! (i & 0x80))
  59. return { (int) v, numBytesUsed + 1 };
  60. }
  61. // If this is hit, the input was malformed. Either there were not enough
  62. // bytes of input to construct a full value, or no terminating byte was
  63. // found. This implementation only supports variable-length values of up
  64. // to four bytes.
  65. jassertfalse;
  66. return {};
  67. }
  68. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) noexcept
  69. {
  70. numBytesUsed = 0;
  71. int v = 0, i;
  72. do
  73. {
  74. i = (int) *data++;
  75. if (++numBytesUsed > 6)
  76. break;
  77. v = (v << 7) + (i & 0x7f);
  78. } while (i & 0x80);
  79. return v;
  80. }
  81. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) noexcept
  82. {
  83. // this method only works for valid starting bytes of a short midi message
  84. jassert (firstByte >= 0x80 && firstByte != 0xf0 && firstByte != 0xf7);
  85. static const char messageLengths[] =
  86. {
  87. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  88. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  89. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  90. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  91. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  92. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  94. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  95. };
  96. return messageLengths[firstByte & 0x7f];
  97. }
  98. //==============================================================================
  99. MidiMessage::MidiMessage() noexcept
  100. : size (2)
  101. {
  102. packedData.asBytes[0] = 0xf0;
  103. packedData.asBytes[1] = 0xf7;
  104. }
  105. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  106. : timeStamp (t), size (dataSize)
  107. {
  108. jassert (dataSize > 0);
  109. // this checks that the length matches the data..
  110. jassert (dataSize > 3 || *(uint8*)d >= 0xf0 || getMessageLengthFromFirstByte (*(uint8*)d) == size);
  111. memcpy (allocateSpace (dataSize), d, (size_t) dataSize);
  112. }
  113. MidiMessage::MidiMessage (const int byte1, const double t) noexcept
  114. : timeStamp (t), size (1)
  115. {
  116. packedData.asBytes[0] = (uint8) byte1;
  117. // check that the length matches the data..
  118. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  119. }
  120. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) noexcept
  121. : timeStamp (t), size (2)
  122. {
  123. packedData.asBytes[0] = (uint8) byte1;
  124. packedData.asBytes[1] = (uint8) byte2;
  125. // check that the length matches the data..
  126. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  127. }
  128. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) noexcept
  129. : timeStamp (t), size (3)
  130. {
  131. packedData.asBytes[0] = (uint8) byte1;
  132. packedData.asBytes[1] = (uint8) byte2;
  133. packedData.asBytes[2] = (uint8) byte3;
  134. // check that the length matches the data..
  135. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  136. }
  137. MidiMessage::MidiMessage (const MidiMessage& other)
  138. : timeStamp (other.timeStamp), size (other.size)
  139. {
  140. if (isHeapAllocated())
  141. memcpy (allocateSpace (size), other.getData(), (size_t) size);
  142. else
  143. packedData.allocatedData = other.packedData.allocatedData;
  144. }
  145. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  146. : timeStamp (newTimeStamp), size (other.size)
  147. {
  148. if (isHeapAllocated())
  149. memcpy (allocateSpace (size), other.getData(), (size_t) size);
  150. else
  151. packedData.allocatedData = other.packedData.allocatedData;
  152. }
  153. MidiMessage::MidiMessage (const void* srcData, int sz, int& numBytesUsed, const uint8 lastStatusByte,
  154. double t, bool sysexHasEmbeddedLength)
  155. : timeStamp (t)
  156. {
  157. auto src = static_cast<const uint8*> (srcData);
  158. auto byte = (unsigned int) *src;
  159. if (byte < 0x80)
  160. {
  161. byte = (unsigned int) lastStatusByte;
  162. numBytesUsed = -1;
  163. }
  164. else
  165. {
  166. numBytesUsed = 0;
  167. --sz;
  168. ++src;
  169. }
  170. if (byte >= 0x80)
  171. {
  172. if (byte == 0xf0)
  173. {
  174. auto d = src;
  175. bool haveReadAllLengthBytes = ! sysexHasEmbeddedLength;
  176. int numVariableLengthSysexBytes = 0;
  177. while (d < src + sz)
  178. {
  179. if (*d >= 0x80)
  180. {
  181. if (*d == 0xf7)
  182. {
  183. ++d; // include the trailing 0xf7 when we hit it
  184. break;
  185. }
  186. if (haveReadAllLengthBytes) // if we see a 0x80 bit set after the initial data length
  187. break; // bytes, assume it's the end of the sysex
  188. ++numVariableLengthSysexBytes;
  189. }
  190. else if (! haveReadAllLengthBytes)
  191. {
  192. haveReadAllLengthBytes = true;
  193. ++numVariableLengthSysexBytes;
  194. }
  195. ++d;
  196. }
  197. src += numVariableLengthSysexBytes;
  198. size = 1 + (int) (d - src);
  199. auto dest = allocateSpace (size);
  200. *dest = (uint8) byte;
  201. memcpy (dest + 1, src, (size_t) (size - 1));
  202. numBytesUsed += (numVariableLengthSysexBytes + size); // (these aren't counted in the size)
  203. }
  204. else if (byte == 0xff)
  205. {
  206. const auto bytesLeft = readVariableLengthValue (src + 1, sz - 1);
  207. size = jmin (sz + 1, bytesLeft.bytesUsed + 2 + bytesLeft.value);
  208. auto dest = allocateSpace (size);
  209. *dest = (uint8) byte;
  210. memcpy (dest + 1, src, (size_t) size - 1);
  211. numBytesUsed += size;
  212. }
  213. else
  214. {
  215. size = getMessageLengthFromFirstByte ((uint8) byte);
  216. packedData.asBytes[0] = (uint8) byte;
  217. if (size > 1)
  218. {
  219. packedData.asBytes[1] = (sz > 0 ? src[0] : 0);
  220. if (size > 2)
  221. packedData.asBytes[2] = (sz > 1 ? src[1] : 0);
  222. }
  223. numBytesUsed += jmin (size, sz + 1);
  224. }
  225. }
  226. else
  227. {
  228. packedData.allocatedData = nullptr;
  229. size = 0;
  230. }
  231. }
  232. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  233. {
  234. if (this != &other)
  235. {
  236. if (other.isHeapAllocated())
  237. {
  238. if (isHeapAllocated())
  239. packedData.allocatedData = static_cast<uint8*> (std::realloc (packedData.allocatedData, (size_t) other.size));
  240. else
  241. packedData.allocatedData = static_cast<uint8*> (std::malloc ((size_t) other.size));
  242. memcpy (packedData.allocatedData, other.packedData.allocatedData, (size_t) other.size);
  243. }
  244. else
  245. {
  246. if (isHeapAllocated())
  247. std::free (packedData.allocatedData);
  248. packedData.allocatedData = other.packedData.allocatedData;
  249. }
  250. timeStamp = other.timeStamp;
  251. size = other.size;
  252. }
  253. return *this;
  254. }
  255. MidiMessage::MidiMessage (MidiMessage&& other) noexcept
  256. : timeStamp (other.timeStamp), size (other.size)
  257. {
  258. packedData.allocatedData = other.packedData.allocatedData;
  259. other.size = 0;
  260. }
  261. MidiMessage& MidiMessage::operator= (MidiMessage&& other) noexcept
  262. {
  263. packedData.allocatedData = other.packedData.allocatedData;
  264. timeStamp = other.timeStamp;
  265. size = other.size;
  266. other.size = 0;
  267. return *this;
  268. }
  269. MidiMessage::~MidiMessage() noexcept
  270. {
  271. if (isHeapAllocated())
  272. std::free (packedData.allocatedData);
  273. }
  274. uint8* MidiMessage::allocateSpace (int bytes)
  275. {
  276. if (bytes > (int) sizeof (packedData))
  277. {
  278. auto d = static_cast<uint8*> (std::malloc ((size_t) bytes));
  279. packedData.allocatedData = d;
  280. return d;
  281. }
  282. return packedData.asBytes;
  283. }
  284. String MidiMessage::getDescription() const
  285. {
  286. if (isNoteOn()) return "Note on " + MidiMessage::getMidiNoteName (getNoteNumber(), true, true, 3) + " Velocity " + String (getVelocity()) + " Channel " + String (getChannel());
  287. if (isNoteOff()) return "Note off " + MidiMessage::getMidiNoteName (getNoteNumber(), true, true, 3) + " Velocity " + String (getVelocity()) + " Channel " + String (getChannel());
  288. if (isProgramChange()) return "Program change " + String (getProgramChangeNumber()) + " Channel " + String (getChannel());
  289. if (isPitchWheel()) return "Pitch wheel " + String (getPitchWheelValue()) + " Channel " + String (getChannel());
  290. if (isAftertouch()) return "Aftertouch " + MidiMessage::getMidiNoteName (getNoteNumber(), true, true, 3) + ": " + String (getAfterTouchValue()) + " Channel " + String (getChannel());
  291. if (isChannelPressure()) return "Channel pressure " + String (getChannelPressureValue()) + " Channel " + String (getChannel());
  292. if (isAllNotesOff()) return "All notes off Channel " + String (getChannel());
  293. if (isAllSoundOff()) return "All sound off Channel " + String (getChannel());
  294. if (isMetaEvent()) return "Meta event";
  295. if (isController())
  296. {
  297. String name (MidiMessage::getControllerName (getControllerNumber()));
  298. if (name.isEmpty())
  299. name = String (getControllerNumber());
  300. return "Controller " + name + ": " + String (getControllerValue()) + " Channel " + String (getChannel());
  301. }
  302. return String::toHexString (getRawData(), getRawDataSize());
  303. }
  304. MidiMessage MidiMessage::withTimeStamp (double newTimestamp) const
  305. {
  306. return { *this, newTimestamp };
  307. }
  308. int MidiMessage::getChannel() const noexcept
  309. {
  310. auto data = getRawData();
  311. if ((data[0] & 0xf0) != 0xf0)
  312. return (data[0] & 0xf) + 1;
  313. return 0;
  314. }
  315. bool MidiMessage::isForChannel (const int channel) const noexcept
  316. {
  317. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  318. auto data = getRawData();
  319. return ((data[0] & 0xf) == channel - 1)
  320. && ((data[0] & 0xf0) != 0xf0);
  321. }
  322. void MidiMessage::setChannel (const int channel) noexcept
  323. {
  324. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  325. auto data = getData();
  326. if ((data[0] & 0xf0) != (uint8) 0xf0)
  327. data[0] = (uint8) ((data[0] & (uint8) 0xf0)
  328. | (uint8)(channel - 1));
  329. }
  330. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const noexcept
  331. {
  332. auto data = getRawData();
  333. return ((data[0] & 0xf0) == 0x90)
  334. && (returnTrueForVelocity0 || data[2] != 0);
  335. }
  336. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const noexcept
  337. {
  338. auto data = getRawData();
  339. return ((data[0] & 0xf0) == 0x80)
  340. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  341. }
  342. bool MidiMessage::isNoteOnOrOff() const noexcept
  343. {
  344. auto d = getRawData()[0] & 0xf0;
  345. return (d == 0x90) || (d == 0x80);
  346. }
  347. int MidiMessage::getNoteNumber() const noexcept
  348. {
  349. return getRawData()[1];
  350. }
  351. void MidiMessage::setNoteNumber (const int newNoteNumber) noexcept
  352. {
  353. if (isNoteOnOrOff() || isAftertouch())
  354. getData()[1] = (uint8) (newNoteNumber & 127);
  355. }
  356. uint8 MidiMessage::getVelocity() const noexcept
  357. {
  358. if (isNoteOnOrOff())
  359. return getRawData()[2];
  360. return 0;
  361. }
  362. float MidiMessage::getFloatVelocity() const noexcept
  363. {
  364. return getVelocity() * (1.0f / 127.0f);
  365. }
  366. void MidiMessage::setVelocity (const float newVelocity) noexcept
  367. {
  368. if (isNoteOnOrOff())
  369. getData()[2] = floatValueToMidiByte (newVelocity);
  370. }
  371. void MidiMessage::multiplyVelocity (const float scaleFactor) noexcept
  372. {
  373. if (isNoteOnOrOff())
  374. {
  375. auto data = getData();
  376. data[2] = MidiHelpers::validVelocity (roundToInt (scaleFactor * data[2]));
  377. }
  378. }
  379. bool MidiMessage::isAftertouch() const noexcept
  380. {
  381. return (getRawData()[0] & 0xf0) == 0xa0;
  382. }
  383. int MidiMessage::getAfterTouchValue() const noexcept
  384. {
  385. jassert (isAftertouch());
  386. return getRawData()[2];
  387. }
  388. MidiMessage MidiMessage::aftertouchChange (const int channel,
  389. const int noteNum,
  390. const int aftertouchValue) noexcept
  391. {
  392. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  393. jassert (isPositiveAndBelow (noteNum, 128));
  394. jassert (isPositiveAndBelow (aftertouchValue, 128));
  395. return MidiMessage (MidiHelpers::initialByte (0xa0, channel),
  396. noteNum & 0x7f,
  397. aftertouchValue & 0x7f);
  398. }
  399. bool MidiMessage::isChannelPressure() const noexcept
  400. {
  401. return (getRawData()[0] & 0xf0) == 0xd0;
  402. }
  403. int MidiMessage::getChannelPressureValue() const noexcept
  404. {
  405. jassert (isChannelPressure());
  406. return getRawData()[1];
  407. }
  408. MidiMessage MidiMessage::channelPressureChange (const int channel, const int pressure) noexcept
  409. {
  410. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  411. jassert (isPositiveAndBelow (pressure, 128));
  412. return MidiMessage (MidiHelpers::initialByte (0xd0, channel), pressure & 0x7f);
  413. }
  414. bool MidiMessage::isSustainPedalOn() const noexcept { return isControllerOfType (0x40) && getRawData()[2] >= 64; }
  415. bool MidiMessage::isSustainPedalOff() const noexcept { return isControllerOfType (0x40) && getRawData()[2] < 64; }
  416. bool MidiMessage::isSostenutoPedalOn() const noexcept { return isControllerOfType (0x42) && getRawData()[2] >= 64; }
  417. bool MidiMessage::isSostenutoPedalOff() const noexcept { return isControllerOfType (0x42) && getRawData()[2] < 64; }
  418. bool MidiMessage::isSoftPedalOn() const noexcept { return isControllerOfType (0x43) && getRawData()[2] >= 64; }
  419. bool MidiMessage::isSoftPedalOff() const noexcept { return isControllerOfType (0x43) && getRawData()[2] < 64; }
  420. bool MidiMessage::isProgramChange() const noexcept
  421. {
  422. return (getRawData()[0] & 0xf0) == 0xc0;
  423. }
  424. int MidiMessage::getProgramChangeNumber() const noexcept
  425. {
  426. jassert (isProgramChange());
  427. return getRawData()[1];
  428. }
  429. MidiMessage MidiMessage::programChange (const int channel, const int programNumber) noexcept
  430. {
  431. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  432. return MidiMessage (MidiHelpers::initialByte (0xc0, channel), programNumber & 0x7f);
  433. }
  434. bool MidiMessage::isPitchWheel() const noexcept
  435. {
  436. return (getRawData()[0] & 0xf0) == 0xe0;
  437. }
  438. int MidiMessage::getPitchWheelValue() const noexcept
  439. {
  440. jassert (isPitchWheel());
  441. auto data = getRawData();
  442. return data[1] | (data[2] << 7);
  443. }
  444. MidiMessage MidiMessage::pitchWheel (const int channel, const int position) noexcept
  445. {
  446. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  447. jassert (isPositiveAndBelow (position, 0x4000));
  448. return MidiMessage (MidiHelpers::initialByte (0xe0, channel),
  449. position & 127, (position >> 7) & 127);
  450. }
  451. bool MidiMessage::isController() const noexcept
  452. {
  453. return (getRawData()[0] & 0xf0) == 0xb0;
  454. }
  455. bool MidiMessage::isControllerOfType (const int controllerType) const noexcept
  456. {
  457. auto data = getRawData();
  458. return (data[0] & 0xf0) == 0xb0 && data[1] == controllerType;
  459. }
  460. int MidiMessage::getControllerNumber() const noexcept
  461. {
  462. jassert (isController());
  463. return getRawData()[1];
  464. }
  465. int MidiMessage::getControllerValue() const noexcept
  466. {
  467. jassert (isController());
  468. return getRawData()[2];
  469. }
  470. MidiMessage MidiMessage::controllerEvent (const int channel, const int controllerType, const int value) noexcept
  471. {
  472. // the channel must be between 1 and 16 inclusive
  473. jassert (channel > 0 && channel <= 16);
  474. return MidiMessage (MidiHelpers::initialByte (0xb0, channel),
  475. controllerType & 127, value & 127);
  476. }
  477. MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const uint8 velocity) noexcept
  478. {
  479. jassert (channel > 0 && channel <= 16);
  480. jassert (isPositiveAndBelow (noteNumber, 128));
  481. return MidiMessage (MidiHelpers::initialByte (0x90, channel),
  482. noteNumber & 127, MidiHelpers::validVelocity (velocity));
  483. }
  484. MidiMessage MidiMessage::noteOn (const int channel, const int noteNumber, const float velocity) noexcept
  485. {
  486. return noteOn (channel, noteNumber, floatValueToMidiByte (velocity));
  487. }
  488. MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, uint8 velocity) noexcept
  489. {
  490. jassert (channel > 0 && channel <= 16);
  491. jassert (isPositiveAndBelow (noteNumber, 128));
  492. return MidiMessage (MidiHelpers::initialByte (0x80, channel),
  493. noteNumber & 127, MidiHelpers::validVelocity (velocity));
  494. }
  495. MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber, float velocity) noexcept
  496. {
  497. return noteOff (channel, noteNumber, floatValueToMidiByte (velocity));
  498. }
  499. MidiMessage MidiMessage::noteOff (const int channel, const int noteNumber) noexcept
  500. {
  501. jassert (channel > 0 && channel <= 16);
  502. jassert (isPositiveAndBelow (noteNumber, 128));
  503. return MidiMessage (MidiHelpers::initialByte (0x80, channel), noteNumber & 127, 0);
  504. }
  505. MidiMessage MidiMessage::allNotesOff (const int channel) noexcept
  506. {
  507. return controllerEvent (channel, 123, 0);
  508. }
  509. bool MidiMessage::isAllNotesOff() const noexcept
  510. {
  511. auto data = getRawData();
  512. return (data[0] & 0xf0) == 0xb0 && data[1] == 123;
  513. }
  514. MidiMessage MidiMessage::allSoundOff (const int channel) noexcept
  515. {
  516. return controllerEvent (channel, 120, 0);
  517. }
  518. bool MidiMessage::isAllSoundOff() const noexcept
  519. {
  520. auto data = getRawData();
  521. return data[1] == 120 && (data[0] & 0xf0) == 0xb0;
  522. }
  523. bool MidiMessage::isResetAllControllers() const noexcept
  524. {
  525. auto data = getRawData();
  526. return (data[0] & 0xf0) == 0xb0 && data[1] == 121;
  527. }
  528. MidiMessage MidiMessage::allControllersOff (const int channel) noexcept
  529. {
  530. return controllerEvent (channel, 121, 0);
  531. }
  532. MidiMessage MidiMessage::masterVolume (const float volume)
  533. {
  534. auto vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  535. return { 0xf0, 0x7f, 0x7f, 0x04, 0x01, vol & 0x7f, vol >> 7, 0xf7 };
  536. }
  537. //==============================================================================
  538. bool MidiMessage::isSysEx() const noexcept
  539. {
  540. return *getRawData() == 0xf0;
  541. }
  542. MidiMessage MidiMessage::createSysExMessage (const void* sysexData, const int dataSize)
  543. {
  544. HeapBlock<uint8> m (dataSize + 2);
  545. m[0] = 0xf0;
  546. memcpy (m + 1, sysexData, (size_t) dataSize);
  547. m[dataSize + 1] = 0xf7;
  548. return MidiMessage (m, dataSize + 2);
  549. }
  550. const uint8* MidiMessage::getSysExData() const noexcept
  551. {
  552. return isSysEx() ? getRawData() + 1 : nullptr;
  553. }
  554. int MidiMessage::getSysExDataSize() const noexcept
  555. {
  556. return isSysEx() ? size - 2 : 0;
  557. }
  558. //==============================================================================
  559. bool MidiMessage::isMetaEvent() const noexcept { return *getRawData() == 0xff; }
  560. bool MidiMessage::isActiveSense() const noexcept { return *getRawData() == 0xfe; }
  561. int MidiMessage::getMetaEventType() const noexcept
  562. {
  563. auto data = getRawData();
  564. return (size < 2 || *data != 0xff) ? -1 : data[1];
  565. }
  566. int MidiMessage::getMetaEventLength() const noexcept
  567. {
  568. auto data = getRawData();
  569. if (*data == 0xff)
  570. {
  571. const auto var = readVariableLengthValue (data + 2, size - 2);
  572. return jmax (0, jmin (size - 2 - var.bytesUsed, var.value));
  573. }
  574. return 0;
  575. }
  576. const uint8* MidiMessage::getMetaEventData() const noexcept
  577. {
  578. jassert (isMetaEvent());
  579. auto d = getRawData() + 2;
  580. const auto var = readVariableLengthValue (d, size - 2);
  581. return d + var.bytesUsed;
  582. }
  583. bool MidiMessage::isTrackMetaEvent() const noexcept { return getMetaEventType() == 0; }
  584. bool MidiMessage::isEndOfTrackMetaEvent() const noexcept { return getMetaEventType() == 47; }
  585. bool MidiMessage::isTextMetaEvent() const noexcept
  586. {
  587. auto t = getMetaEventType();
  588. return t > 0 && t < 16;
  589. }
  590. String MidiMessage::getTextFromTextMetaEvent() const
  591. {
  592. auto textData = reinterpret_cast<const char*> (getMetaEventData());
  593. return String (CharPointer_UTF8 (textData),
  594. CharPointer_UTF8 (textData + getMetaEventLength()));
  595. }
  596. MidiMessage MidiMessage::textMetaEvent (int type, StringRef text)
  597. {
  598. jassert (type > 0 && type < 16);
  599. MidiMessage result;
  600. const size_t textSize = text.text.sizeInBytes() - 1;
  601. uint8 header[8];
  602. size_t n = sizeof (header);
  603. header[--n] = (uint8) (textSize & 0x7f);
  604. for (size_t i = textSize; (i >>= 7) != 0;)
  605. header[--n] = (uint8) ((i & 0x7f) | 0x80);
  606. header[--n] = (uint8) type;
  607. header[--n] = 0xff;
  608. const size_t headerLen = sizeof (header) - n;
  609. const int totalSize = (int) (headerLen + textSize);
  610. auto dest = result.allocateSpace (totalSize);
  611. result.size = totalSize;
  612. memcpy (dest, header + n, headerLen);
  613. memcpy (dest + headerLen, text.text.getAddress(), textSize);
  614. return result;
  615. }
  616. bool MidiMessage::isTrackNameEvent() const noexcept { auto data = getRawData(); return (data[1] == 3) && (*data == 0xff); }
  617. bool MidiMessage::isTempoMetaEvent() const noexcept { auto data = getRawData(); return (data[1] == 81) && (*data == 0xff); }
  618. bool MidiMessage::isMidiChannelMetaEvent() const noexcept { auto data = getRawData(); return (data[1] == 0x20) && (*data == 0xff) && (data[2] == 1); }
  619. int MidiMessage::getMidiChannelMetaEventChannel() const noexcept
  620. {
  621. jassert (isMidiChannelMetaEvent());
  622. return getRawData()[3] + 1;
  623. }
  624. double MidiMessage::getTempoSecondsPerQuarterNote() const noexcept
  625. {
  626. if (! isTempoMetaEvent())
  627. return 0.0;
  628. auto d = getMetaEventData();
  629. return (((unsigned int) d[0] << 16)
  630. | ((unsigned int) d[1] << 8)
  631. | d[2])
  632. / 1000000.0;
  633. }
  634. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const noexcept
  635. {
  636. if (timeFormat > 0)
  637. {
  638. if (! isTempoMetaEvent())
  639. return 0.5 / timeFormat;
  640. return getTempoSecondsPerQuarterNote() / timeFormat;
  641. }
  642. const int frameCode = (-timeFormat) >> 8;
  643. double framesPerSecond;
  644. switch (frameCode)
  645. {
  646. case 24: framesPerSecond = 24.0; break;
  647. case 25: framesPerSecond = 25.0; break;
  648. case 29: framesPerSecond = 30.0 * 1000.0 / 1001.0; break;
  649. case 30: framesPerSecond = 30.0; break;
  650. default: framesPerSecond = 30.0; break;
  651. }
  652. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  653. }
  654. MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) noexcept
  655. {
  656. return { 0xff, 81, 3,
  657. (uint8) (microsecondsPerQuarterNote >> 16),
  658. (uint8) (microsecondsPerQuarterNote >> 8),
  659. (uint8) microsecondsPerQuarterNote };
  660. }
  661. bool MidiMessage::isTimeSignatureMetaEvent() const noexcept
  662. {
  663. auto data = getRawData();
  664. return (data[1] == 0x58) && (*data == (uint8) 0xff);
  665. }
  666. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const noexcept
  667. {
  668. if (isTimeSignatureMetaEvent())
  669. {
  670. auto d = getMetaEventData();
  671. numerator = d[0];
  672. denominator = 1 << d[1];
  673. }
  674. else
  675. {
  676. numerator = 4;
  677. denominator = 4;
  678. }
  679. }
  680. MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  681. {
  682. int n = 1;
  683. int powerOfTwo = 0;
  684. while (n < denominator)
  685. {
  686. n <<= 1;
  687. ++powerOfTwo;
  688. }
  689. return { 0xff, 0x58, 0x04, numerator, powerOfTwo, 1, 96 };
  690. }
  691. MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) noexcept
  692. {
  693. return { 0xff, 0x20, 0x01, jlimit (0, 0xff, channel - 1) };
  694. }
  695. bool MidiMessage::isKeySignatureMetaEvent() const noexcept
  696. {
  697. return getMetaEventType() == 0x59;
  698. }
  699. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const noexcept
  700. {
  701. return (int) (int8) getMetaEventData()[0];
  702. }
  703. bool MidiMessage::isKeySignatureMajorKey() const noexcept
  704. {
  705. return getMetaEventData()[1] == 0;
  706. }
  707. MidiMessage MidiMessage::keySignatureMetaEvent (int numberOfSharpsOrFlats, bool isMinorKey)
  708. {
  709. jassert (numberOfSharpsOrFlats >= -7 && numberOfSharpsOrFlats <= 7);
  710. return { 0xff, 0x59, 0x02, numberOfSharpsOrFlats, isMinorKey ? 1 : 0 };
  711. }
  712. MidiMessage MidiMessage::endOfTrack() noexcept
  713. {
  714. return { 0xff, 0x2f, 0x00 };
  715. }
  716. //==============================================================================
  717. bool MidiMessage::isSongPositionPointer() const noexcept { return *getRawData() == 0xf2; }
  718. int MidiMessage::getSongPositionPointerMidiBeat() const noexcept { auto data = getRawData(); return data[1] | (data[2] << 7); }
  719. MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) noexcept
  720. {
  721. return { 0xf2,
  722. positionInMidiBeats & 127,
  723. (positionInMidiBeats >> 7) & 127 };
  724. }
  725. bool MidiMessage::isMidiStart() const noexcept { return *getRawData() == 0xfa; }
  726. MidiMessage MidiMessage::midiStart() noexcept { return MidiMessage (0xfa); }
  727. bool MidiMessage::isMidiContinue() const noexcept { return *getRawData() == 0xfb; }
  728. MidiMessage MidiMessage::midiContinue() noexcept { return MidiMessage (0xfb); }
  729. bool MidiMessage::isMidiStop() const noexcept { return *getRawData() == 0xfc; }
  730. MidiMessage MidiMessage::midiStop() noexcept { return MidiMessage (0xfc); }
  731. bool MidiMessage::isMidiClock() const noexcept { return *getRawData() == 0xf8; }
  732. MidiMessage MidiMessage::midiClock() noexcept { return MidiMessage (0xf8); }
  733. bool MidiMessage::isQuarterFrame() const noexcept { return *getRawData() == 0xf1; }
  734. int MidiMessage::getQuarterFrameSequenceNumber() const noexcept { return ((int) getRawData()[1]) >> 4; }
  735. int MidiMessage::getQuarterFrameValue() const noexcept { return ((int) getRawData()[1]) & 0x0f; }
  736. MidiMessage MidiMessage::quarterFrame (const int sequenceNumber, const int value) noexcept
  737. {
  738. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  739. }
  740. bool MidiMessage::isFullFrame() const noexcept
  741. {
  742. auto data = getRawData();
  743. return data[0] == 0xf0
  744. && data[1] == 0x7f
  745. && size >= 10
  746. && data[3] == 0x01
  747. && data[4] == 0x01;
  748. }
  749. void MidiMessage::getFullFrameParameters (int& hours, int& minutes, int& seconds, int& frames,
  750. MidiMessage::SmpteTimecodeType& timecodeType) const noexcept
  751. {
  752. jassert (isFullFrame());
  753. auto data = getRawData();
  754. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  755. hours = data[5] & 0x1f;
  756. minutes = data[6];
  757. seconds = data[7];
  758. frames = data[8];
  759. }
  760. MidiMessage MidiMessage::fullFrame (int hours, int minutes, int seconds, int frames,
  761. MidiMessage::SmpteTimecodeType timecodeType)
  762. {
  763. return { 0xf0, 0x7f, 0x7f, 0x01, 0x01,
  764. (hours & 0x01f) | (timecodeType << 5),
  765. minutes, seconds, frames,
  766. 0xf7 };
  767. }
  768. bool MidiMessage::isMidiMachineControlMessage() const noexcept
  769. {
  770. auto data = getRawData();
  771. return data[0] == 0xf0
  772. && data[1] == 0x7f
  773. && data[3] == 0x06
  774. && size > 5;
  775. }
  776. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const noexcept
  777. {
  778. jassert (isMidiMachineControlMessage());
  779. return (MidiMachineControlCommand) getRawData()[4];
  780. }
  781. MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  782. {
  783. return { 0xf0, 0x7f, 0, 6, command, 0xf7 };
  784. }
  785. //==============================================================================
  786. bool MidiMessage::isMidiMachineControlGoto (int& hours, int& minutes, int& seconds, int& frames) const noexcept
  787. {
  788. auto data = getRawData();
  789. if (size >= 12
  790. && data[0] == 0xf0
  791. && data[1] == 0x7f
  792. && data[3] == 0x06
  793. && data[4] == 0x44
  794. && data[5] == 0x06
  795. && data[6] == 0x01)
  796. {
  797. hours = data[7] % 24; // (that some machines send out hours > 24)
  798. minutes = data[8];
  799. seconds = data[9];
  800. frames = data[10];
  801. return true;
  802. }
  803. return false;
  804. }
  805. MidiMessage MidiMessage::midiMachineControlGoto (int hours, int minutes, int seconds, int frames)
  806. {
  807. return { 0xf0, 0x7f, 0, 6, 0x44, 6, 1, hours, minutes, seconds, frames, 0xf7 };
  808. }
  809. //==============================================================================
  810. String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  811. {
  812. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  813. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  814. if (isPositiveAndBelow (note, 128))
  815. {
  816. String s (useSharps ? sharpNoteNames[note % 12]
  817. : flatNoteNames [note % 12]);
  818. if (includeOctaveNumber)
  819. s << (note / 12 + (octaveNumForMiddleC - 5));
  820. return s;
  821. }
  822. return {};
  823. }
  824. double MidiMessage::getMidiNoteInHertz (const int noteNumber, const double frequencyOfA) noexcept
  825. {
  826. return frequencyOfA * std::pow (2.0, (noteNumber - 69) / 12.0);
  827. }
  828. bool MidiMessage::isMidiNoteBlack (int noteNumber) noexcept
  829. {
  830. return ((1 << (noteNumber % 12)) & 0x054a) != 0;
  831. }
  832. const char* MidiMessage::getGMInstrumentName (const int n)
  833. {
  834. static const char* names[] =
  835. {
  836. NEEDS_TRANS("Acoustic Grand Piano"), NEEDS_TRANS("Bright Acoustic Piano"), NEEDS_TRANS("Electric Grand Piano"), NEEDS_TRANS("Honky-tonk Piano"),
  837. NEEDS_TRANS("Electric Piano 1"), NEEDS_TRANS("Electric Piano 2"), NEEDS_TRANS("Harpsichord"), NEEDS_TRANS("Clavinet"),
  838. NEEDS_TRANS("Celesta"), NEEDS_TRANS("Glockenspiel"), NEEDS_TRANS("Music Box"), NEEDS_TRANS("Vibraphone"),
  839. NEEDS_TRANS("Marimba"), NEEDS_TRANS("Xylophone"), NEEDS_TRANS("Tubular Bells"), NEEDS_TRANS("Dulcimer"),
  840. NEEDS_TRANS("Drawbar Organ"), NEEDS_TRANS("Percussive Organ"), NEEDS_TRANS("Rock Organ"), NEEDS_TRANS("Church Organ"),
  841. NEEDS_TRANS("Reed Organ"), NEEDS_TRANS("Accordion"), NEEDS_TRANS("Harmonica"), NEEDS_TRANS("Tango Accordion"),
  842. NEEDS_TRANS("Acoustic Guitar (nylon)"), NEEDS_TRANS("Acoustic Guitar (steel)"), NEEDS_TRANS("Electric Guitar (jazz)"), NEEDS_TRANS("Electric Guitar (clean)"),
  843. NEEDS_TRANS("Electric Guitar (mute)"), NEEDS_TRANS("Overdriven Guitar"), NEEDS_TRANS("Distortion Guitar"), NEEDS_TRANS("Guitar Harmonics"),
  844. NEEDS_TRANS("Acoustic Bass"), NEEDS_TRANS("Electric Bass (finger)"), NEEDS_TRANS("Electric Bass (pick)"), NEEDS_TRANS("Fretless Bass"),
  845. NEEDS_TRANS("Slap Bass 1"), NEEDS_TRANS("Slap Bass 2"), NEEDS_TRANS("Synth Bass 1"), NEEDS_TRANS("Synth Bass 2"),
  846. NEEDS_TRANS("Violin"), NEEDS_TRANS("Viola"), NEEDS_TRANS("Cello"), NEEDS_TRANS("Contrabass"),
  847. NEEDS_TRANS("Tremolo Strings"), NEEDS_TRANS("Pizzicato Strings"), NEEDS_TRANS("Orchestral Harp"), NEEDS_TRANS("Timpani"),
  848. NEEDS_TRANS("String Ensemble 1"), NEEDS_TRANS("String Ensemble 2"), NEEDS_TRANS("SynthStrings 1"), NEEDS_TRANS("SynthStrings 2"),
  849. NEEDS_TRANS("Choir Aahs"), NEEDS_TRANS("Voice Oohs"), NEEDS_TRANS("Synth Voice"), NEEDS_TRANS("Orchestra Hit"),
  850. NEEDS_TRANS("Trumpet"), NEEDS_TRANS("Trombone"), NEEDS_TRANS("Tuba"), NEEDS_TRANS("Muted Trumpet"),
  851. NEEDS_TRANS("French Horn"), NEEDS_TRANS("Brass Section"), NEEDS_TRANS("SynthBrass 1"), NEEDS_TRANS("SynthBrass 2"),
  852. NEEDS_TRANS("Soprano Sax"), NEEDS_TRANS("Alto Sax"), NEEDS_TRANS("Tenor Sax"), NEEDS_TRANS("Baritone Sax"),
  853. NEEDS_TRANS("Oboe"), NEEDS_TRANS("English Horn"), NEEDS_TRANS("Bassoon"), NEEDS_TRANS("Clarinet"),
  854. NEEDS_TRANS("Piccolo"), NEEDS_TRANS("Flute"), NEEDS_TRANS("Recorder"), NEEDS_TRANS("Pan Flute"),
  855. NEEDS_TRANS("Blown Bottle"), NEEDS_TRANS("Shakuhachi"), NEEDS_TRANS("Whistle"), NEEDS_TRANS("Ocarina"),
  856. NEEDS_TRANS("Lead 1 (square)"), NEEDS_TRANS("Lead 2 (sawtooth)"), NEEDS_TRANS("Lead 3 (calliope)"), NEEDS_TRANS("Lead 4 (chiff)"),
  857. NEEDS_TRANS("Lead 5 (charang)"), NEEDS_TRANS("Lead 6 (voice)"), NEEDS_TRANS("Lead 7 (fifths)"), NEEDS_TRANS("Lead 8 (bass+lead)"),
  858. NEEDS_TRANS("Pad 1 (new age)"), NEEDS_TRANS("Pad 2 (warm)"), NEEDS_TRANS("Pad 3 (polysynth)"), NEEDS_TRANS("Pad 4 (choir)"),
  859. NEEDS_TRANS("Pad 5 (bowed)"), NEEDS_TRANS("Pad 6 (metallic)"), NEEDS_TRANS("Pad 7 (halo)"), NEEDS_TRANS("Pad 8 (sweep)"),
  860. NEEDS_TRANS("FX 1 (rain)"), NEEDS_TRANS("FX 2 (soundtrack)"), NEEDS_TRANS("FX 3 (crystal)"), NEEDS_TRANS("FX 4 (atmosphere)"),
  861. NEEDS_TRANS("FX 5 (brightness)"), NEEDS_TRANS("FX 6 (goblins)"), NEEDS_TRANS("FX 7 (echoes)"), NEEDS_TRANS("FX 8 (sci-fi)"),
  862. NEEDS_TRANS("Sitar"), NEEDS_TRANS("Banjo"), NEEDS_TRANS("Shamisen"), NEEDS_TRANS("Koto"),
  863. NEEDS_TRANS("Kalimba"), NEEDS_TRANS("Bag pipe"), NEEDS_TRANS("Fiddle"), NEEDS_TRANS("Shanai"),
  864. NEEDS_TRANS("Tinkle Bell"), NEEDS_TRANS("Agogo"), NEEDS_TRANS("Steel Drums"), NEEDS_TRANS("Woodblock"),
  865. NEEDS_TRANS("Taiko Drum"), NEEDS_TRANS("Melodic Tom"), NEEDS_TRANS("Synth Drum"), NEEDS_TRANS("Reverse Cymbal"),
  866. NEEDS_TRANS("Guitar Fret Noise"), NEEDS_TRANS("Breath Noise"), NEEDS_TRANS("Seashore"), NEEDS_TRANS("Bird Tweet"),
  867. NEEDS_TRANS("Telephone Ring"), NEEDS_TRANS("Helicopter"), NEEDS_TRANS("Applause"), NEEDS_TRANS("Gunshot")
  868. };
  869. return isPositiveAndBelow (n, numElementsInArray (names)) ? names[n] : nullptr;
  870. }
  871. const char* MidiMessage::getGMInstrumentBankName (const int n)
  872. {
  873. static const char* names[] =
  874. {
  875. NEEDS_TRANS("Piano"), NEEDS_TRANS("Chromatic Percussion"), NEEDS_TRANS("Organ"), NEEDS_TRANS("Guitar"),
  876. NEEDS_TRANS("Bass"), NEEDS_TRANS("Strings"), NEEDS_TRANS("Ensemble"), NEEDS_TRANS("Brass"),
  877. NEEDS_TRANS("Reed"), NEEDS_TRANS("Pipe"), NEEDS_TRANS("Synth Lead"), NEEDS_TRANS("Synth Pad"),
  878. NEEDS_TRANS("Synth Effects"), NEEDS_TRANS("Ethnic"), NEEDS_TRANS("Percussive"), NEEDS_TRANS("Sound Effects")
  879. };
  880. return isPositiveAndBelow (n, numElementsInArray (names)) ? names[n] : nullptr;
  881. }
  882. const char* MidiMessage::getRhythmInstrumentName (const int n)
  883. {
  884. static const char* names[] =
  885. {
  886. NEEDS_TRANS("Acoustic Bass Drum"), NEEDS_TRANS("Bass Drum 1"), NEEDS_TRANS("Side Stick"), NEEDS_TRANS("Acoustic Snare"),
  887. NEEDS_TRANS("Hand Clap"), NEEDS_TRANS("Electric Snare"), NEEDS_TRANS("Low Floor Tom"), NEEDS_TRANS("Closed Hi-Hat"),
  888. NEEDS_TRANS("High Floor Tom"), NEEDS_TRANS("Pedal Hi-Hat"), NEEDS_TRANS("Low Tom"), NEEDS_TRANS("Open Hi-Hat"),
  889. NEEDS_TRANS("Low-Mid Tom"), NEEDS_TRANS("Hi-Mid Tom"), NEEDS_TRANS("Crash Cymbal 1"), NEEDS_TRANS("High Tom"),
  890. NEEDS_TRANS("Ride Cymbal 1"), NEEDS_TRANS("Chinese Cymbal"), NEEDS_TRANS("Ride Bell"), NEEDS_TRANS("Tambourine"),
  891. NEEDS_TRANS("Splash Cymbal"), NEEDS_TRANS("Cowbell"), NEEDS_TRANS("Crash Cymbal 2"), NEEDS_TRANS("Vibraslap"),
  892. NEEDS_TRANS("Ride Cymbal 2"), NEEDS_TRANS("Hi Bongo"), NEEDS_TRANS("Low Bongo"), NEEDS_TRANS("Mute Hi Conga"),
  893. NEEDS_TRANS("Open Hi Conga"), NEEDS_TRANS("Low Conga"), NEEDS_TRANS("High Timbale"), NEEDS_TRANS("Low Timbale"),
  894. NEEDS_TRANS("High Agogo"), NEEDS_TRANS("Low Agogo"), NEEDS_TRANS("Cabasa"), NEEDS_TRANS("Maracas"),
  895. NEEDS_TRANS("Short Whistle"), NEEDS_TRANS("Long Whistle"), NEEDS_TRANS("Short Guiro"), NEEDS_TRANS("Long Guiro"),
  896. NEEDS_TRANS("Claves"), NEEDS_TRANS("Hi Wood Block"), NEEDS_TRANS("Low Wood Block"), NEEDS_TRANS("Mute Cuica"),
  897. NEEDS_TRANS("Open Cuica"), NEEDS_TRANS("Mute Triangle"), NEEDS_TRANS("Open Triangle")
  898. };
  899. return (n >= 35 && n <= 81) ? names[n - 35] : nullptr;
  900. }
  901. const char* MidiMessage::getControllerName (const int n)
  902. {
  903. static const char* names[] =
  904. {
  905. NEEDS_TRANS("Bank Select"), NEEDS_TRANS("Modulation Wheel (coarse)"), NEEDS_TRANS("Breath controller (coarse)"),
  906. nullptr,
  907. NEEDS_TRANS("Foot Pedal (coarse)"), NEEDS_TRANS("Portamento Time (coarse)"), NEEDS_TRANS("Data Entry (coarse)"),
  908. NEEDS_TRANS("Volume (coarse)"), NEEDS_TRANS("Balance (coarse)"),
  909. nullptr,
  910. NEEDS_TRANS("Pan position (coarse)"), NEEDS_TRANS("Expression (coarse)"), NEEDS_TRANS("Effect Control 1 (coarse)"),
  911. NEEDS_TRANS("Effect Control 2 (coarse)"),
  912. nullptr, nullptr,
  913. NEEDS_TRANS("General Purpose Slider 1"), NEEDS_TRANS("General Purpose Slider 2"),
  914. NEEDS_TRANS("General Purpose Slider 3"), NEEDS_TRANS("General Purpose Slider 4"),
  915. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
  916. NEEDS_TRANS("Bank Select (fine)"), NEEDS_TRANS("Modulation Wheel (fine)"), NEEDS_TRANS("Breath controller (fine)"),
  917. nullptr,
  918. NEEDS_TRANS("Foot Pedal (fine)"), NEEDS_TRANS("Portamento Time (fine)"), NEEDS_TRANS("Data Entry (fine)"), NEEDS_TRANS("Volume (fine)"),
  919. NEEDS_TRANS("Balance (fine)"), nullptr, NEEDS_TRANS("Pan position (fine)"), NEEDS_TRANS("Expression (fine)"),
  920. NEEDS_TRANS("Effect Control 1 (fine)"), NEEDS_TRANS("Effect Control 2 (fine)"),
  921. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
  922. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
  923. NEEDS_TRANS("Hold Pedal (on/off)"), NEEDS_TRANS("Portamento (on/off)"), NEEDS_TRANS("Sustenuto Pedal (on/off)"), NEEDS_TRANS("Soft Pedal (on/off)"),
  924. NEEDS_TRANS("Legato Pedal (on/off)"), NEEDS_TRANS("Hold 2 Pedal (on/off)"), NEEDS_TRANS("Sound Variation"), NEEDS_TRANS("Sound Timbre"),
  925. NEEDS_TRANS("Sound Release Time"), NEEDS_TRANS("Sound Attack Time"), NEEDS_TRANS("Sound Brightness"), NEEDS_TRANS("Sound Control 6"),
  926. NEEDS_TRANS("Sound Control 7"), NEEDS_TRANS("Sound Control 8"), NEEDS_TRANS("Sound Control 9"), NEEDS_TRANS("Sound Control 10"),
  927. NEEDS_TRANS("General Purpose Button 1 (on/off)"), NEEDS_TRANS("General Purpose Button 2 (on/off)"),
  928. NEEDS_TRANS("General Purpose Button 3 (on/off)"), NEEDS_TRANS("General Purpose Button 4 (on/off)"),
  929. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
  930. NEEDS_TRANS("Reverb Level"), NEEDS_TRANS("Tremolo Level"), NEEDS_TRANS("Chorus Level"), NEEDS_TRANS("Celeste Level"),
  931. NEEDS_TRANS("Phaser Level"), NEEDS_TRANS("Data Button increment"), NEEDS_TRANS("Data Button decrement"), NEEDS_TRANS("Non-registered Parameter (fine)"),
  932. NEEDS_TRANS("Non-registered Parameter (coarse)"), NEEDS_TRANS("Registered Parameter (fine)"), NEEDS_TRANS("Registered Parameter (coarse)"),
  933. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
  934. nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr,
  935. NEEDS_TRANS("All Sound Off"), NEEDS_TRANS("All Controllers Off"), NEEDS_TRANS("Local Keyboard (on/off)"), NEEDS_TRANS("All Notes Off"),
  936. NEEDS_TRANS("Omni Mode Off"), NEEDS_TRANS("Omni Mode On"), NEEDS_TRANS("Mono Operation"), NEEDS_TRANS("Poly Operation")
  937. };
  938. return isPositiveAndBelow (n, numElementsInArray (names)) ? names[n] : nullptr;
  939. }
  940. //==============================================================================
  941. //==============================================================================
  942. #if JUCE_UNIT_TESTS
  943. struct MidiMessageTest : public UnitTest
  944. {
  945. MidiMessageTest()
  946. : UnitTest ("MidiMessage", UnitTestCategories::midi)
  947. {}
  948. void runTest() override
  949. {
  950. using std::begin;
  951. using std::end;
  952. beginTest ("ReadVariableLengthValue should return valid, backward-compatible results");
  953. {
  954. const std::vector<uint8> inputs[]
  955. {
  956. { 0x00 },
  957. { 0x40 },
  958. { 0x7f },
  959. { 0x81, 0x00 },
  960. { 0xc0, 0x00 },
  961. { 0xff, 0x7f },
  962. { 0x81, 0x80, 0x00 },
  963. { 0xc0, 0x80, 0x00 },
  964. { 0xff, 0xff, 0x7f },
  965. { 0x81, 0x80, 0x80, 0x00 },
  966. { 0xc0, 0x80, 0x80, 0x00 },
  967. { 0xff, 0xff, 0xff, 0x7f }
  968. };
  969. const int outputs[]
  970. {
  971. 0x00,
  972. 0x40,
  973. 0x7f,
  974. 0x80,
  975. 0x2000,
  976. 0x3fff,
  977. 0x4000,
  978. 0x100000,
  979. 0x1fffff,
  980. 0x200000,
  981. 0x8000000,
  982. 0xfffffff,
  983. };
  984. expectEquals (std::distance (begin (inputs), end (inputs)),
  985. std::distance (begin (outputs), end (outputs)));
  986. size_t index = 0;
  987. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  988. JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4996)
  989. for (const auto& input : inputs)
  990. {
  991. auto copy = input;
  992. while (copy.size() < 16)
  993. copy.push_back (0);
  994. const auto result = MidiMessage::readVariableLengthValue (copy.data(),
  995. (int) copy.size());
  996. expectEquals (result.value, outputs[index]);
  997. expectEquals (result.bytesUsed, (int) inputs[index].size());
  998. int legacyNumUsed = 0;
  999. const auto legacyResult = MidiMessage::readVariableLengthVal (copy.data(),
  1000. legacyNumUsed);
  1001. expectEquals (result.value, legacyResult);
  1002. expectEquals (result.bytesUsed, legacyNumUsed);
  1003. ++index;
  1004. }
  1005. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1006. JUCE_END_IGNORE_WARNINGS_MSVC
  1007. }
  1008. beginTest ("ReadVariableLengthVal should return 0 if input is truncated");
  1009. {
  1010. for (size_t i = 0; i != 16; ++i)
  1011. {
  1012. std::vector<uint8> input;
  1013. input.resize (i, 0xFF);
  1014. const auto result = MidiMessage::readVariableLengthValue (input.data(),
  1015. (int) input.size());
  1016. expectEquals (result.value, 0);
  1017. expectEquals (result.bytesUsed, 0);
  1018. }
  1019. }
  1020. const std::vector<uint8> metaEvents[]
  1021. {
  1022. // Format is 0xff, followed by a 'kind' byte, followed by a variable-length
  1023. // 'data-length' value, followed by that many data bytes
  1024. { 0xff, 0x00, 0x02, 0x00, 0x00 }, // Sequence number
  1025. { 0xff, 0x01, 0x00 }, // Text event
  1026. { 0xff, 0x02, 0x00 }, // Copyright notice
  1027. { 0xff, 0x03, 0x00 }, // Track name
  1028. { 0xff, 0x04, 0x00 }, // Instrument name
  1029. { 0xff, 0x05, 0x00 }, // Lyric
  1030. { 0xff, 0x06, 0x00 }, // Marker
  1031. { 0xff, 0x07, 0x00 }, // Cue point
  1032. { 0xff, 0x20, 0x01, 0x00 }, // Channel prefix
  1033. { 0xff, 0x2f, 0x00 }, // End of track
  1034. { 0xff, 0x51, 0x03, 0x01, 0x02, 0x03 }, // Set tempo
  1035. { 0xff, 0x54, 0x05, 0x01, 0x02, 0x03, 0x04, 0x05 }, // SMPTE offset
  1036. { 0xff, 0x58, 0x04, 0x01, 0x02, 0x03, 0x04 }, // Time signature
  1037. { 0xff, 0x59, 0x02, 0x01, 0x02 }, // Key signature
  1038. { 0xff, 0x7f, 0x00 }, // Sequencer-specific
  1039. };
  1040. beginTest ("MidiMessage data constructor works for well-formed meta-events");
  1041. {
  1042. const auto status = (uint8) 0x90;
  1043. for (const auto& input : metaEvents)
  1044. {
  1045. int bytesUsed = 0;
  1046. const MidiMessage msg (input.data(), (int) input.size(), bytesUsed, status);
  1047. expect (msg.isMetaEvent());
  1048. expectEquals (msg.getMetaEventLength(), (int) input.size() - 3);
  1049. expectEquals (msg.getMetaEventType(), (int) input[1]);
  1050. }
  1051. }
  1052. beginTest ("MidiMessage data constructor works for malformed meta-events");
  1053. {
  1054. const auto status = (uint8) 0x90;
  1055. const auto runTest = [&] (const std::vector<uint8>& input)
  1056. {
  1057. int bytesUsed = 0;
  1058. const MidiMessage msg (input.data(), (int) input.size(), bytesUsed, status);
  1059. expect (msg.isMetaEvent());
  1060. expectEquals (msg.getMetaEventLength(), jmax (0, (int) input.size() - 3));
  1061. expectEquals (msg.getMetaEventType(), input.size() >= 2 ? input[1] : -1);
  1062. };
  1063. runTest ({ 0xff });
  1064. for (const auto& input : metaEvents)
  1065. {
  1066. auto copy = input;
  1067. copy[2] = 0x40; // Set the size of the message to more bytes than are present
  1068. runTest (copy);
  1069. }
  1070. }
  1071. }
  1072. };
  1073. static MidiMessageTest midiMessageTests;
  1074. #endif
  1075. } // namespace juce