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.

594 lines
17KB

  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. if(kill_id == -1)
  284. return;
  285. MidiMapperStorage *nstorage = storage->clone();
  286. killMap(kill_id, *nstorage);
  287. storage = nstorage;
  288. //TODO clean up unused value and callback objects
  289. char buf[1024];
  290. rtosc_message(buf, 1024, "/midi-learn/midi-bind", "b", sizeof(storage), &storage);
  291. rt_cb(buf);
  292. }
  293. void MidiMappernRT::delMapping(int ID, bool coarse, const char *addr){
  294. (void) ID;
  295. (void) coarse;
  296. (void) addr;
  297. };
  298. void MidiMappernRT::replaceMapping(int, bool, const char *){};
  299. std::map<std::string, std::string> MidiMappernRT::getMidiMappingStrings(void)
  300. {
  301. std::map<std::string, std::string> result;
  302. for(auto s:inv_map)
  303. result[s.first] = getMappedString(s.first);
  304. char ID = 'A';
  305. for(auto s:learnQueue)
  306. {
  307. if(s.second == false)
  308. result[s.first] += std::string(":")+ID++;
  309. else
  310. result[s.first] = ID++;
  311. }
  312. return result;
  313. }
  314. //unclear if this should be be here as a helper or not
  315. std::string MidiMappernRT::getMappedString(std::string addr)
  316. {
  317. std::stringstream out;
  318. //find coarse
  319. if(has_t(inv_map,addr)) {
  320. if(std::get<1>(inv_map[addr]) != -1)
  321. out << std::get<1>(inv_map[addr]);
  322. }else if(has2(learnQueue, make_pair(addr,true)))
  323. out << getInd(learnQueue,std::make_pair(addr,true));
  324. //find Fine
  325. if(has_t(inv_map,addr)) {
  326. if(std::get<2>(inv_map[addr]) != -1)
  327. out << ":" << std::get<2>(inv_map[addr]);
  328. } else if(has2(learnQueue, make_pair(addr,false)))
  329. out << getInd(learnQueue,std::make_pair(addr,false));
  330. return out.str();
  331. }
  332. MidiBijection MidiMappernRT::getBijection(std::string s)
  333. {
  334. return std::get<3>(inv_map[s]);
  335. }
  336. void MidiMappernRT::snoop(const char *msg)
  337. {
  338. if(inv_map.find(msg) != inv_map.end())
  339. {
  340. auto apple = inv_map[msg];
  341. MidiBijection bi = getBijection(msg);
  342. float value = 0;
  343. std::string args = rtosc_argument_string(msg);
  344. if(args == "f")
  345. value = rtosc_argument(msg, 0).f;
  346. else if(args == "i")
  347. value = rtosc_argument(msg, 0).i;
  348. else if(args == "T")
  349. value = 1.0;
  350. else if(args == "F")
  351. value = 0.0;
  352. else
  353. return;
  354. int new_midi = bi(value);
  355. //printf("--------------------------------------------\n");
  356. //printf("msg = '%s'\n", msg);
  357. //printf("--------------------------------------------\n");
  358. //printf("new midi value: %f->'%x'\n", value, new_midi);
  359. if(std::get<1>(apple) != -1)
  360. apply_high(new_midi,std::get<1>(apple));
  361. if(std::get<2>(apple) != -1)
  362. apply_low(new_midi,std::get<2>(apple));
  363. }
  364. };
  365. void MidiMappernRT::apply_high(int v, int ID) { apply_midi(v>>7,ID); }
  366. void MidiMappernRT::apply_low(int v, int ID) { apply_midi(0x7f&v,ID);}
  367. void MidiMappernRT::apply_midi(int val, int ID)
  368. {
  369. char buf[1024];
  370. rtosc_message(buf,1024,"/virtual_midi_cc","iii",0,val,ID);
  371. rt_cb(buf);
  372. }
  373. void MidiMappernRT::setBounds(const char *str, float low, float high)
  374. {
  375. if(inv_map.find(str) == inv_map.end())
  376. return;
  377. string addr = str;
  378. auto imap = inv_map[str];
  379. auto newBi = MidiBijection{0,low,high};
  380. inv_map[str] = make_tuple(get<0>(imap),get<1>(imap),get<2>(imap),newBi);
  381. MidiMapperStorage *nstorage = storage->clone();
  382. nstorage->callbacks[get<0>(imap)] = [newBi,addr](int16_t x, MidiMapperStorage::write_cb cb) {
  383. float out = newBi(x);
  384. char buf[1024];
  385. rtosc_message(buf, 1024, addr.c_str(), "f", out);
  386. cb(buf);
  387. };
  388. storage = nstorage;
  389. char buf[1024];
  390. rtosc_message(buf, 1024, "/midi-learn/midi-bind", "b", sizeof(storage), &storage);
  391. rt_cb(buf);
  392. }
  393. std::tuple<float,float,float,float> MidiMappernRT::getBounds(const char *str)
  394. {
  395. const rtosc::Port *p = base_ports->apropos(str);
  396. assert(p);
  397. float min_val = atof(p->meta()["min"]);
  398. float max_val = atof(p->meta()["max"]);
  399. if(inv_map.find(str) != inv_map.end()) {
  400. auto elm = std::get<3>(inv_map[str]);
  401. return std::make_tuple(min_val, max_val,elm.min,elm.max);
  402. }
  403. return std::make_tuple(min_val, max_val,-1.0f,-1.0f);
  404. }
  405. bool MidiMappernRT::has(std::string addr)
  406. {
  407. return inv_map.find(addr) != inv_map.end();
  408. }
  409. bool MidiMappernRT::hasPending(std::string addr)
  410. {
  411. for(auto s:learnQueue)
  412. if(s.first == addr)
  413. return true;
  414. return false;
  415. }
  416. bool MidiMappernRT::hasCoarse(std::string addr)
  417. {
  418. if(!has(addr))
  419. return false;
  420. auto e = inv_map[addr];
  421. return std::get<1>(e) != -1;
  422. }
  423. bool MidiMappernRT::hasFine(std::string addr)
  424. {
  425. if(!has(addr))
  426. return false;
  427. auto e = inv_map[addr];
  428. return std::get<2>(e) != -1;
  429. }
  430. bool MidiMappernRT::hasCoarsePending(std::string addr)
  431. {
  432. for(auto s:learnQueue)
  433. if(s.first == addr && s.second)
  434. return true;
  435. return false;
  436. }
  437. bool MidiMappernRT::hasFinePending(std::string addr)
  438. {
  439. for(auto s:learnQueue)
  440. if(s.first == addr && !s.second)
  441. return true;
  442. return false;
  443. }
  444. int MidiMappernRT::getCoarse(std::string addr)
  445. {
  446. if(!has(addr))
  447. return -1;
  448. auto e = inv_map[addr];
  449. return std::get<1>(e);
  450. }
  451. int MidiMappernRT::getFine(std::string addr)
  452. {
  453. if(!has(addr))
  454. return -1;
  455. auto e = inv_map[addr];
  456. return std::get<2>(e);
  457. }
  458. /*****************
  459. * Realtime code *
  460. *****************/
  461. MidiMapperRT::MidiMapperRT(void)
  462. :storage(NULL), watchSize(0)
  463. {}
  464. void MidiMapperRT::setBackendCb(std::function<void(const char*)> cb) {backend = cb;}
  465. void MidiMapperRT::setFrontendCb(std::function<void(const char*)> cb) {frontend = cb;}
  466. void MidiMapperRT::handleCC(int ID, int val) {
  467. //printf("handling CC(%d,%d){%d,%d,%d}\n", ID, val, (int)storage, pending.has(ID), watchSize);
  468. if((!storage || !storage->handleCC(ID, val, backend)) && !pending.has(ID) && watchSize) {
  469. watchSize--;
  470. pending.insert(ID);
  471. char msg[1024];
  472. rtosc_message(msg, 1024, "/midi-use-CC", "i", ID);
  473. frontend(msg);
  474. }
  475. }
  476. void MidiMapperRT::addWatch(void) {watchSize++;}
  477. void MidiMapperRT::remWatch(void) {if(watchSize) watchSize--;}
  478. const rtosc::Ports MidiMapperRT::ports = {
  479. {"midi-add-watch",0,0, [](msg_t, RtData&d)
  480. {
  481. auto midi = (MidiMapperRT*)d.obj;
  482. midi->addWatch();}},
  483. {"midi-remove-watch",0,0, [](msg_t, RtData&d)
  484. {
  485. auto midi = (MidiMapperRT*)d.obj;
  486. midi->remWatch();}},
  487. {"midi-bind:b","",0, [](msg_t msg, RtData&d)
  488. {
  489. auto &midi = *(MidiMapperRT*)d.obj;
  490. midi.pending.pop();
  491. MidiMapperStorage *nstorage =
  492. *(MidiMapperStorage**)rtosc_argument(msg,0).b.data;
  493. if(midi.storage) {
  494. nstorage->cloneValues(*midi.storage);
  495. midi.storage = nstorage;
  496. } else
  497. midi.storage = nstorage;}}
  498. };
  499. //Depricated
  500. Port MidiMapperRT::addWatchPort(void) {
  501. return Port{"midi-add-watch","",0, [this](msg_t, RtData&) {
  502. this->addWatch();
  503. }};
  504. }
  505. Port MidiMapperRT::removeWatchPort(void) {
  506. return Port{"midi-remove-watch","",0, [this](msg_t, RtData&) {
  507. this->remWatch();
  508. }};
  509. }
  510. Port MidiMapperRT::bindPort(void) {
  511. return Port{"midi-bind:b","",0, [this](msg_t msg, RtData&) {
  512. pending.pop();
  513. MidiMapperStorage *nstorage =
  514. *(MidiMapperStorage**)rtosc_argument(msg,0).b.data;
  515. if(storage) {
  516. nstorage->cloneValues(*storage);
  517. storage = nstorage;
  518. } else
  519. storage = nstorage;
  520. //TODO memory deallocation
  521. }};
  522. }