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