]> Shamusworld >> Repos - ardour-manual/blob - include/lua-scripting.html
re-organize lua scripting doc
[ardour-manual] / include / lua-scripting.html
1
2 <p>
3 Starting with version 4.7.213, Ardour supports Lua scripts.
4 </p>
5
6
7 <p class="warning">
8 This Documentation is Work in Progress and far from complete. Also the documented API may be subject to change.
9 </p>
10
11 <h2 id="Preface">Preface</h2>
12 <p>
13 There are cases that a Ardour cannot reasonably cater for with core functionality by itself, either because they're session specific or user specific edge cases.
14 </p><p>
15 Examples for these include voice-activate (record-arm specific tracks and roll transport depending on signal levels),
16 rename all regions after a specific timecode, launch an external application when a certain track is soloed, generate automation curves
17 or simply provide a quick shortcut for a custom batch operation.
18 </p><p>
19 Cases like this call for means to extend the DAW without actually changing the DAW itself. This is where scripting comes in.
20 </p><p>
21 "Scripting" refers to tasks that could alternatively be executed step-by-step by a human operator.
22 </p><p>
23 Lua is a tiny and simple language which is easy to learn, yet allows for comprehensive solutions.
24 Lua is also a glue language it allows to tie existing component in Ardour together in unprecedented ways,
25 and most importantly Lua is one of the few scripting-languages which can be safely used in a real-time environment.
26 </p><p>
27 A good introduction to Lua is the book <a href="http://www.lua.org/pil/">Programming in Lua</a>. The first edition is available online,
28 but if you have the means buy a copy of the book, it not only helps to support the Lua project,
29 but provides for a much nicer reading and learning experience.
30 </p>
31
32 <h2 id="Overview">Overview</h2>
33 <p>
34 The core of ardour is a real-time audio engine that runs and processes audio. One interfaces with than engine by sending it commands.
35 Scripting can be used to interact with or modify active Ardour session. Just like a user uses the Editor/Mixer GUI to modify the state or parameters of the session.
36 </p><p>
37 Doing this programmatically requires some knowledge about the objects used internally.
38 Most Ardour C++ objects and their methods are directly exposed to Lua and one can call functions or modify variables:
39 </p>
40
41 <div style="width:80%; margin:.5em auto;">
42         <div style="width:45%; float:left;">
43                 C++<br/>
44                 <code class="cxx">
45                         session-&gt;set_transport_speed (1.0);
46                 </code>
47         </div>
48         <div style="width:45%; float:right;">
49                 Lua<br/>
50                 <code class="lua">
51                         Session:set_transport_speed (1.0)
52                 </code>
53         </div>
54 </div>
55 <div style="clear:both;"></div>
56
57 <p>
58 You may notice that there is only a small syntactic difference, in this case.
59 While C++ requires recompiling the application for every change, Lua script can be loaded, written or modified while the application is running.
60 Lua also abstracts away many of the C++ complexities such as object lifetime, type conversion and null-pointer checks.
61 </p><p>
62 Close ties with the underlying C++ components is where the power of scripting comes from.
63 A script can orchestrate interaction of lower-level components which take the bulk of the CPU time of the final program.
64 </p>
65 </p><p>
66 At the time of writing Ardour integrates Lua 5.3.2: <a href="http://www.lua.org/manual/5.3/manual.html">Lua 5.3 reference manual</a>.
67 </p>
68
69 <h2 id="Integration">Integration</h2>
70 <p>
71 Like Control surfaces and the GUI, Lua Scripts are confined to certain aspects of the program. Ardour provides the framework and runs Lua (not the other way around).
72 </p>
73 <p>
74 In Ardour's case Lua is available:
75 </p>
76
77 <dl>
78         <dt>Editor Action Scripts</dt><dd>User initiated actions (menu, shortcuts) for batch processing</dd>
79         <dt>Editor Hooks/Callbacks</dt><dd>Event triggered actions for the Editor/Mixer GUI</dd>
80         <dt>Session Scripts</dt><dd>Scripts called at the start of every audio cycle (session, real-time)</dd>
81         <dt>DSP Scripts</dt><dd>Audio/Midi processor - plugins with access to the Ardour session (per track/bus, real-time)</dd>
82         <dt>Script Console</dt><dd>Action Script commandline</dd>
83 </dl>
84
85 <p>
86 There are is also a special mode:
87 </p>
88 <dl>
89         <dt>Commandline Tool</dt><dd>Replaces the complete Editor GUI, direct access to libardour (no GUI) from the commandline.<br/>
90         <em>Be aware that the vast majority of complex functionality is provided by the Editor UI.</em></dd>
91 </dl>
92
93 <h2 id="Managing Scripts">Managing Scripts</h2>
94
95 <p>
96 Ardour searches for Lua scripts in the <code>scripts</code> folder in <code>$ARDOUR_DATA_PATH</code>,
97 Apart from scripts included directly with Ardour, this includes</p>
98 <table>
99         <tr><th>GNU/Linux</th><td><code>$HOME/.config/ardour5/scripts</code></td></tr>
100         <tr><th>Mac OS X</th><td><code>$HOME/Library/Preferences/Ardour5/scripts</code></td></tr>
101         <tr><th>Windows</th><td><code>%localappdata%\ardour5\scripts</code></td></tr>
102 </table>
103
104 <p>Files must end with <code>.lua</code> file extension.</p>
105
106 <p>Scripts are managed via the GUI</p>
107 <dl>
108         <dt>Editor Action Scripts</dt><dd>Menu &rarr; Edit &rarr; Scripted Actions &rarr; Manage</dd>
109         <dt>Editor Hooks/Callbacks</dt><dd>Menu &rarr; Edit &rarr; Scripted Actions &rarr; Manage</dd>
110         <dt>Session Scripts</dt><dd>Menu &rarr; Session &rarr; Scripting &rarr; Add/Remove Script</dd>
111         <dt>DSP Scripts</dt><dd>Mixer-strip &rarr; context menu (right click) &rarr; New Lua Proc</dd>
112         <dt>Script Console</dt><dd>Menu &rarr; Window &rarr; Scripting</dd>
113 </dl>
114
115 <h2 id="Script Layout">Script Layout</h2>
116 <ul>
117         <li>Every script must include an <code>ardour</code> descriptor table. Required fields are "Name" and "Type".</li>
118         <li>A script must provide a <em>Factory method</em>: A function with optional instantiation parameters which returns the actual script.</li>
119         <li>[optional]: list of parameters for the "factory".</li>
120         <li>in case of DSP scripts, an optional list of automatable parameters and possible audio/midi port configurations, and a <code>dsp_run</code> function, more on that later.</li>
121 </ul>
122
123
124 <p>A minimal example script looks like:</p>
125 <div>
126 <pre><code class="lua">
127         ardour {
128           ["type"]    = "EditorAction",
129           name        = "Rewind",
130         }
131
132         function factory (unused_params)
133           return function ()
134            Session:goto_start()  -- rewind the transport
135           end
136         end
137 </code></pre>
138 </div>
139
140 <p>
141 The common part for all scripts is the "Descriptor". It's a Lua function which returns a table (key/values) with the following keys (the keys are case-sensitive):
142 </p>
143 <dl>
144         <dt>type [required]</dt><dd>one of "<code>DSP</code>", "<code>Session</code>", "<code>EditorHook</code>", "<code>EditorAction</code>" (the type is not case-sensitive)</dd>
145         <dt>name [required]</dt><dd>Name/Title of the script</dd>
146         <dt>author</dt><dd>Your Name</dd>
147         <dt>license</dt><dd>The license of the script (e.g. "GPL" or "MIT")</dd>
148         <dt>description</dt><dd>A longer text explaining to the user what the script does</dd>
149 </dl>
150
151 <p class="note">
152 Scripts that come with Ardour (currently mostly examples) can be found in the <a href="https://github.com/Ardour/ardour/tree/master/scripts">Source Tree</a>.
153 </p>
154
155 <h3 id="Action Scripts">Action Scripts</h3>
156 <p>Action scripts are the simplest form. An anonymous Lua function is called whenever the action is triggered. A simple action script is shown above.</p>
157 <p>There are 10 action script slots available, each of which is a standard GUI action available from the menu and hence can be bound to a keyboard shortcut</p>
158
159 <h3 id="Session Scripts">Session Scripts</h3>
160 <p>Session scripts similar to Actions Scripts, except the anonymous function is called periodically every process cycle.
161 The function receives a single parameter - the number of audio samples which are processed in the given cycle</p>
162 <div>
163 <pre><code class="lua">
164 ardour {
165   ["type"]    = "session",
166   name        = "Example Session Script",
167   description = [[
168   An Example Ardour Session Script.
169   This example stops the transport after rolling for a specific time.]]
170 }
171
172
173 -- instantiation options, these are passed to the "factory" method below
174 function sess_params ()
175   return
176   {
177     ["print"]  = { title = "Debug Print (yes/no)", default = "no", optional = true },
178     ["time"] = { title = "Timeout (sec)", default = "90", optional = false },
179   }
180 end
181
182 function factory (params)
183   return function (n_samples)
184     local p = params["print"] or "no"
185     local timeout = params["time"] or 90
186     a = a or 0
187     if p ~= "no" then print (a, n_samples, Session:frame_rate (), Session:transport_rolling ()) end -- debug output (not rt safe)
188     if (not Session:transport_rolling()) then
189       a = 0
190       return
191     end
192     a = a + n_samples
193     if (a &gt; timeout * Session:frame_rate()) then
194       Session:request_transport_speed(0.0, true)
195     end
196   end
197 end
198 </code></pre>
199 </div>
200
201 <h3 id="Action Hooks">Action Hooks</h3>
202 <p>Action hook scripts must define an additional function which returns a <em>Set</em> of Signal that which trigger the callback (documenting available slots and their parameters remains to be done).</p>
203 <div>
204 <pre><code class="lua">
205 ardour {
206   ["type"]    = "EditorHook",
207   name        = "Hook Example",
208   description = "Rewind On Solo Change, Write a file when regions are moved.",
209 }
210
211 function signals ()
212   s = LuaSignal.Set()
213   s:add (
214     {
215       [LuaSignal.SoloActive] = true,
216       [LuaSignal.RegionPropertyChanged] = true
217     }
218   )
219   return s
220 end
221
222 function factory (params)
223   return function (signal, ref, ...)
224     -- print (signal, ref, ...)
225
226     if (signal == LuaSignal.SoloActive) then
227       Session:goto_start()
228     end
229
230     if (signal == LuaSignal.RegionPropertyChanged) then
231       obj,pch = ...
232       file = io.open ("/tmp/test" ,"a")
233       io.output (file
234       io.write (string.format ("Region: '%s' pos-changed: %s, length-changed: %s\n",
235         obj:name (),
236         tostring (pch:containsFramePos (ARDOUR.Properties.Start)),
237         tostring (pch:containsFramePos (ARDOUR.Properties.Length))
238         ))
239       io.close (file)
240     end
241   end
242 end
243 </code></pre>
244 </div>
245
246 <h3 id="DSP Scripts">DSP Scripts</h3>
247 <p>See the scripts folder for examples for now.</p>
248 <p>Some notes for further doc:</p>
249 <ul>
250         <li>required function: <code>dsp_ioconfig ()</code>: return a list of possible audio I/O configurations - follows Audio Unit conventions.</li>
251         <li>optional function: <code>dsp_dsp_midi_input ()</code>: return true if the plugin can receive midi input</li>
252         <li>optional function: <code>dsp_params ()</code>: return a table of possible parameters (automatable)</li>
253         <li>optional function: <code>dsp_init (samplerate)</code>: called when instantiation the plugin with given samplerate.</li>
254         <li>optional function: <code>dsp_configure (in, out)</code>: called after instantiation with configured plugin i/o.</li>
255         <li>required function: <code>dsp_run (ins, outs, n_samples)</code> OR <code>dsp_runmap (bufs, in_map, out_map, n_samples, offset)</code>: DSP process callback. The former is a convenient abstraction that passes mapped buffers (as table). The latter is a direct pass-through matching Ardour's internal <code>::connect_and_run()</code> API, which requires the caller to map and offset raw buffers.</li>
256         <li>plugin parameters are handled via the global variable <code>CtrlPorts</code>.</li>
257         <li>midi data is passed via the global variable <code>mididata</code> which is valid during <code>dsp_run</code> only. (dsp_runmap requires the script to pass raw data from the buffers according to in_map)</li>
258         <li>The script has access to the current session via the global variable Session, but access to the session methods are limited to realtime safe functions</li>
259 </ul>
260
261 <h2 id="Accessing Ardour Objects">Accessing Ardour Objects</h2>
262 <p>
263 The top most object in Ardour is the <code>ARDOUR::Session</code>.
264 Fundamentally, a Session is just a collection of other things:
265 Routes (tracks, busses), Sources (Audio/Midi), Regions, Playlists, Locations, Tempo map, Undo/Redo history, Ports, Transport state &amp; controls, etc.
266 </p><p>
267 Every Lua interpreter can access it via the global variable <code>Session</code>.
268 </p><p>
269 GUI context interpreters also have an additional object in the global environment: The Ardour <code>Editor</code>. The Editor provides access to high level functionality which is otherwise triggered via GUI interaction such as undo/redo, open/close windows, select objects, drag/move regions. It also holds the current UI state: snap-mode, zoom-range, etc.
270 The Editor also provides complex operations such as "import audio" which under the hood, creates a new Track, adds a new Source Objects (for every channel) with optional resampling, creates both playlist and regions and loads the region onto the Track all the while displaying a progress information to the user.
271 </p>
272
273 <p class="note">
274 Documenting the bound C++ methods and class hierarchy is somewhere on the ToDo list.
275 Meanwhile <a href="https://github.com/Ardour/ardour/blob/master/libs/ardour/luabindings.cc">luabindings.cc</a> is the best we can offer.
276 </p>
277
278 <h2 id="Concepts">Concepts</h2>
279 <ul>
280         <li>There are no bound constructors: Lua asks Ardour to create objects (e.g. add a new track), then receives a reference to the object to modify it.</li>
281         <li>Scripts, once loaded, are saved with the Session (no reference to external files). This provides for portable Sessions.</li>
282         <li>Lua Scripts are never executed directly. They provide a "factory" method which can have optional instantiation parameters, which returns a lua closure.</li>
283         <li>No external lua modules/libraries can be used, scripts need to be self contained (portable across different systems (libs written in Lua can be used, and important c-libs/functions can be included with ardour if needed).</li>
284 </ul>
285 <p>
286 Ardour is a highly multithreaded application and interaction between the different threads, particularly real-time threads, needs to to be done with care.
287 This part has been abstracted away by providing separate Lua interpreters in different contexts and restricting available interaction:
288 </p>
289 <ul>
290         <li>Editor Actions run in a single instance interpreter in the GUI thread.</li>
291         <li>Editor Hooks connect to libardour signals. Every Callback uses a dedicated lua interpreter which is in the GUI thread context.</li>
292         <li>All Session scripts run in a single instance in the main real-time thread (audio callback)</li>
293         <li>DSP scripts have a separate instance per script and run in one of the DSP threads.</li>
294 </ul>
295 <p>
296 The available interfaces differ between contexts. e.g. it is not possible to create new tracks or import audio from real-time context; while it is not possible to modify audio buffers from the GUI thread.
297 </p>
298
299 <h2 id="Current State">Current State</h2>
300 Fully functional, yet still in a prototyping stage:
301
302 <ul>
303         <li>The GUI to add/configure scripts is rather minimalistic.</li>
304         <li>The interfaces may change (particularly DSP, and Session script <code>run()</code>.</li>
305         <li>Further planned work includes:
306                 <ul>
307                         <li>Built-in Script editor (customize/modify Scripts in-place)</li>
308                         <li>convenience methods (wrap more complex Ardour actions into a library). e.g set plugin parameters, write automation lists from a lua table</li>
309                         <li>Add some useful scripts and more examples</li>
310                         <li>Documentation (Ardour API), also usable for tab-exansion, syntax highlighting</li>
311                         <li>bindings for GUI Widgets (plugin UIs, message boxes, etc)</li>
312                 </ul>
313                 <li>
314 </ul>
315
316
317 <h2 id="Examples">Examples</h2>
318 <p>Apart from the <a href="https://github.com/Ardour/ardour/tree/master/scripts">scripts included with the source-code</a> here are a few examples without further comments...
319
320 <h3 id="Editor Console Examples">Editor Console Examples</h3>
321 <div>
322 <pre><code class="lua">
323 print (Session:route_by_remote_id(1):name())
324
325 a = Session:route_by_remote_id(1);
326 print (a:name());
327
328 print(Session:get_tracks():size())
329
330 for i, v in ipairs(Session:unknown_processors():table()) do print(v) end
331 for i, v in ipairs(Session:get_tracks():table()) do print(v:name()) end
332
333 for t in Session:get_tracks():iter() do print(t:name()) end
334 for r in Session:get_routes():iter() do print(r:name()) end
335
336
337 Session:tempo_map():add_tempo(ARDOUR.Tempo(100,4), Timecode.BBT_TIME(4,1,0))
338
339
340 Editor:set_zoom_focus(Editing.ZoomFocusRight)
341 print(Editing.ZoomFocusRight);
342 Editor:set_zoom_focus(1)
343
344
345 files = C.StringVector();
346 files:push_back("/home/rgareus/data/coding/ltc-tools/smpte.wav")
347 pos = -1
348 Editor:do_import(files, Editing.ImportDistinctFiles, Editing.ImportAsTrack, ARDOUR.SrcQuality.SrcBest, pos, ARDOUR.PluginInfo())
349
350 #or in one line:
351 Editor:do_import(C.StringVector():add({"/path/to/file.wav"}), Editing.ImportDistinctFiles, Editing.ImportAsTrack, ARDOUR.SrcQuality.SrcBest, -1, ARDOUR.PluginInfo())
352
353 # called when a new session is loaded:
354 function new_session (name) print("NEW SESSION:", name) end
355
356
357 # read/set/describe a plugin parameter
358 route = Session:route_by_remote_id(1)
359 processor = route:nth_plugin(0)
360 plugininsert = processor:to_insert()
361
362 plugin = plugininsert:plugin(0)
363 print (plugin:label())
364 print (plugin:parameter_count())
365
366 x = ARDOUR.ParameterDescriptor ()
367 _, t = plugin:get_parameter_descriptor(2, x) -- port #2
368 paramdesc = t[2]
369 print (paramdesc.lower)
370
371 ctrl = Evoral.Parameter(ARDOUR.AutomationType.PluginAutomation, 0, 2)
372 ac = plugininsert:automation_control(ctrl, false)
373 print (ac:get_value ())
374 ac:set_value(1.0, PBD.GroupControlDisposition.NoGroup)
375
376 # the same using a convenience wrapper:
377 route = Session:route_by_remote_id(1)
378 proc = t:nth_plugin (i)
379 ARDOUR.LuaAPI.set_processor_param (proc, 2, 1.0)
380
381 </code></pre>
382 </div>
383
384 <h3 id="Commandline Session">Commandline Session</h3>
385 <p>The standalone tool <code>luasession</code> allows one to access an Ardour session directly from the commandline.
386 Interaction is limited by the fact that most actions in Ardour are provided by the Editor GUI.
387 </p><p>
388 <code>luasession</code> provides only two special functions <code>load_session</code> and <code>close_session</code> and exposes the <code>AudioEngine</code> instance as global variable.
389 </p>
390
391 <div>
392 <pre><code class="lua">
393 for i,_ in AudioEngine:available_backends():iter() do print (i.name) end
394
395 backend = AudioEngine:set_backend("ALSA", "", "")
396 print (AudioEngine:current_backend_name())
397
398 for i,_ in backend:enumerate_devices():iter() do print (i.name) end
399
400 backend:set_input_device_name("HDA Intel PCH")
401 backend:set_output_device_name("HDA Intel PCH")
402
403 print (backend:buffer_size())
404 print (AudioEngine:get_last_backend_error())
405
406 s = load_session ("/home/rgareus/Documents/ArdourSessions/lua2/", "lua2")
407 s:request_transport_speed (1.0)
408 print (s:transport_rolling())
409 s:goto_start()
410 close_session()
411
412 </code></pre>
413 </div>
414