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.

350 lines
10KB

  1. /*
  2. Copyright 2007-2016 David Robillard <http://drobilla.net>
  3. Permission to use, copy, modify, and/or distribute this software for any
  4. purpose with or without fee is hereby granted, provided that the above
  5. copyright notice and this permission notice appear in all copies.
  6. THIS SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  7. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  8. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  9. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  10. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  11. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  12. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  13. */
  14. #include <assert.h>
  15. #include <math.h>
  16. #include <sndfile.h>
  17. #include <stdarg.h>
  18. #include <stdio.h>
  19. #include <stdlib.h>
  20. #include <string.h>
  21. #include "lilv/lilv.h"
  22. /** Control port value set from the command line */
  23. typedef struct Param {
  24. const char* sym; ///< Port symbol
  25. float value; ///< Control value
  26. } Param;
  27. /** Port type (only float ports are supported) */
  28. typedef enum {
  29. TYPE_CONTROL,
  30. TYPE_AUDIO
  31. } PortType;
  32. /** Runtime port information */
  33. typedef struct {
  34. const LilvPort* lilv_port; ///< Port description
  35. PortType type; ///< Datatype
  36. uint32_t index; ///< Port index
  37. float value; ///< Control value (if applicable)
  38. bool is_input; ///< True iff an input port
  39. bool optional; ///< True iff connection optional
  40. } Port;
  41. /** Application state */
  42. typedef struct {
  43. LilvWorld* world;
  44. const LilvPlugin* plugin;
  45. LilvInstance* instance;
  46. const char* in_path;
  47. const char* out_path;
  48. SNDFILE* in_file;
  49. SNDFILE* out_file;
  50. unsigned n_params;
  51. Param* params;
  52. unsigned n_ports;
  53. unsigned n_audio_in;
  54. unsigned n_audio_out;
  55. Port* ports;
  56. } LV2Apply;
  57. static int fatal(LV2Apply* self, int status, const char* fmt, ...);
  58. /** Open a sound file with error handling. */
  59. static SNDFILE*
  60. sopen(LV2Apply* self, const char* path, int mode, SF_INFO* fmt)
  61. {
  62. SNDFILE* file = sf_open(path, mode, fmt);
  63. const int st = sf_error(file);
  64. if (st) {
  65. fatal(self, 1, "Failed to open %s (%s)\n", path, sf_error_number(st));
  66. return NULL;
  67. }
  68. return file;
  69. }
  70. /** Close a sound file with error handling. */
  71. static void
  72. sclose(const char* path, SNDFILE* file)
  73. {
  74. int st;
  75. if (file && (st = sf_close(file))) {
  76. fatal(NULL, 1, "Failed to close %s (%s)\n", path, sf_error_number(st));
  77. }
  78. }
  79. /**
  80. Read a single frame from a file into an interleaved buffer.
  81. If more channels are required than are available in the file, the remaining
  82. channels are distributed in a round-robin fashion (LRLRL).
  83. */
  84. static bool
  85. sread(SNDFILE* file, unsigned file_chans, float* buf, unsigned buf_chans)
  86. {
  87. const sf_count_t n_read = sf_readf_float(file, buf, 1);
  88. for (unsigned i = file_chans - 1; i < buf_chans; ++i) {
  89. buf[i] = buf[i % file_chans];
  90. }
  91. return n_read == 1;
  92. }
  93. /** Clean up all resources. */
  94. static int
  95. cleanup(int status, LV2Apply* self)
  96. {
  97. sclose(self->in_path, self->in_file);
  98. sclose(self->out_path, self->out_file);
  99. lilv_instance_free(self->instance);
  100. lilv_world_free(self->world);
  101. free(self->ports);
  102. free(self->params);
  103. return status;
  104. }
  105. /** Print a fatal error and clean up for exit. */
  106. static int
  107. fatal(LV2Apply* self, int status, const char* fmt, ...)
  108. {
  109. va_list args;
  110. va_start(args, fmt);
  111. fprintf(stderr, "error: ");
  112. vfprintf(stderr, fmt, args);
  113. va_end(args);
  114. return self ? cleanup(status, self) : status;
  115. }
  116. /**
  117. Create port structures from data (via create_port()) for all ports.
  118. */
  119. static int
  120. create_ports(LV2Apply* self)
  121. {
  122. LilvWorld* world = self->world;
  123. const uint32_t n_ports = lilv_plugin_get_num_ports(self->plugin);
  124. self->n_ports = n_ports;
  125. self->ports = (Port*)calloc(self->n_ports, sizeof(Port));
  126. /* Get default values for all ports */
  127. float* values = (float*)calloc(n_ports, sizeof(float));
  128. lilv_plugin_get_port_ranges_float(self->plugin, NULL, NULL, values);
  129. LilvNode* lv2_InputPort = lilv_new_uri(world, LV2_CORE__InputPort);
  130. LilvNode* lv2_OutputPort = lilv_new_uri(world, LV2_CORE__OutputPort);
  131. LilvNode* lv2_AudioPort = lilv_new_uri(world, LV2_CORE__AudioPort);
  132. LilvNode* lv2_ControlPort = lilv_new_uri(world, LV2_CORE__ControlPort);
  133. LilvNode* lv2_connectionOptional = lilv_new_uri(world, LV2_CORE__connectionOptional);
  134. for (uint32_t i = 0; i < n_ports; ++i) {
  135. Port* port = &self->ports[i];
  136. const LilvPort* lport = lilv_plugin_get_port_by_index(self->plugin, i);
  137. port->lilv_port = lport;
  138. port->index = i;
  139. port->value = isnan(values[i]) ? values[i] : 0.0f;
  140. port->optional = lilv_port_has_property(
  141. self->plugin, lport, lv2_connectionOptional);
  142. /* Check if port is an input or output */
  143. if (lilv_port_is_a(self->plugin, lport, lv2_InputPort)) {
  144. port->is_input = true;
  145. } else if (!lilv_port_is_a(self->plugin, lport, lv2_OutputPort) &&
  146. !port->optional) {
  147. return fatal(self, 1, "Port %d is neither input nor output\n", i);
  148. }
  149. /* Check if port is an audio or control port */
  150. if (lilv_port_is_a(self->plugin, lport, lv2_ControlPort)) {
  151. port->type = TYPE_CONTROL;
  152. } else if (lilv_port_is_a(self->plugin, lport, lv2_AudioPort)) {
  153. port->type = TYPE_AUDIO;
  154. if (port->is_input) {
  155. ++self->n_audio_in;
  156. } else {
  157. ++self->n_audio_out;
  158. }
  159. } else if (!port->optional) {
  160. return fatal(self, 1, "Port %d has unsupported type\n", i);
  161. }
  162. }
  163. lilv_node_free(lv2_connectionOptional);
  164. lilv_node_free(lv2_ControlPort);
  165. lilv_node_free(lv2_AudioPort);
  166. lilv_node_free(lv2_OutputPort);
  167. lilv_node_free(lv2_InputPort);
  168. free(values);
  169. return 0;
  170. }
  171. static void
  172. print_version(void)
  173. {
  174. printf(
  175. "lv2apply (lilv) " LILV_VERSION "\n"
  176. "Copyright 2007-2016 David Robillard <http://drobilla.net>\n"
  177. "License: <http://www.opensource.org/licenses/isc-license>\n"
  178. "This is free software: you are free to change and redistribute it.\n"
  179. "There is NO WARRANTY, to the extent permitted by law.\n");
  180. }
  181. static int
  182. print_usage(int status)
  183. {
  184. fprintf(status ? stderr : stdout,
  185. "Usage: lv2apply [OPTION]... PLUGIN_URI\n"
  186. "Apply an LV2 plugin to an audio file.\n\n"
  187. " -i IN_FILE Input file\n"
  188. " -o OUT_FILE Output file\n"
  189. " -c SYM VAL Control value\n"
  190. " --help Display this help and exit\n"
  191. " --version Display version information and exit\n");
  192. return status;
  193. }
  194. int
  195. main(int argc, char** argv)
  196. {
  197. LV2Apply self = {
  198. NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, 0, 0, 0, NULL
  199. };
  200. /* Parse command line arguments */
  201. const char* plugin_uri = NULL;
  202. for (int i = 1; i < argc; ++i) {
  203. if (!strcmp(argv[i], "--version")) {
  204. print_version();
  205. return 0;
  206. } else if (!strcmp(argv[i], "--help")) {
  207. return print_usage(0);
  208. } else if (!strcmp(argv[i], "-i")) {
  209. self.in_path = argv[++i];
  210. } else if (!strcmp(argv[i], "-o")) {
  211. self.out_path = argv[++i];
  212. } else if (!strcmp(argv[i], "-c")) {
  213. if (argc < i + 3) {
  214. return fatal(&self, 1, "Missing argument for -c\n");
  215. }
  216. self.params = (Param*)realloc(self.params,
  217. ++self.n_params * sizeof(Param));
  218. self.params[self.n_params - 1].sym = argv[++i];
  219. self.params[self.n_params - 1].value = atof(argv[++i]);
  220. } else if (argv[i][0] == '-') {
  221. free(self.params);
  222. return print_usage(1);
  223. } else if (i == argc - 1) {
  224. plugin_uri = argv[i];
  225. }
  226. }
  227. /* Check that required arguments are given */
  228. if (!self.in_path || !self.out_path || !plugin_uri) {
  229. free(self.params);
  230. return print_usage(1);
  231. }
  232. /* Create world and plugin URI */
  233. self.world = lilv_world_new();
  234. LilvNode* uri = lilv_new_uri(self.world, plugin_uri);
  235. if (!uri) {
  236. return fatal(&self, 2, "Invalid plugin URI <%s>\n", plugin_uri);
  237. }
  238. /* Discover world */
  239. lilv_world_load_all(self.world);
  240. /* Get plugin */
  241. const LilvPlugins* plugins = lilv_world_get_all_plugins(self.world);
  242. const LilvPlugin* plugin = lilv_plugins_get_by_uri(plugins, uri);
  243. lilv_node_free(uri);
  244. if (!(self.plugin = plugin)) {
  245. return fatal(&self, 3, "Plugin <%s> not found\n", plugin_uri);
  246. }
  247. /* Open input file */
  248. SF_INFO in_fmt = { 0, 0, 0, 0, 0, 0 };
  249. if (!(self.in_file = sopen(&self, self.in_path, SFM_READ, &in_fmt))) {
  250. return 4;
  251. }
  252. /* Create port structures */
  253. if (create_ports(&self)) {
  254. return 5;
  255. }
  256. if (in_fmt.channels != (int)self.n_audio_in && in_fmt.channels != 1) {
  257. return fatal(&self, 6, "Unable to map %d inputs to %d ports\n",
  258. in_fmt.channels, self.n_audio_in);
  259. }
  260. /* Set control values */
  261. for (unsigned i = 0; i < self.n_params; ++i) {
  262. const Param* param = &self.params[i];
  263. LilvNode* sym = lilv_new_string(self.world, param->sym);
  264. const LilvPort* port = lilv_plugin_get_port_by_symbol(plugin, sym);
  265. lilv_node_free(sym);
  266. if (!port) {
  267. return fatal(&self, 7, "Unknown port `%s'\n", param->sym);
  268. }
  269. self.ports[lilv_port_get_index(plugin, port)].value = param->value;
  270. }
  271. /* Open output file */
  272. SF_INFO out_fmt = in_fmt;
  273. out_fmt.channels = self.n_audio_out;
  274. if (!(self.out_file = sopen(&self, self.out_path, SFM_WRITE, &out_fmt))) {
  275. return 8;
  276. }
  277. /* Instantiate plugin and connect ports */
  278. const uint32_t n_ports = lilv_plugin_get_num_ports(plugin);
  279. float in_buf[self.n_audio_in];
  280. float out_buf[self.n_audio_out];
  281. self.instance = lilv_plugin_instantiate(
  282. self.plugin, in_fmt.samplerate, NULL);
  283. for (uint32_t p = 0, i = 0, o = 0; p < n_ports; ++p) {
  284. if (self.ports[p].type == TYPE_CONTROL) {
  285. lilv_instance_connect_port(self.instance, p, &self.ports[p].value);
  286. } else if (self.ports[p].type == TYPE_AUDIO) {
  287. if (self.ports[p].is_input) {
  288. lilv_instance_connect_port(self.instance, p, in_buf + i++);
  289. } else {
  290. lilv_instance_connect_port(self.instance, p, out_buf + o++);
  291. }
  292. } else {
  293. lilv_instance_connect_port(self.instance, p, NULL);
  294. }
  295. }
  296. /* Ports are now connected to buffers in interleaved format, so we can run
  297. a single frame at a time and avoid having to interleave buffers to
  298. read/write from/to sndfile. */
  299. while (sread(self.in_file, in_fmt.channels, in_buf, self.n_audio_in)) {
  300. lilv_instance_run(self.instance, 1);
  301. if (sf_writef_float(self.out_file, out_buf, 1) != 1) {
  302. return fatal(&self, 9, "Failed to write to output file\n");
  303. }
  304. }
  305. return cleanup(0, &self);
  306. }