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.

722 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. /** Clock output pulses per quarter note */
  223. uint32_t clockDivision;
  224. /** Actual number of polyphonic channels */
  225. uint8_t channels;
  226. enum PolyMode {
  227. ROTATE_MODE,
  228. REUSE_MODE,
  229. RESET_MODE,
  230. MPE_MODE,
  231. NUM_POLY_MODES
  232. };
  233. PolyMode polyMode;
  234. // States
  235. /** Clock index from song start */
  236. int64_t clock;
  237. /** Whether sustain pedal is held. */
  238. bool pedal;
  239. uint8_t notes[MAX_CHANNELS];
  240. bool gates[MAX_CHANNELS];
  241. uint8_t velocities[MAX_CHANNELS];
  242. uint8_t aftertouches[MAX_CHANNELS];
  243. std::vector<uint8_t> heldNotes;
  244. int8_t rotateIndex;
  245. /** Pitch wheel values, from -8192 to 8191.
  246. When MPE is disabled, only the first channel is used.
  247. */
  248. int16_t pws[MAX_CHANNELS];
  249. /** Mod wheel values, from 0 to 127.
  250. */
  251. uint8_t mods[MAX_CHANNELS];
  252. /** Smoothing filters for wheel values */
  253. dsp::ExponentialFilter pwFilters[MAX_CHANNELS];
  254. dsp::ExponentialFilter modFilters[MAX_CHANNELS];
  255. dsp::PulseGenerator clockPulse;
  256. dsp::PulseGenerator clockDividerPulse;
  257. dsp::PulseGenerator retriggerPulses[MAX_CHANNELS];
  258. dsp::PulseGenerator startPulse;
  259. dsp::PulseGenerator stopPulse;
  260. dsp::PulseGenerator continuePulse;
  261. MidiParser() {
  262. heldNotes.reserve(128);
  263. reset();
  264. }
  265. /** Resets settings and performance state */
  266. void reset() {
  267. clock = 0;
  268. smooth = true;
  269. channels = 1;
  270. polyMode = ROTATE_MODE;
  271. pwRange = 2.f;
  272. clockDivision = 24;
  273. setFilterLambda(30.f);
  274. panic();
  275. }
  276. /** Resets performance state */
  277. void panic() {
  278. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  279. // Middle C
  280. notes[c] = 60;
  281. gates[c] = false;
  282. velocities[c] = 0;
  283. aftertouches[c] = 0;
  284. pws[c] = 0;
  285. mods[c] = 0;
  286. pwFilters[c].reset();
  287. modFilters[c].reset();
  288. }
  289. pedal = false;
  290. rotateIndex = -1;
  291. heldNotes.clear();
  292. }
  293. void processFilters(float deltaTime) {
  294. uint8_t wheelChannels = getWheelChannels();
  295. for (uint8_t c = 0; c < wheelChannels; c++) {
  296. float pw = pws[c] / 8191.f;
  297. pw = math::clamp(pw, -1.f, 1.f);
  298. if (smooth)
  299. pw = pwFilters[c].process(deltaTime, pw);
  300. else
  301. pwFilters[c].out = pw;
  302. float mod = mods[c] / 127.f;
  303. mod = math::clamp(mod, 0.f, 1.f);
  304. if (smooth)
  305. mod = modFilters[c].process(deltaTime, mod);
  306. else
  307. modFilters[c].out = mod;
  308. }
  309. }
  310. void processPulses(float deltaTime) {
  311. clockPulse.process(deltaTime);
  312. clockDividerPulse.process(deltaTime);
  313. startPulse.process(deltaTime);
  314. stopPulse.process(deltaTime);
  315. continuePulse.process(deltaTime);
  316. for (uint8_t c = 0; c < channels; c++) {
  317. retriggerPulses[c].process(deltaTime);
  318. }
  319. }
  320. void processMessage(const midi::Message& msg) {
  321. // DEBUG("MIDI: %ld %s", msg.getFrame(), msg.toString().c_str());
  322. switch (msg.getStatus()) {
  323. // note off
  324. case 0x8: {
  325. releaseNote(msg.getNote());
  326. } break;
  327. // note on
  328. case 0x9: {
  329. if (msg.getValue() > 0) {
  330. uint8_t c = msg.getChannel();
  331. c = pressNote(msg.getNote(), c);
  332. velocities[c] = msg.getValue();
  333. }
  334. else {
  335. // Note-on event with velocity 0 is an alternative for note-off event.
  336. releaseNote(msg.getNote());
  337. }
  338. } break;
  339. // key pressure
  340. case 0xa: {
  341. // Set the aftertouches with the same note
  342. // TODO Should we handle the MPE case differently?
  343. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  344. if (notes[c] == msg.getNote())
  345. aftertouches[c] = msg.getValue();
  346. }
  347. } break;
  348. // cc
  349. case 0xb: {
  350. processCC(msg);
  351. } break;
  352. // channel pressure
  353. case 0xd: {
  354. if (polyMode == MPE_MODE) {
  355. // Set the channel aftertouch
  356. aftertouches[msg.getChannel()] = msg.getNote();
  357. }
  358. else {
  359. // Set all aftertouches
  360. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  361. aftertouches[c] = msg.getNote();
  362. }
  363. }
  364. } break;
  365. // pitch wheel
  366. case 0xe: {
  367. uint8_t c = (polyMode == MPE_MODE) ? msg.getChannel() : 0;
  368. int16_t pw = msg.getValue();
  369. pw <<= 7;
  370. pw |= msg.getNote();
  371. pw -= 8192;
  372. pws[c] = pw;
  373. } break;
  374. case 0xf: {
  375. processSystem(msg);
  376. } break;
  377. default: break;
  378. }
  379. }
  380. void processCC(const midi::Message& msg) {
  381. switch (msg.getNote()) {
  382. // mod
  383. case 0x01: {
  384. uint8_t c = (polyMode == MPE_MODE) ? msg.getChannel() : 0;
  385. mods[c] = msg.getValue();
  386. } break;
  387. // sustain
  388. case 0x40: {
  389. if (msg.getValue() >= 64)
  390. pressPedal();
  391. else
  392. releasePedal();
  393. } break;
  394. // all notes off (panic)
  395. case 0x7b: {
  396. if (msg.getValue() == 0) {
  397. panic();
  398. }
  399. } break;
  400. default: break;
  401. }
  402. }
  403. void processSystem(const midi::Message& msg) {
  404. switch (msg.getChannel()) {
  405. // Song Position Pointer
  406. case 0x2: {
  407. int64_t pos = int64_t(msg.getNote()) | (int64_t(msg.getValue()) << 7);
  408. clock = pos * 6;
  409. } break;
  410. // Timing
  411. case 0x8: {
  412. clockPulse.trigger(1e-3);
  413. if (clock % clockDivision == 0) {
  414. clockDividerPulse.trigger(1e-3);
  415. }
  416. clock++;
  417. } break;
  418. // Start
  419. case 0xa: {
  420. startPulse.trigger(1e-3);
  421. clock = 0;
  422. } break;
  423. // Continue
  424. case 0xb: {
  425. continuePulse.trigger(1e-3);
  426. } break;
  427. // Stop
  428. case 0xc: {
  429. stopPulse.trigger(1e-3);
  430. } break;
  431. default: break;
  432. }
  433. }
  434. uint8_t assignChannel(uint8_t note) {
  435. if (channels == 1)
  436. return 0;
  437. switch (polyMode) {
  438. case REUSE_MODE: {
  439. // Find channel with the same note
  440. for (uint8_t c = 0; c < channels; c++) {
  441. if (notes[c] == note)
  442. return c;
  443. }
  444. } // fallthrough
  445. case ROTATE_MODE: {
  446. // Find next available channel
  447. for (uint8_t i = 0; i < channels; i++) {
  448. rotateIndex++;
  449. if (rotateIndex >= channels)
  450. rotateIndex = 0;
  451. if (!gates[rotateIndex])
  452. return rotateIndex;
  453. }
  454. // No notes are available. Advance rotateIndex once more.
  455. rotateIndex++;
  456. if (rotateIndex >= channels)
  457. rotateIndex = 0;
  458. return rotateIndex;
  459. } break;
  460. case RESET_MODE: {
  461. for (uint8_t c = 0; c < channels; c++) {
  462. if (!gates[c])
  463. return c;
  464. }
  465. return channels - 1;
  466. } break;
  467. case MPE_MODE: {
  468. // This case is handled by querying the MIDI message channel.
  469. return 0;
  470. } break;
  471. default: return 0;
  472. }
  473. }
  474. /** Returns actual assigned channel */
  475. uint8_t pressNote(uint8_t note, uint8_t channel) {
  476. // Remove existing similar note
  477. auto it = std::find(heldNotes.begin(), heldNotes.end(), note);
  478. if (it != heldNotes.end())
  479. heldNotes.erase(it);
  480. // Push note
  481. heldNotes.push_back(note);
  482. // Determine actual channel
  483. if (polyMode == MPE_MODE) {
  484. // Channel is already decided for us
  485. }
  486. else {
  487. channel = assignChannel(note);
  488. }
  489. // Set note
  490. notes[channel] = note;
  491. gates[channel] = true;
  492. retriggerPulses[channel].trigger(1e-3);
  493. return channel;
  494. }
  495. void releaseNote(uint8_t note) {
  496. // Remove the note
  497. auto it = std::find(heldNotes.begin(), heldNotes.end(), note);
  498. if (it != heldNotes.end())
  499. heldNotes.erase(it);
  500. // Hold note if pedal is pressed
  501. if (pedal)
  502. return;
  503. // Turn off gate of all channels with note
  504. for (uint8_t c = 0; c < channels; c++) {
  505. if (notes[c] == note) {
  506. gates[c] = false;
  507. }
  508. }
  509. // Set last note if monophonic
  510. if (channels == 1) {
  511. if (note == notes[0] && !heldNotes.empty()) {
  512. uint8_t lastNote = heldNotes.back();
  513. notes[0] = lastNote;
  514. gates[0] = true;
  515. return;
  516. }
  517. }
  518. }
  519. void pressPedal() {
  520. if (pedal)
  521. return;
  522. pedal = true;
  523. }
  524. void releasePedal() {
  525. if (!pedal)
  526. return;
  527. pedal = false;
  528. // Set last note if monophonic
  529. if (channels == 1) {
  530. if (!heldNotes.empty()) {
  531. // Replace note with last held note
  532. uint8_t lastNote = heldNotes.back();
  533. notes[0] = lastNote;
  534. }
  535. else {
  536. // Disable gate
  537. gates[0] = false;
  538. }
  539. }
  540. // Clear notes that are not held if polyphonic
  541. else {
  542. for (uint8_t c = 0; c < channels; c++) {
  543. if (!gates[c])
  544. continue;
  545. // Disable all gates
  546. gates[c] = false;
  547. // Re-enable gate if channel's note is still held
  548. for (uint8_t note : heldNotes) {
  549. if (notes[c] == note) {
  550. gates[c] = true;
  551. break;
  552. }
  553. }
  554. }
  555. }
  556. }
  557. uint8_t getChannels() {
  558. return channels;
  559. }
  560. void setChannels(uint8_t channels) {
  561. if (channels == this->channels)
  562. return;
  563. this->channels = channels;
  564. panic();
  565. }
  566. void setPolyMode(PolyMode polyMode) {
  567. if (polyMode == this->polyMode)
  568. return;
  569. this->polyMode = polyMode;
  570. panic();
  571. }
  572. float getPitchVoltage(uint8_t channel) {
  573. uint8_t wheelChannel = (polyMode == MPE_MODE) ? channel : 0;
  574. return (notes[channel] - 60.f + pwFilters[wheelChannel].out * pwRange) / 12.f;
  575. }
  576. /** Sets exponential smoothing filter lambda speed. */
  577. void setFilterLambda(float lambda) {
  578. for (uint8_t c = 0; c < MAX_CHANNELS; c++) {
  579. pwFilters[c].setLambda(lambda);
  580. modFilters[c].setLambda(lambda);
  581. }
  582. }
  583. /** Returns pitch wheel value, from -1 to 1. */
  584. float getPw(uint8_t channel) {
  585. return pwFilters[channel].out;
  586. }
  587. /** Returns mod wheel value, from 0 to 1. */
  588. float getMod(uint8_t channel) {
  589. return modFilters[channel].out;
  590. }
  591. /** Returns number of polyphonic channels for pitch and mod wheels. */
  592. uint8_t getWheelChannels() {
  593. return (polyMode == MPE_MODE) ? MAX_CHANNELS : 1;
  594. }
  595. json_t* toJson() {
  596. json_t* rootJ = json_object();
  597. json_object_set_new(rootJ, "pwRange", json_real(pwRange));
  598. json_object_set_new(rootJ, "smooth", json_boolean(smooth));
  599. json_object_set_new(rootJ, "channels", json_integer(channels));
  600. json_object_set_new(rootJ, "polyMode", json_integer(polyMode));
  601. json_object_set_new(rootJ, "clockDivision", json_integer(clockDivision));
  602. // Saving/restoring pitch and mod doesn't make much sense for MPE.
  603. if (polyMode != MPE_MODE) {
  604. json_object_set_new(rootJ, "lastPw", json_integer(pws[0]));
  605. json_object_set_new(rootJ, "lastMod", json_integer(mods[0]));
  606. }
  607. // Assume all filter lambdas are the same
  608. json_object_set_new(rootJ, "filterLambda", json_real(pwFilters[0].lambda));
  609. return rootJ;
  610. }
  611. void fromJson(json_t* rootJ) {
  612. json_t* pwRangeJ = json_object_get(rootJ, "pwRange");
  613. if (pwRangeJ)
  614. pwRange = json_number_value(pwRangeJ);
  615. json_t* smoothJ = json_object_get(rootJ, "smooth");
  616. if (smoothJ)
  617. smooth = json_boolean_value(smoothJ);
  618. json_t* channelsJ = json_object_get(rootJ, "channels");
  619. if (channelsJ)
  620. setChannels(json_integer_value(channelsJ));
  621. json_t* polyModeJ = json_object_get(rootJ, "polyMode");
  622. if (polyModeJ)
  623. polyMode = (PolyMode) json_integer_value(polyModeJ);
  624. json_t* clockDivisionJ = json_object_get(rootJ, "clockDivision");
  625. if (clockDivisionJ)
  626. clockDivision = json_integer_value(clockDivisionJ);
  627. json_t* lastPwJ = json_object_get(rootJ, "lastPw");
  628. if (lastPwJ)
  629. pws[0] = json_integer_value(lastPwJ);
  630. // In Rack <2.5.3, `lastPitch` was used from 0 to 16383.
  631. json_t* lastPitchJ = json_object_get(rootJ, "lastPitch");
  632. if (lastPitchJ)
  633. pws[0] = json_integer_value(lastPitchJ) - 8192;
  634. json_t* lastModJ = json_object_get(rootJ, "lastMod");
  635. if (lastModJ)
  636. mods[0] = json_integer_value(lastModJ);
  637. // Added in Rack 2.5.3
  638. json_t* filterLambdaJ = json_object_get(rootJ, "filterLambda");
  639. if (filterLambdaJ)
  640. setFilterLambda(json_number_value(filterLambdaJ));
  641. }
  642. };
  643. } // namespace dsp
  644. } // namespace rack