host_carla.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2012-2013 AGR Audio, Industria e Comercio LTDA. <contato@portalmod.com>
  3. #
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  16. """
  17. This module works as an interface for mod-host, it uses a socket to communicate
  18. with mod-host, the protocol is described in <http://github.com/portalmod/mod-host>
  19. The module relies on tornado.ioloop stuff, but you need to start the ioloop
  20. by yourself:
  21. >>> from tornado import ioloop
  22. >>> ioloop.IOLoop.instance().start()
  23. This will start the mainloop and will handle the callbacks and the async functions
  24. """
  25. import logging
  26. from carla_utils import *
  27. from tornado import ioloop
  28. from mod.host import Host
  29. from mod.protocol import process_resp
  30. class FakeSocket(object):
  31. def write(self, data):
  32. return
  33. def read_until(self, msg, callback):
  34. return
  35. class CarlaHost(Host):
  36. def __init__(self, hmi, prefs, msg_callback):
  37. Host.__init__(self, hmi, prefs, msg_callback)
  38. self.carla = CarlaHostDLL("/usr/lib/carla/libcarla_standalone2.so")
  39. self.carla.set_engine_callback(self.carla_callback)
  40. self.carla.set_engine_option(ENGINE_OPTION_PREFER_PLUGIN_BRIDGES, 0, "")
  41. self.carla.set_engine_option(ENGINE_OPTION_PREFER_UI_BRIDGES, 0, "")
  42. self.carla.set_engine_option(ENGINE_OPTION_PROCESS_MODE, ENGINE_PROCESS_MODE_MULTIPLE_CLIENTS, "")
  43. self.carla.set_engine_option(ENGINE_OPTION_TRANSPORT_MODE, ENGINE_TRANSPORT_MODE_JACK, "")
  44. self.carla.set_engine_option(ENGINE_OPTION_PATH_BINARIES, 0, "/usr/lib/carla/")
  45. self.carla.set_engine_option(ENGINE_OPTION_PATH_RESOURCES, 0, "/usr/share/carla/resources/")
  46. self.carlatimer = ioloop.PeriodicCallback(self.carlatimer_callback, 300)
  47. self._client_id_system = -1
  48. self._plugins_info = []
  49. def __del__(self):
  50. if self.carla.is_engine_running():
  51. self.carlatimer.stop()
  52. self.carla.engine_close()
  53. #Host.__del__(self)
  54. def open_connection_if_needed(self, websocket):
  55. if self.readsock is not None and self.writesock is not None:
  56. self.report_current_state(websocket)
  57. return
  58. if not self.carla.engine_init("JACK", "MOD"):
  59. return
  60. if self.readsock is None:
  61. self.readsock = FakeSocket()
  62. if self.writesock is None:
  63. self.writesock = FakeSocket()
  64. self.connected = True
  65. self.report_current_state(websocket)
  66. self.statstimer.start()
  67. self.carlatimer.start()
  68. if self.memtimer is not None:
  69. self.memtimer_callback()
  70. self.memtimer.start()
  71. if len(self._queue):
  72. self.process_write_queue()
  73. else:
  74. self._idle = True
  75. def process_write_queue(self):
  76. try:
  77. msg, callback, datatype = self._queue.pop(0)
  78. logging.info("[host] popped from queue: %s" % msg)
  79. except IndexError:
  80. self._idle = True
  81. return
  82. if self.writesock is None:
  83. self.process_write_queue()
  84. return
  85. self._idle = False
  86. logging.info("[host] sending -> %s" % msg)
  87. print(msg)
  88. ret = self.send_carla_msg(msg)
  89. if callback is not None:
  90. callback(process_resp(ret, datatype))
  91. self.process_write_queue()
  92. def send_carla_msg(self, msg):
  93. if msg == "remove -1":
  94. self.carla.remove_all_plugins()
  95. return True
  96. data = msg.split(" ",1)
  97. cmd = data[0]
  98. if len(data) == 2:
  99. data = data[1]
  100. else:
  101. data = None
  102. if cmd == "add":
  103. uri, ret = data.split(" ",1)
  104. if not self.carla.add_plugin(BINARY_NATIVE, PLUGIN_LV2, None, "effect_"+ret, uri, 0, None, 0x0):
  105. return -1
  106. return int(ret)
  107. def _getPluginId(self, instance):
  108. for i in range(len(self._plugins_info)):
  109. if self._plugins_info[i]['name'] == instance:
  110. return i
  111. return -1
  112. # host stuff
  113. def _get(self, subject):
  114. if subject == "/graph":
  115. self._client_id_system = -1
  116. self.carla.patchbay_refresh(True)
  117. return
  118. def _add_plugin(self, instance, uri, enabled, x, y, callback):
  119. if self.carla.add_plugin(BINARY_NATIVE, PLUGIN_LV2, "", instance, uri, 0, None, 0x0):
  120. if enabled:
  121. self.carla.set_active(self.carla.get_current_plugin_count()-1, True)
  122. callback(True)
  123. else:
  124. callback(False)
  125. def _remove_plugin(self, instance, callback):
  126. pluginId = self._getPluginId(instance)
  127. if pluginId >= 0:
  128. self.carla.remove_plugin(pluginId)
  129. callback(True)
  130. else:
  131. callback(False)
  132. def _enable(self, instance, enabled, callback):
  133. pluginId = self._getPluginId(instance)
  134. if pluginId >= 0:
  135. self.carla.set_active(pluginId, enabled)
  136. callback(True)
  137. else:
  138. callback(False)
  139. def _param_set(self, port, value, callback):
  140. instance, port = port.rsplit("/", 1)
  141. pluginId = self._getPluginId(instance)
  142. if pluginId >= 0:
  143. #parameterId = self._plugins_info[pluginId]['symbols'][parameterId]
  144. #self.carla.set_parameter_value(pluginId, parameterId, value)
  145. callback(True)
  146. else:
  147. callback(False)
  148. def _connect(self, port_from, port_to, callback):
  149. # TODO
  150. #split_from = port_from.split("/")
  151. #if len(split_from) != 3:
  152. #return
  153. #if split_from[1] == "system":
  154. #groupIdA = self._client_id_system
  155. #portIdA = int(split_from[2].rsplit("_",1)[-1])
  156. #instance_from, port_from = port_from.rsplit("/", 1)
  157. #else:
  158. #groupIdB = self._getPluginId(split_from[:1].join("/"))
  159. #portIdB = int(split_from[2].rsplit("_",1)[-1])
  160. #instance_from, port_from = port_from.rsplit("/", 1)
  161. #self.carla.patchbay_connect()
  162. callback(True)
  163. def carla_callback(self, host, action, pluginId, value1, value2, value3, valueStr):
  164. valueStr = charPtrToString(valueStr)
  165. print("carla callback", host, action, pluginId, value1, value2, value3, valueStr)
  166. return
  167. # Debug.
  168. # This opcode is undefined and used only for testing purposes.
  169. if action == ENGINE_CALLBACK_DEBUG:
  170. return
  171. # A plugin has been added.
  172. # @a pluginId Plugin Id
  173. # @a valueStr Plugin name
  174. if action == ENGINE_CALLBACK_PLUGIN_ADDED:
  175. if pluginId != len(self._plugins_info):
  176. return
  177. info = self.carla.get_plugin_info(pluginId)
  178. self._plugins_info.append(info)
  179. uri = info['label']
  180. x = 0.0
  181. y = 0.0
  182. msg = """[]
  183. a <http://lv2plug.in/ns/ext/patch#Put> ;
  184. <http://lv2plug.in/ns/ext/patch#subject> <%s> ;
  185. <http://lv2plug.in/ns/ext/patch#body> [
  186. <http://drobilla.net/ns/ingen#canvasX> "%.1f"^^<http://www.w3.org/2001/XMLSchema#float> ;
  187. <http://drobilla.net/ns/ingen#canvasY> "%.1f"^^<http://www.w3.org/2001/XMLSchema#float> ;
  188. <http://drobilla.net/ns/ingen#enabled> true ;
  189. <http://lv2plug.in/ns/lv2core#prototype> <%s> ;
  190. a <http://drobilla.net/ns/ingen#Block> ;
  191. ] .
  192. """ % (valueStr, x, y, uri)
  193. self.plugin_added_callback(valueStr, uri, False, x, y)
  194. self.msg_callback(msg)
  195. return
  196. # A plugin has been removed.
  197. # @a pluginId Plugin Id
  198. if action == ENGINE_CALLBACK_PLUGIN_REMOVED:
  199. if pluginId >= len(self._plugins_info):
  200. return
  201. info = self._plugins_info.pop(pluginId)
  202. msg = """[]
  203. a <http://lv2plug.in/ns/ext/patch#Delete> ;
  204. <http://lv2plug.in/ns/ext/patch#subject> <%s> .
  205. """ % (info['name'])
  206. self.plugin_removed_callback(info['name'])
  207. self.msg_callback(msg)
  208. return
  209. # A plugin has been renamed.
  210. # @a pluginId Plugin Id
  211. # @a valueStr New plugin name
  212. if action == ENGINE_CALLBACK_PLUGIN_RENAMED:
  213. return
  214. # A plugin has become unavailable.
  215. # @a pluginId Plugin Id
  216. # @a valueStr Related error string
  217. if action == ENGINE_CALLBACK_PLUGIN_UNAVAILABLE:
  218. return
  219. # A parameter value has changed.
  220. # @a pluginId Plugin Id
  221. # @a value1 Parameter index
  222. # @a value3 New parameter value
  223. if action == ENGINE_CALLBACK_PARAMETER_VALUE_CHANGED:
  224. return
  225. # A parameter default has changed.
  226. # @a pluginId Plugin Id
  227. # @a value1 Parameter index
  228. # @a value3 New default value
  229. if action == ENGINE_CALLBACK_PARAMETER_DEFAULT_CHANGED:
  230. return
  231. # A parameter's MIDI CC has changed.
  232. # @a pluginId Plugin Id
  233. # @a value1 Parameter index
  234. # @a value2 New MIDI CC
  235. if action == ENGINE_CALLBACK_PARAMETER_MIDI_CC_CHANGED:
  236. return
  237. # A parameter's MIDI channel has changed.
  238. # @a pluginId Plugin Id
  239. # @a value1 Parameter index
  240. # @a value2 New MIDI channel
  241. if action == ENGINE_CALLBACK_PARAMETER_MIDI_CHANNEL_CHANGED:
  242. return
  243. # A plugin option has changed.
  244. # @a pluginId Plugin Id
  245. # @a value1 Option
  246. # @a value2 New on/off state (1 for on, 0 for off)
  247. # @see PluginOptions
  248. if action == ENGINE_CALLBACK_OPTION_CHANGED:
  249. return
  250. # The current program of a plugin has changed.
  251. # @a pluginId Plugin Id
  252. # @a value1 New program index
  253. if action == ENGINE_CALLBACK_PROGRAM_CHANGED:
  254. return
  255. # The current MIDI program of a plugin has changed.
  256. # @a pluginId Plugin Id
  257. # @a value1 New MIDI program index
  258. if action == ENGINE_CALLBACK_MIDI_PROGRAM_CHANGED:
  259. return
  260. # A plugin's custom UI state has changed.
  261. # @a pluginId Plugin Id
  262. # @a value1 New state, as follows:
  263. # 0: UI is now hidden
  264. # 1: UI is now visible
  265. # -1: UI has crashed and should not be shown again
  266. if action == ENGINE_CALLBACK_UI_STATE_CHANGED:
  267. return
  268. # A note has been pressed.
  269. # @a pluginId Plugin Id
  270. # @a value1 Channel
  271. # @a value2 Note
  272. # @a value3 Velocity
  273. if action == ENGINE_CALLBACK_NOTE_ON:
  274. return
  275. # A note has been released.
  276. # @a pluginId Plugin Id
  277. # @a value1 Channel
  278. # @a value2 Note
  279. if action == ENGINE_CALLBACK_NOTE_OFF:
  280. return
  281. # A plugin needs update.
  282. # @a pluginId Plugin Id
  283. if action == ENGINE_CALLBACK_UPDATE:
  284. return
  285. # A plugin's data/information has changed.
  286. # @a pluginId Plugin Id
  287. if action == ENGINE_CALLBACK_RELOAD_INFO:
  288. return
  289. # A plugin's parameters have changed.
  290. # @a pluginId Plugin Id
  291. if action == ENGINE_CALLBACK_RELOAD_PARAMETERS:
  292. return
  293. # A plugin's programs have changed.
  294. # @a pluginId Plugin Id
  295. if action == ENGINE_CALLBACK_RELOAD_PROGRAMS:
  296. return
  297. # A plugin state has changed.
  298. # @a pluginId Plugin Id
  299. if action == ENGINE_CALLBACK_RELOAD_ALL:
  300. return
  301. # A patchbay client has been added.
  302. # @a pluginId Client Id
  303. # @a value1 Client icon
  304. # @a value2 Plugin Id (-1 if not a plugin)
  305. # @a valueStr Client name
  306. # @see PatchbayIcon
  307. if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_ADDED:
  308. if valueStr == "system":
  309. self._client_id_system = pluginId
  310. return
  311. # A patchbay client has been removed.
  312. # @a pluginId Client Id
  313. if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_REMOVED:
  314. if self._client_id_system == pluginId:
  315. self._client_id_system = -1
  316. return
  317. # A patchbay client has been renamed.
  318. # @a pluginId Client Id
  319. # @a valueStr New client name
  320. if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_RENAMED:
  321. return
  322. # A patchbay client data has changed.
  323. # @a pluginId Client Id
  324. # @a value1 New icon
  325. # @a value2 New plugin Id (-1 if not a plugin)
  326. # @see PatchbayIcon
  327. if action == ENGINE_CALLBACK_PATCHBAY_CLIENT_DATA_CHANGED:
  328. return
  329. # A patchbay port has been added.
  330. # @a pluginId Client Id
  331. # @a value1 Port Id
  332. # @a value2 Port hints
  333. # @a valueStr Port name
  334. # @see PatchbayPortHints
  335. if action == ENGINE_CALLBACK_PATCHBAY_PORT_ADDED:
  336. if self._client_id_system == pluginId:
  337. if value2 & PATCHBAY_PORT_TYPE_MIDI:
  338. types = "<http://lv2plug.in/ns/ext/atom#bufferType> <http://lv2plug.in/ns/ext/atom#Sequence> ;\n"
  339. types += "a <http://lv2plug.in/ns/ext/atom#AtomPort> ,\n"
  340. elif value2 & PATCHBAY_PORT_TYPE_AUDIO:
  341. types = "a <http://lv2plug.in/ns/lv2core#AudioPort> ,\n"
  342. elif value2 & PATCHBAY_PORT_TYPE_CV:
  343. types = "a <http://lv2plug.in/ns/lv2core#CVPort> ,\n"
  344. else:
  345. return
  346. if value2 & PATCHBAY_PORT_IS_INPUT:
  347. types += "<http://lv2plug.in/ns/lv2core#OutputPort>\n"
  348. else:
  349. types += "<http://lv2plug.in/ns/lv2core#InputPort>\n"
  350. msg = """[]
  351. a <http://lv2plug.in/ns/ext/patch#Put> ;
  352. <http://lv2plug.in/ns/ext/patch#subject> </graph/system/%s> ;
  353. <http://lv2plug.in/ns/ext/patch#body> [
  354. <http://lv2plug.in/ns/lv2core#index> "0"^^<http://www.w3.org/2001/XMLSchema#int> ;
  355. <http://lv2plug.in/ns/lv2core#name> "%s" ;
  356. %s
  357. ] .
  358. """ % (valueStr, valueStr.title().replace("_", " "), types)
  359. self.msg_callback(msg)
  360. return
  361. # A patchbay port has been removed.
  362. # @a pluginId Client Id
  363. # @a value1 Port Id
  364. if action == ENGINE_CALLBACK_PATCHBAY_PORT_REMOVED:
  365. return
  366. # A patchbay port has been renamed.
  367. # @a pluginId Client Id
  368. # @a value1 Port Id
  369. # @a valueStr New port name
  370. if action == ENGINE_CALLBACK_PATCHBAY_PORT_RENAMED:
  371. return
  372. # A patchbay connection has been added.
  373. # @a pluginId Connection Id
  374. # @a valueStr Out group, port plus in group and port, in "og:op:ig:ip" syntax.
  375. if action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_ADDED:
  376. return
  377. # A patchbay connection has been removed.
  378. # @a pluginId Connection Id
  379. if action == ENGINE_CALLBACK_PATCHBAY_CONNECTION_REMOVED:
  380. return
  381. # Engine started.
  382. # @a value1 Process mode
  383. # @a value2 Transport mode
  384. # @a valuestr Engine driver
  385. # @see EngineProcessMode
  386. # @see EngineTransportMode
  387. if action == ENGINE_CALLBACK_ENGINE_STARTED:
  388. return
  389. # Engine stopped.
  390. if action == ENGINE_CALLBACK_ENGINE_STOPPED:
  391. return
  392. # Engine process mode has changed.
  393. # @a value1 New process mode
  394. # @see EngineProcessMode
  395. if action == ENGINE_CALLBACK_PROCESS_MODE_CHANGED:
  396. return
  397. # Engine transport mode has changed.
  398. # @a value1 New transport mode
  399. # @see EngineTransportMode
  400. if action == ENGINE_CALLBACK_TRANSPORT_MODE_CHANGED:
  401. return
  402. # Engine buffer-size changed.
  403. # @a value1 New buffer size
  404. if action == ENGINE_CALLBACK_BUFFER_SIZE_CHANGED:
  405. return
  406. # Engine sample-rate changed.
  407. # @a value3 New sample rate
  408. if action == ENGINE_CALLBACK_SAMPLE_RATE_CHANGED:
  409. return
  410. # NSM callback.
  411. # (Work in progress, values are not defined yet)
  412. if action == ENGINE_CALLBACK_NSM:
  413. return
  414. # Idle frontend.
  415. # This is used by the engine during long operations that might block the frontend,
  416. # giving it the possibility to idle while the operation is still in place.
  417. if action == ENGINE_CALLBACK_IDLE:
  418. return
  419. # Show a message as information.
  420. # @a valueStr The message
  421. if action == ENGINE_CALLBACK_INFO:
  422. return
  423. # Show a message as an error.
  424. # @a valueStr The message
  425. if action == ENGINE_CALLBACK_ERROR:
  426. return
  427. # The engine has crashed or malfunctioned and will no longer work.
  428. if action == ENGINE_CALLBACK_QUIT:
  429. return
  430. def carlatimer_callback(self):
  431. self.carla.engine_idle()