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.

723 lines
15KB

  1. #pragma once
  2. #include <dsp/common.hpp>
  3. #include <dsp/filter.hpp>
  4. #include <dsp/digital.hpp>
  5. #include <midi.hpp>
  6. #include <jansson.h>
  7. namespace rack {
  8. namespace dsp {
  9. /** Converts gates and CV to MIDI messages.
  10. CHANNELS is the number of polyphony channels. Use 1 for monophonic.
  11. */
  12. template <int CHANNELS>
  13. struct MidiGenerator {
  14. int8_t vels[CHANNELS];
  15. int8_t notes[CHANNELS];
  16. bool gates[CHANNELS];
  17. int8_t keyPressures[CHANNELS];
  18. int8_t channelPressure;
  19. int8_t ccs[128];
  20. int16_t pw;
  21. bool clk;
  22. bool start;
  23. bool stop;
  24. bool cont;
  25. int64_t frame = -1;
  26. MidiGenerator() {
  27. reset();
  28. }
  29. void reset() {
  30. for (int c = 0; c < CHANNELS; c++) {
  31. vels[c] = 100;
  32. notes[c] = 60;
  33. gates[c] = false;
  34. keyPressures[c] = -1;
  35. }
  36. channelPressure = -1;
  37. for (int i = 0; i < 128; i++) {
  38. ccs[i] = -1;
  39. }
  40. pw = 0x2000;
  41. clk = false;
  42. start = false;
  43. stop = false;
  44. cont = false;
  45. }
  46. void panic() {
  47. reset();
  48. // Send all note off commands
  49. for (int note = 0; note <= 127; note++) {
  50. // Note off
  51. midi::Message m;
  52. m.setStatus(0x8);
  53. m.setNote(note);
  54. m.setValue(0);
  55. m.setFrame(frame);
  56. onMessage(m);
  57. }
  58. }
  59. /** Must be called before setNoteGate(). */
  60. void setVelocity(int8_t vel, int c) {
  61. vels[c] = vel;
  62. }
  63. void setNoteGate(int8_t note, bool gate, int c) {
  64. bool changedNote = gate && gates[c] && (note != notes[c]);
  65. bool enabledGate = gate && !gates[c];
  66. bool disabledGate = !gate && gates[c];
  67. if (changedNote || disabledGate) {
  68. // Note off
  69. midi::Message m;
  70. m.setStatus(0x8);
  71. m.setNote(notes[c]);
  72. m.setValue(vels[c]);
  73. m.setFrame(frame);
  74. onMessage(m);
  75. }
  76. if (changedNote || enabledGate) {
  77. // Note on
  78. midi::Message m;
  79. m.setStatus(0x9);
  80. m.setNote(note);
  81. m.setValue(vels[c]);
  82. m.setFrame(frame);
  83. onMessage(m);
  84. }
  85. notes[c] = note;
  86. gates[c] = gate;
  87. }
  88. void setKeyPressure(int8_t val, int c) {
  89. if (keyPressures[c] == val)
  90. return;
  91. keyPressures[c] = val;
  92. // Polyphonic key pressure
  93. midi::Message m;
  94. m.setStatus(0xa);
  95. m.setNote(notes[c]);
  96. m.setValue(val);
  97. m.setFrame(frame);
  98. onMessage(m);
  99. }
  100. void setChannelPressure(int8_t val) {
  101. if (channelPressure == val)
  102. return;
  103. channelPressure = val;
  104. // Channel pressure
  105. midi::Message m;
  106. m.setSize(2);
  107. m.setStatus(0xd);
  108. m.setNote(val);
  109. m.setFrame(frame);
  110. onMessage(m);
  111. }
  112. void setCc(int8_t cc, int id) {
  113. if (ccs[id] == cc)
  114. return;
  115. ccs[id] = cc;
  116. // Continuous controller
  117. midi::Message m;
  118. m.setStatus(0xb);
  119. m.setNote(id);
  120. m.setValue(cc);
  121. m.setFrame(frame);
  122. onMessage(m);
  123. }
  124. void setModWheel(int8_t cc) {
  125. setCc(cc, 0x01);
  126. }
  127. void setVolume(int8_t cc) {
  128. setCc(cc, 0x07);
  129. }
  130. void setBalance(int8_t cc) {
  131. setCc(cc, 0x08);
  132. }
  133. void setPan(int8_t cc) {
  134. setCc(cc, 0x0a);
  135. }
  136. void setSustainPedal(int8_t cc) {
  137. setCc(cc, 0x40);
  138. }
  139. void setPitchWheel(int16_t pw) {
  140. if (this->pw == pw)
  141. return;
  142. this->pw = pw;
  143. // Pitch wheel
  144. midi::Message m;
  145. m.setStatus(0xe);
  146. m.setNote(pw & 0x7f);
  147. m.setValue((pw >> 7) & 0x7f);
  148. m.setFrame(frame);
  149. onMessage(m);
  150. }
  151. void setClock(bool clk) {
  152. if (this->clk == clk)
  153. return;
  154. this->clk = clk;
  155. if (clk) {
  156. // Timing clock
  157. midi::Message m;
  158. m.setSize(1);
  159. m.setStatus(0xf);
  160. m.setChannel(0x8);
  161. m.setFrame(frame);
  162. onMessage(m);
  163. }
  164. }
  165. void setStart(bool start) {
  166. if (this->start == start)
  167. return;
  168. this->start = start;
  169. if (start) {
  170. // Start
  171. midi::Message m;
  172. m.setSize(1);
  173. m.setStatus(0xf);
  174. m.setChannel(0xa);
  175. m.setFrame(frame);
  176. onMessage(m);
  177. }
  178. }
  179. void setContinue(bool cont) {
  180. if (this->cont == cont)
  181. return;
  182. this->cont = cont;
  183. if (cont) {
  184. // Continue
  185. midi::Message m;
  186. m.setSize(1);
  187. m.setStatus(0xf);
  188. m.setChannel(0xb);
  189. m.setFrame(frame);
  190. onMessage(m);
  191. }
  192. }
  193. void setStop(bool stop) {
  194. if (this->stop == stop)
  195. return;
  196. this->stop = stop;
  197. if (stop) {
  198. // Stop
  199. midi::Message m;
  200. m.setSize(1);
  201. m.setStatus(0xf);
  202. m.setChannel(0xc);
  203. m.setFrame(frame);
  204. onMessage(m);
  205. }
  206. }
  207. void setFrame(int64_t frame) {
  208. this->frame = frame;
  209. }
  210. virtual void onMessage(const midi::Message& message) {}
  211. };
  212. /** Converts MIDI note and transport messages to gates, CV, and other states.
  213. MAX_CHANNELS is the maximum number of polyphonic channels.
  214. */
  215. template <uint8_t MAX_CHANNELS>
  216. struct MidiParser {
  217. // Settings
  218. /** Number of semitones to bend up/down by pitch wheel */
  219. float pwRange;
  220. /** Enables pitch-wheel and mod-wheel exponential smoothing */
  221. bool smooth;
  222. /** Number of 24 PPQN clocks between clock divider pulses */
  223. uint32_t clockDivision;
  224. /** Actual number of polyphonic channels */
  225. uint8_t channels;
  226. /** Method for assigning notes to polyphony channels */
  227. enum PolyMode {
  228. ROTATE_MODE,
  229. REUSE_MODE,
  230. RESET_MODE,
  231. MPE_MODE,
  232. NUM_POLY_MODES
  233. };
  234. PolyMode polyMode;
  235. // States
  236. /** Clock index from song start */
  237. int64_t clock;
  238. /** Whether sustain pedal is held. */
  239. bool pedal;
  240. uint8_t notes[MAX_CHANNELS];
  241. bool gates[MAX_CHANNELS];
  242. uint8_t velocities[MAX_CHANNELS];
  243. uint8_t aftertouches[MAX_CHANNELS];
  244. std::vector<uint8_t> heldNotes;
  245. int8_t rotateIndex;
  246. /** Pitch wheel values, from -8192 to 8191.
  247. When MPE is disabled, only the first channel is used.
  248. */
  249. int16_t pws[MAX_CHANNELS];
  250. /** Mod wheel values, from 0 to 127.
  251. */
  252. uint8_t mods[MAX_CHANNELS];
  253. /** Smoothing filters for wheel values */
  254. dsp::ExponentialFilter pwFilters[MAX_CHANNELS];
  255. dsp::ExponentialFilter modFilters[MAX_CHANNELS];
  256. dsp::PulseGenerator clockPulse;
  257. dsp::PulseGenerator clockDividerPulse;
  258. dsp::PulseGenerator retriggerPulses[MAX_CHANNELS];
  259. dsp::PulseGenerator startPulse;
  260. dsp::PulseGenerator stopPulse;
  261. dsp::PulseGenerator continuePulse;
  262. MidiParser() {
  263. heldNotes.reserve(128);
  264. reset();
  265. }
  266. /** Resets settings and performance state */
  267. void reset() {
  268. clock = 0;
  269. smooth = true;
  270. channels = 1;
  271. polyMode = ROTATE_MODE;
  272. pwRange = 2.f;
  273. clockDivision = 24;
  274. setFilterLambda(30.f);
  275. panic();
  276. }
  277. /** Resets performance state */
  278. void panic() {
  279. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  280. // Middle C
  281. notes[c] = 60;
  282. gates[c] = false;
  283. velocities[c] = 0;
  284. aftertouches[c] = 0;
  285. pws[c] = 0;
  286. mods[c] = 0;
  287. pwFilters[c].reset();
  288. modFilters[c].reset();
  289. }
  290. pedal = false;
  291. rotateIndex = -1;
  292. heldNotes.clear();
  293. }
  294. void processFilters(float deltaTime) {
  295. uint8_t wheelChannels = getWheelChannels();
  296. for (uint8_t c = 0; c < wheelChannels; c++) {
  297. float pw = pws[c] / 8191.f;
  298. pw = math::clamp(pw, -1.f, 1.f);
  299. if (smooth)
  300. pw = pwFilters[c].process(deltaTime, pw);
  301. else
  302. pwFilters[c].out = pw;
  303. float mod = mods[c] / 127.f;
  304. mod = math::clamp(mod, 0.f, 1.f);
  305. if (smooth)
  306. mod = modFilters[c].process(deltaTime, mod);
  307. else
  308. modFilters[c].out = mod;
  309. }
  310. }
  311. void processPulses(float deltaTime) {
  312. clockPulse.process(deltaTime);
  313. clockDividerPulse.process(deltaTime);
  314. startPulse.process(deltaTime);
  315. stopPulse.process(deltaTime);
  316. continuePulse.process(deltaTime);
  317. for (uint8_t c = 0; c < channels; c++) {
  318. retriggerPulses[c].process(deltaTime);
  319. }
  320. }
  321. void processMessage(const midi::Message& msg) {
  322. // DEBUG("MIDI: %ld %s", msg.getFrame(), msg.toString().c_str());
  323. switch (msg.getStatus()) {
  324. // note off
  325. case 0x8: {
  326. releaseNote(msg.getNote());
  327. } break;
  328. // note on
  329. case 0x9: {
  330. if (msg.getValue() > 0) {
  331. uint8_t c = msg.getChannel();
  332. c = pressNote(msg.getNote(), c);
  333. velocities[c] = msg.getValue();
  334. }
  335. else {
  336. // Note-on event with velocity 0 is an alternative for note-off event.
  337. releaseNote(msg.getNote());
  338. }
  339. } break;
  340. // key pressure
  341. case 0xa: {
  342. // Set the aftertouches with the same note
  343. // TODO Should we handle the MPE case differently?
  344. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  345. if (notes[c] == msg.getNote())
  346. aftertouches[c] = msg.getValue();
  347. }
  348. } break;
  349. // cc
  350. case 0xb: {
  351. processCC(msg);
  352. } break;
  353. // channel pressure
  354. case 0xd: {
  355. if (polyMode == MPE_MODE) {
  356. // Set the channel aftertouch
  357. aftertouches[msg.getChannel()] = msg.getNote();
  358. }
  359. else {
  360. // Set all aftertouches
  361. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  362. aftertouches[c] = msg.getNote();
  363. }
  364. }
  365. } break;
  366. // pitch wheel
  367. case 0xe: {
  368. uint8_t c = (polyMode == MPE_MODE) ? msg.getChannel() : 0;
  369. int16_t pw = msg.getValue();
  370. pw <<= 7;
  371. pw |= msg.getNote();
  372. pw -= 8192;
  373. pws[c] = pw;
  374. } break;
  375. case 0xf: {
  376. processSystem(msg);
  377. } break;
  378. default: break;
  379. }
  380. }
  381. void processCC(const midi::Message& msg) {
  382. switch (msg.getNote()) {
  383. // mod
  384. case 0x01: {
  385. uint8_t c = (polyMode == MPE_MODE) ? msg.getChannel() : 0;
  386. mods[c] = msg.getValue();
  387. } break;
  388. // sustain
  389. case 0x40: {
  390. if (msg.getValue() >= 64)
  391. pressPedal();
  392. else
  393. releasePedal();
  394. } break;
  395. // all notes off (panic)
  396. case 0x7b: {
  397. if (msg.getValue() == 0) {
  398. panic();
  399. }
  400. } break;
  401. default: break;
  402. }
  403. }
  404. void processSystem(const midi::Message& msg) {
  405. switch (msg.getChannel()) {
  406. // Song Position Pointer
  407. case 0x2: {
  408. int64_t pos = int64_t(msg.getNote()) | (int64_t(msg.getValue()) << 7);
  409. clock = pos * 6;
  410. } break;
  411. // Timing
  412. case 0x8: {
  413. clockPulse.trigger(1e-3);
  414. if (clock % clockDivision == 0) {
  415. clockDividerPulse.trigger(1e-3);
  416. }
  417. clock++;
  418. } break;
  419. // Start
  420. case 0xa: {
  421. startPulse.trigger(1e-3);
  422. clock = 0;
  423. } break;
  424. // Continue
  425. case 0xb: {
  426. continuePulse.trigger(1e-3);
  427. } break;
  428. // Stop
  429. case 0xc: {
  430. stopPulse.trigger(1e-3);
  431. } break;
  432. default: break;
  433. }
  434. }
  435. uint8_t assignChannel(uint8_t note) {
  436. if (channels == 1)
  437. return 0;
  438. switch (polyMode) {
  439. case REUSE_MODE: {
  440. // Find channel with the same note
  441. for (uint8_t c = 0; c < channels; c++) {
  442. if (notes[c] == note)
  443. return c;
  444. }
  445. } // fallthrough
  446. case ROTATE_MODE: {
  447. // Find next available channel
  448. for (uint8_t i = 0; i < channels; i++) {
  449. rotateIndex++;
  450. if (rotateIndex >= channels)
  451. rotateIndex = 0;
  452. if (!gates[rotateIndex])
  453. return rotateIndex;
  454. }
  455. // No notes are available. Advance rotateIndex once more.
  456. rotateIndex++;
  457. if (rotateIndex >= channels)
  458. rotateIndex = 0;
  459. return rotateIndex;
  460. } break;
  461. case RESET_MODE: {
  462. for (uint8_t c = 0; c < channels; c++) {
  463. if (!gates[c])
  464. return c;
  465. }
  466. return channels - 1;
  467. } break;
  468. case MPE_MODE: {
  469. // This case is handled by querying the MIDI message channel.
  470. return 0;
  471. } break;
  472. default: return 0;
  473. }
  474. }
  475. /** Returns actual assigned channel */
  476. uint8_t pressNote(uint8_t note, uint8_t channel) {
  477. // Remove existing similar note
  478. auto it = std::find(heldNotes.begin(), heldNotes.end(), note);
  479. if (it != heldNotes.end())
  480. heldNotes.erase(it);
  481. // Push note
  482. heldNotes.push_back(note);
  483. // Determine actual channel
  484. if (polyMode == MPE_MODE) {
  485. // Channel is already decided for us
  486. }
  487. else {
  488. channel = assignChannel(note);
  489. }
  490. // Set note
  491. notes[channel] = note;
  492. gates[channel] = true;
  493. retriggerPulses[channel].trigger(1e-3);
  494. return channel;
  495. }
  496. void releaseNote(uint8_t note) {
  497. // Remove the note
  498. auto it = std::find(heldNotes.begin(), heldNotes.end(), note);
  499. if (it != heldNotes.end())
  500. heldNotes.erase(it);
  501. // Hold note if pedal is pressed
  502. if (pedal)
  503. return;
  504. // Turn off gate of all channels with note
  505. for (uint8_t c = 0; c < channels; c++) {
  506. if (notes[c] == note) {
  507. gates[c] = false;
  508. }
  509. }
  510. // Set last note if monophonic
  511. if (channels == 1) {
  512. if (note == notes[0] && !heldNotes.empty()) {
  513. uint8_t lastNote = heldNotes.back();
  514. notes[0] = lastNote;
  515. gates[0] = true;
  516. return;
  517. }
  518. }
  519. }
  520. void pressPedal() {
  521. if (pedal)
  522. return;
  523. pedal = true;
  524. }
  525. void releasePedal() {
  526. if (!pedal)
  527. return;
  528. pedal = false;
  529. // Set last note if monophonic
  530. if (channels == 1) {
  531. if (!heldNotes.empty()) {
  532. // Replace note with last held note
  533. uint8_t lastNote = heldNotes.back();
  534. notes[0] = lastNote;
  535. }
  536. else {
  537. // Disable gate
  538. gates[0] = false;
  539. }
  540. }
  541. // Clear notes that are not held if polyphonic
  542. else {
  543. for (uint8_t c = 0; c < channels; c++) {
  544. if (!gates[c])
  545. continue;
  546. // Disable all gates
  547. gates[c] = false;
  548. // Re-enable gate if channel's note is still held
  549. for (uint8_t note : heldNotes) {
  550. if (notes[c] == note) {
  551. gates[c] = true;
  552. break;
  553. }
  554. }
  555. }
  556. }
  557. }
  558. uint8_t getChannels() {
  559. return channels;
  560. }
  561. void setChannels(uint8_t channels) {
  562. if (channels == this->channels)
  563. return;
  564. this->channels = channels;
  565. panic();
  566. }
  567. void setPolyMode(PolyMode polyMode) {
  568. if (polyMode == this->polyMode)
  569. return;
  570. this->polyMode = polyMode;
  571. panic();
  572. }
  573. float getPitchVoltage(uint8_t channel) {
  574. uint8_t wheelChannel = (polyMode == MPE_MODE) ? channel : 0;
  575. return (notes[channel] - 60.f + pwFilters[wheelChannel].out * pwRange) / 12.f;
  576. }
  577. /** Sets exponential smoothing filter lambda speed. */
  578. void setFilterLambda(float lambda) {
  579. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  580. pwFilters[c].setLambda(lambda);
  581. modFilters[c].setLambda(lambda);
  582. }
  583. }
  584. /** Returns pitch wheel value, from -1 to 1. */
  585. float getPw(uint8_t channel) {
  586. return pwFilters[channel].out;
  587. }
  588. /** Returns mod wheel value, from 0 to 1. */
  589. float getMod(uint8_t channel) {
  590. return modFilters[channel].out;
  591. }
  592. /** Returns number of polyphonic channels for pitch and mod wheels. */
  593. uint8_t getWheelChannels() {
  594. return (polyMode == MPE_MODE) ? MAX_CHANNELS : 1;
  595. }
  596. json_t* toJson() {
  597. json_t* rootJ = json_object();
  598. json_object_set_new(rootJ, "pwRange", json_real(pwRange));
  599. json_object_set_new(rootJ, "smooth", json_boolean(smooth));
  600. json_object_set_new(rootJ, "channels", json_integer(channels));
  601. json_object_set_new(rootJ, "polyMode", json_integer(polyMode));
  602. json_object_set_new(rootJ, "clockDivision", json_integer(clockDivision));
  603. // Saving/restoring pitch and mod doesn't make much sense for MPE.
  604. if (polyMode != MPE_MODE) {
  605. json_object_set_new(rootJ, "lastPw", json_integer(pws[0]));
  606. json_object_set_new(rootJ, "lastMod", json_integer(mods[0]));
  607. }
  608. // Assume all filter lambdas are the same
  609. json_object_set_new(rootJ, "filterLambda", json_real(pwFilters[0].lambda));
  610. return rootJ;
  611. }
  612. void fromJson(json_t* rootJ) {
  613. json_t* pwRangeJ = json_object_get(rootJ, "pwRange");
  614. if (pwRangeJ)
  615. pwRange = json_number_value(pwRangeJ);
  616. json_t* smoothJ = json_object_get(rootJ, "smooth");
  617. if (smoothJ)
  618. smooth = json_boolean_value(smoothJ);
  619. json_t* channelsJ = json_object_get(rootJ, "channels");
  620. if (channelsJ)
  621. setChannels(json_integer_value(channelsJ));
  622. json_t* polyModeJ = json_object_get(rootJ, "polyMode");
  623. if (polyModeJ)
  624. polyMode = (PolyMode) json_integer_value(polyModeJ);
  625. json_t* clockDivisionJ = json_object_get(rootJ, "clockDivision");
  626. if (clockDivisionJ)
  627. clockDivision = json_integer_value(clockDivisionJ);
  628. json_t* lastPwJ = json_object_get(rootJ, "lastPw");
  629. if (lastPwJ)
  630. pws[0] = json_integer_value(lastPwJ);
  631. // In Rack <2.5.3, `lastPitch` was used from 0 to 16383.
  632. json_t* lastPitchJ = json_object_get(rootJ, "lastPitch");
  633. if (lastPitchJ)
  634. pws[0] = json_integer_value(lastPitchJ) - 8192;
  635. json_t* lastModJ = json_object_get(rootJ, "lastMod");
  636. if (lastModJ)
  637. mods[0] = json_integer_value(lastModJ);
  638. // Added in Rack 2.5.3
  639. json_t* filterLambdaJ = json_object_get(rootJ, "filterLambda");
  640. if (filterLambdaJ)
  641. setFilterLambda(json_number_value(filterLambdaJ));
  642. }
  643. };
  644. } // namespace dsp
  645. } // namespace rack