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.

midimapper.cpp 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. #include <rtosc/ports.h>
  2. #include <cstring>
  3. #include <algorithm>
  4. #include <map>
  5. #include <sstream>
  6. #include <deque>
  7. #include <utility>
  8. #include <cassert>
  9. #include <rtosc/miditable.h>
  10. using namespace rtosc;
  11. using std::string;
  12. using std::get;
  13. using std::tuple;
  14. using std::make_tuple;
  15. /********************
  16. * Helper Templates *
  17. ********************/
  18. template<class T, class U>
  19. bool has_t(const T &t, const U&u)
  20. {return t.find(u) != t.end();}
  21. template<class T, class U>
  22. bool has2(const T &t, const U&u) {
  23. for(const U&uu:t)
  24. if(uu==u)
  25. return true;
  26. return false;
  27. }
  28. template<class T,class U>
  29. int getInd(const T&t,const U&u){
  30. int i=0;
  31. for(const U&uu:t) {
  32. if(uu==u)
  33. return i;
  34. else
  35. i++;
  36. }
  37. return -1;
  38. }
  39. /***********
  40. * Storage *
  41. ***********/
  42. bool MidiMapperStorage::handleCC(int ID, int val, write_cb write)
  43. {
  44. for(int i=0; i<mapping.size(); ++i)
  45. {
  46. if(std::get<0>(mapping[i]) == ID)
  47. {
  48. bool coarse = std::get<1>(mapping[i]);
  49. int ind = std::get<2>(mapping[i]);
  50. if(coarse)
  51. values[ind] = (val<<7)|(values[ind]&0x7f);
  52. else
  53. values[ind] = val|(values[ind]&0x3f80);
  54. callbacks[ind](values[ind],write);
  55. return true;
  56. }
  57. }
  58. return false;
  59. }
  60. //TODO try to change O(n^2) algorithm to O(n)
  61. void MidiMapperStorage::cloneValues(const MidiMapperStorage &storage)
  62. {
  63. //XXX this method is SUPER error prone
  64. for(int i=0; i<values.size(); ++i)
  65. values[i] = 0;
  66. for(int i=0; i<mapping.size(); ++i) {
  67. for(int j=0; j<storage.mapping.size(); ++j) {
  68. if(std::get<0>(mapping[i]) == std::get<0>(storage.mapping[j])) {
  69. bool coarse_src = std::get<1>(storage.mapping[j]);
  70. int ind_src = std::get<2>(storage.mapping[j]);
  71. bool coarse_dest = std::get<1>(mapping[i]);
  72. int ind_dest = std::get<2>(mapping[i]);
  73. int val = 0;
  74. //Extract
  75. if(coarse_src)
  76. val = storage.values[ind_src]>>7;
  77. else
  78. val = storage.values[ind_src]&0x7f;
  79. //Blit
  80. if(coarse_dest)
  81. values[ind_dest] = (val<<7)|(values[ind_dest]&0x7f);
  82. else
  83. values[ind_dest] = val|(values[ind_dest]&0x3f80);
  84. }
  85. }
  86. }
  87. }
  88. MidiMapperStorage *MidiMapperStorage::clone(void)
  89. {
  90. MidiMapperStorage *nstorage = new MidiMapperStorage();
  91. nstorage->values = values.sized_clone();
  92. nstorage->mapping = mapping.clone();
  93. nstorage->callbacks = callbacks.clone();
  94. return nstorage;
  95. }
  96. int MidiBijection::operator()(float x) const {
  97. if(mode == 0)
  98. return ((x-min)/(max-min))*(1<<14);
  99. else
  100. return 0;
  101. }
  102. float MidiBijection::operator()(int x) const {
  103. if(mode == 0)
  104. return x/((1<<14)*1.0)*(max-min)+min;
  105. else
  106. return 0;
  107. }
  108. /************************
  109. * Non realtime portion *
  110. ************************/
  111. MidiMappernRT::MidiMappernRT(void)
  112. :storage(0),base_ports(0)
  113. {}
  114. void MidiMappernRT::map(const char *addr, bool coarse)
  115. {
  116. for(auto x:learnQueue)
  117. if(x.first == addr && x.second == coarse)
  118. return;
  119. unMap(addr, coarse);
  120. learnQueue.push_back(std::make_pair(addr,coarse));
  121. char buf[1024];
  122. rtosc_message(buf, 1024, "/midi-learn/midi-add-watch","");
  123. rt_cb(buf);
  124. }
  125. MidiMapperStorage *MidiMappernRT::generateNewBijection(const Port &port, std::string addr)
  126. {
  127. MidiBijection bi;
  128. const auto &meta = port.meta();
  129. if(meta.find("min") == meta.end() ||
  130. meta.find("max") == meta.end()) {
  131. printf("Rtosc-MIDI: Cannot Learn address = <%s>\n", addr.c_str());
  132. printf("Rtosc-MIDI: There are no min/max fields\n");
  133. return NULL;
  134. }
  135. bi.mode = 0;
  136. bi.min = atof(port.meta()["min"]);
  137. bi.max = atof(port.meta()["max"]);
  138. char type = 'f';
  139. if(strstr(port.name, ":i"))
  140. type = 'i';
  141. std::function<void(int16_t, MidiMapperStorage::write_cb cb)> tmp =
  142. [bi,addr,type](int16_t x, MidiMapperStorage::write_cb cb) {
  143. float out = bi(x);
  144. //printf("in = %d out = %f\n", x, out);
  145. char buf[1024];
  146. if(type == 'f')
  147. rtosc_message(buf, 1024, addr.c_str(), "f", out);
  148. else
  149. rtosc_message(buf, 1024, addr.c_str(), "i", (int)out);
  150. cb(buf);
  151. };
  152. if(bi.min == 0 && bi.max == 127 && type =='i')
  153. tmp = [bi,addr,type](int16_t x, MidiMapperStorage::write_cb cb) {
  154. //printf("special case in = %x out = %d\n", x, 0x7f&(x>>7));
  155. char buf[1024];
  156. rtosc_message(buf, 1024, addr.c_str(), "i", 0x7f&(x>>7));
  157. cb(buf);
  158. };
  159. MidiMapperStorage *nstorage = new MidiMapperStorage();
  160. if(storage) {
  161. //XXX not quite
  162. nstorage->values = storage->values.one_larger();
  163. nstorage->mapping = storage->mapping.clone();//insert(std::make_tuple(ID, true, storage->callbacks.size()));
  164. nstorage->callbacks = storage->callbacks.insert(tmp);
  165. } else {
  166. nstorage->values = nstorage->values.insert(0);
  167. nstorage->mapping = nstorage->mapping.clone();//insert(std::make_tuple(ID, true, 0));
  168. nstorage->callbacks = nstorage->callbacks.insert(tmp);
  169. }
  170. inv_map[addr] = std::make_tuple(nstorage->callbacks.size()-1, -1,-1,bi);
  171. return nstorage;
  172. }
  173. void MidiMappernRT::addNewMapper(int ID, const Port &port, std::string addr)
  174. {
  175. MidiBijection bi;
  176. bi.mode = 0;
  177. bi.min = atof(port.meta()["min"]);
  178. bi.max = atof(port.meta()["max"]);
  179. char type = 'f';
  180. if(strstr(port.name, ":i"))
  181. type = 'i';
  182. //printf("ADDING TYPE %c\n", type);
  183. auto tmp = [bi,addr,type](int16_t x, MidiMapperStorage::write_cb cb) {
  184. float out = bi(x);
  185. //printf("in = %d out = %f\n", x, out);
  186. char buf[1024];
  187. if(type == 'f')
  188. rtosc_message(buf, 1024, addr.c_str(), "f", out);
  189. else
  190. rtosc_message(buf, 1024, addr.c_str(), "i", (int)out);
  191. cb(buf);
  192. };
  193. MidiMapperStorage *nstorage = new MidiMapperStorage();
  194. if(storage) {
  195. //XXX not quite
  196. nstorage->values = storage->values.one_larger();
  197. nstorage->mapping = storage->mapping.insert(std::make_tuple(ID, true, storage->callbacks.size()));
  198. nstorage->callbacks = storage->callbacks.insert(tmp);
  199. } else {
  200. nstorage->values = nstorage->values.insert(0);
  201. nstorage->mapping = nstorage->mapping.insert(std::make_tuple(ID, true, 0));
  202. nstorage->callbacks = nstorage->callbacks.insert(tmp);
  203. }
  204. storage = nstorage;
  205. inv_map[addr] = std::make_tuple(storage->callbacks.size()-1, ID,-1,bi);
  206. char buf[1024];
  207. rtosc_message(buf, 1024, "/midi-learn/midi-bind", "b", sizeof(storage), &storage);
  208. rt_cb(buf);
  209. }
  210. void MidiMappernRT::addFineMapper(int ID, const Port &port, std::string addr)
  211. {
  212. (void) port;
  213. //TODO asserts
  214. //Bijection already created
  215. //Coarse node already active
  216. //Value already allocated
  217. //Find mapping
  218. int mapped_ID = std::get<0>(inv_map[addr]);
  219. std::get<2>(inv_map[addr]) = ID;
  220. MidiMapperStorage *nstorage = new MidiMapperStorage();
  221. nstorage->values = storage->values.sized_clone();
  222. nstorage->mapping = storage->mapping.insert(std::make_tuple(ID, false, mapped_ID));
  223. nstorage->callbacks = storage->callbacks.insert(storage->callbacks[mapped_ID]);
  224. storage = nstorage;
  225. }
  226. void killMap(int ID, MidiMapperStorage &m)
  227. {
  228. MidiMapperStorage::TinyVector<tuple<int, bool, int>> nmapping(m.mapping.size()-1);
  229. int j=0;
  230. for(int i=0; i<m.mapping.size(); i++)
  231. if(get<0>(m.mapping[i]) != ID)
  232. nmapping[j++] = m.mapping[i];
  233. assert(j == nmapping.size());
  234. m.mapping = nmapping;
  235. }
  236. void MidiMappernRT::useFreeID(int ID)
  237. {
  238. if(learnQueue.empty())
  239. return;
  240. std::string addr = std::get<0>(learnQueue.front());
  241. bool coarse = std::get<1>(learnQueue.front());
  242. learnQueue.pop_front();
  243. assert(base_ports);
  244. const rtosc::Port *p = base_ports->apropos(addr.c_str());
  245. assert(p);
  246. MidiMapperStorage *nstorage;
  247. if(inv_map.find(addr) == inv_map.end())
  248. nstorage = generateNewBijection(*p, addr);
  249. else
  250. nstorage = storage->clone();
  251. auto imap = inv_map[addr];
  252. int mapped_ID = std::get<0>(imap);
  253. nstorage->mapping = nstorage->mapping.insert(make_tuple(ID, coarse, mapped_ID));
  254. if(coarse) {
  255. if(get<1>(imap) != -1)
  256. killMap(get<1>(imap), *nstorage);
  257. inv_map[addr] = make_tuple(get<0>(imap), ID, get<2>(imap), get<3>(imap));
  258. } else {
  259. if(get<2>(imap) != -1)
  260. killMap(get<1>(imap), *nstorage);
  261. inv_map[addr] = make_tuple(get<0>(imap), get<1>(imap), ID, get<3>(imap));
  262. }
  263. storage = nstorage;
  264. //TODO clean up unused value and callback objects
  265. char buf[1024];
  266. rtosc_message(buf, 1024, "/midi-learn/midi-bind", "b", sizeof(storage), &storage);
  267. rt_cb(buf);
  268. };
  269. void MidiMappernRT::unMap(const char *addr, bool coarse)
  270. {
  271. //printf("Unmapping('%s',%d)\n",addr,coarse);
  272. if(inv_map.find(addr) == inv_map.end())
  273. return;
  274. auto imap = inv_map[addr];
  275. int kill_id = -1;
  276. if(coarse) {
  277. kill_id = get<1>(imap);
  278. inv_map[addr] = make_tuple(get<0>(imap), -1, get<2>(imap), get<3>(imap));
  279. } else {
  280. kill_id = get<2>(imap);
  281. inv_map[addr] = make_tuple(get<0>(imap), get<1>(imap), -1, get<3>(imap));
  282. }
  283. {
  284. auto tmp = inv_map[addr];
  285. if(get<1>(tmp) == -1 && get<2>(tmp) == -1)
  286. inv_map.erase(addr);
  287. }
  288. if(kill_id == -1)
  289. return;
  290. MidiMapperStorage *nstorage = storage->clone();
  291. killMap(kill_id, *nstorage);
  292. storage = nstorage;
  293. //TODO clean up unused value and callback objects
  294. char buf[1024];
  295. rtosc_message(buf, 1024, "/midi-learn/midi-bind", "b", sizeof(storage), &storage);
  296. rt_cb(buf);
  297. }
  298. void MidiMappernRT::delMapping(int ID, bool coarse, const char *addr){
  299. (void) ID;
  300. (void) coarse;
  301. (void) addr;
  302. };
  303. void MidiMappernRT::replaceMapping(int, bool, const char *){};
  304. void MidiMappernRT::clear(void)
  305. {
  306. storage = new MidiMapperStorage();
  307. learnQueue.clear();
  308. inv_map.clear();
  309. char buf[1024];
  310. rtosc_message(buf, 1024, "/midi-learn/midi-bind", "b", sizeof(storage), &storage);
  311. rt_cb(buf);
  312. }
  313. std::map<std::string, std::string> MidiMappernRT::getMidiMappingStrings(void)
  314. {
  315. std::map<std::string, std::string> result;
  316. for(auto s:inv_map)
  317. result[s.first] = getMappedString(s.first);
  318. char ID = 'A';
  319. for(auto s:learnQueue)
  320. {
  321. if(s.second == false)
  322. result[s.first] += std::string(":")+ID++;
  323. else
  324. result[s.first] = ID++;
  325. }
  326. return result;
  327. }
  328. //unclear if this should be be here as a helper or not
  329. std::string MidiMappernRT::getMappedString(std::string addr)
  330. {
  331. std::stringstream out;
  332. //find coarse
  333. if(has_t(inv_map,addr)) {
  334. if(std::get<1>(inv_map[addr]) != -1)
  335. out << std::get<1>(inv_map[addr]);
  336. }else if(has2(learnQueue, make_pair(addr,true)))
  337. out << getInd(learnQueue,std::make_pair(addr,true));
  338. //find Fine
  339. if(has_t(inv_map,addr)) {
  340. if(std::get<2>(inv_map[addr]) != -1)
  341. out << ":" << std::get<2>(inv_map[addr]);
  342. } else if(has2(learnQueue, make_pair(addr,false)))
  343. out << getInd(learnQueue,std::make_pair(addr,false));
  344. return out.str();
  345. }
  346. MidiBijection MidiMappernRT::getBijection(std::string s)
  347. {
  348. return std::get<3>(inv_map[s]);
  349. }
  350. void MidiMappernRT::snoop(const char *msg)
  351. {
  352. if(inv_map.find(msg) != inv_map.end())
  353. {
  354. auto apple = inv_map[msg];
  355. MidiBijection bi = getBijection(msg);
  356. float value = 0;
  357. std::string args = rtosc_argument_string(msg);
  358. if(args == "f")
  359. value = rtosc_argument(msg, 0).f;
  360. else if(args == "i")
  361. value = rtosc_argument(msg, 0).i;
  362. else if(args == "T")
  363. value = 1.0;
  364. else if(args == "F")
  365. value = 0.0;
  366. else
  367. return;
  368. int new_midi = bi(value);
  369. //printf("--------------------------------------------\n");
  370. //printf("msg = '%s'\n", msg);
  371. //printf("--------------------------------------------\n");
  372. //printf("new midi value: %f->'%x'\n", value, new_midi);
  373. if(std::get<1>(apple) != -1)
  374. apply_high(new_midi,std::get<1>(apple));
  375. if(std::get<2>(apple) != -1)
  376. apply_low(new_midi,std::get<2>(apple));
  377. }
  378. };
  379. void MidiMappernRT::apply_high(int v, int ID) { apply_midi(v>>7,ID); }
  380. void MidiMappernRT::apply_low(int v, int ID) { apply_midi(0x7f&v,ID);}
  381. void MidiMappernRT::apply_midi(int val, int ID)
  382. {
  383. char buf[1024];
  384. rtosc_message(buf,1024,"/virtual_midi_cc","iii",0,val,ID);
  385. rt_cb(buf);
  386. }
  387. void MidiMappernRT::setBounds(const char *str, float low, float high)
  388. {
  389. if(inv_map.find(str) == inv_map.end())
  390. return;
  391. string addr = str;
  392. auto imap = inv_map[str];
  393. auto newBi = MidiBijection{0,low,high};
  394. inv_map[str] = make_tuple(get<0>(imap),get<1>(imap),get<2>(imap),newBi);
  395. MidiMapperStorage *nstorage = storage->clone();
  396. nstorage->callbacks[get<0>(imap)] = [newBi,addr](int16_t x, MidiMapperStorage::write_cb cb) {
  397. float out = newBi(x);
  398. char buf[1024];
  399. rtosc_message(buf, 1024, addr.c_str(), "f", out);
  400. cb(buf);
  401. };
  402. storage = nstorage;
  403. char buf[1024];
  404. rtosc_message(buf, 1024, "/midi-learn/midi-bind", "b", sizeof(storage), &storage);
  405. rt_cb(buf);
  406. }
  407. std::tuple<float,float,float,float> MidiMappernRT::getBounds(const char *str)
  408. {
  409. const rtosc::Port *p = base_ports->apropos(str);
  410. assert(p);
  411. float min_val = atof(p->meta()["min"]);
  412. float max_val = atof(p->meta()["max"]);
  413. if(inv_map.find(str) != inv_map.end()) {
  414. auto elm = std::get<3>(inv_map[str]);
  415. return std::make_tuple(min_val, max_val,elm.min,elm.max);
  416. }
  417. return std::make_tuple(min_val, max_val,-1.0f,-1.0f);
  418. }
  419. bool MidiMappernRT::has(std::string addr)
  420. {
  421. return inv_map.find(addr) != inv_map.end();
  422. }
  423. bool MidiMappernRT::hasPending(std::string addr)
  424. {
  425. for(auto s:learnQueue)
  426. if(s.first == addr)
  427. return true;
  428. return false;
  429. }
  430. bool MidiMappernRT::hasCoarse(std::string addr)
  431. {
  432. if(!has(addr))
  433. return false;
  434. auto e = inv_map[addr];
  435. return std::get<1>(e) != -1;
  436. }
  437. bool MidiMappernRT::hasFine(std::string addr)
  438. {
  439. if(!has(addr))
  440. return false;
  441. auto e = inv_map[addr];
  442. return std::get<2>(e) != -1;
  443. }
  444. bool MidiMappernRT::hasCoarsePending(std::string addr)
  445. {
  446. for(auto s:learnQueue)
  447. if(s.first == addr && s.second)
  448. return true;
  449. return false;
  450. }
  451. bool MidiMappernRT::hasFinePending(std::string addr)
  452. {
  453. for(auto s:learnQueue)
  454. if(s.first == addr && !s.second)
  455. return true;
  456. return false;
  457. }
  458. int MidiMappernRT::getCoarse(std::string addr)
  459. {
  460. if(!has(addr))
  461. return -1;
  462. auto e = inv_map[addr];
  463. return std::get<1>(e);
  464. }
  465. int MidiMappernRT::getFine(std::string addr)
  466. {
  467. if(!has(addr))
  468. return -1;
  469. auto e = inv_map[addr];
  470. return std::get<2>(e);
  471. }
  472. /*****************
  473. * Realtime code *
  474. *****************/
  475. MidiMapperRT::MidiMapperRT(void)
  476. :storage(NULL), watchSize(0)
  477. {}
  478. void MidiMapperRT::setBackendCb(std::function<void(const char*)> cb) {backend = cb;}
  479. void MidiMapperRT::setFrontendCb(std::function<void(const char*)> cb) {frontend = cb;}
  480. void MidiMapperRT::handleCC(int ID, int val) {
  481. //printf("handling CC(%d,%d){%d,%d,%d}\n", ID, val, (int)storage, pending.has(ID), watchSize);
  482. if((!storage || !storage->handleCC(ID, val, backend)) && !pending.has(ID) && watchSize) {
  483. watchSize--;
  484. pending.insert(ID);
  485. char msg[1024];
  486. rtosc_message(msg, 1024, "/midi-use-CC", "i", ID);
  487. frontend(msg);
  488. }
  489. }
  490. void MidiMapperRT::addWatch(void) {watchSize++;}
  491. void MidiMapperRT::remWatch(void) {if(watchSize) watchSize--;}
  492. const rtosc::Ports MidiMapperRT::ports = {
  493. {"midi-add-watch",0,0, [](msg_t, RtData&d)
  494. {
  495. auto midi = (MidiMapperRT*)d.obj;
  496. midi->addWatch();}},
  497. {"midi-remove-watch",0,0, [](msg_t, RtData&d)
  498. {
  499. auto midi = (MidiMapperRT*)d.obj;
  500. midi->remWatch();}},
  501. {"midi-bind:b","",0, [](msg_t msg, RtData&d)
  502. {
  503. auto &midi = *(MidiMapperRT*)d.obj;
  504. midi.pending.pop();
  505. MidiMapperStorage *nstorage =
  506. *(MidiMapperStorage**)rtosc_argument(msg,0).b.data;
  507. if(midi.storage) {
  508. nstorage->cloneValues(*midi.storage);
  509. midi.storage = nstorage;
  510. } else
  511. midi.storage = nstorage;}}
  512. };
  513. //Depricated
  514. Port MidiMapperRT::addWatchPort(void) {
  515. return Port{"midi-add-watch","",0, [this](msg_t, RtData&) {
  516. this->addWatch();
  517. }};
  518. }
  519. Port MidiMapperRT::removeWatchPort(void) {
  520. return Port{"midi-remove-watch","",0, [this](msg_t, RtData&) {
  521. this->remWatch();
  522. }};
  523. }
  524. Port MidiMapperRT::bindPort(void) {
  525. return Port{"midi-bind:b","",0, [this](msg_t msg, RtData&) {
  526. pending.pop();
  527. MidiMapperStorage *nstorage =
  528. *(MidiMapperStorage**)rtosc_argument(msg,0).b.data;
  529. if(storage) {
  530. nstorage->cloneValues(*storage);
  531. storage = nstorage;
  532. } else
  533. storage = nstorage;
  534. //TODO memory deallocation
  535. }};
  536. }