whitespace editing and comments + add ability to substitute routes at will
[ardour.git] / scripts / normalize_all_tracks.lua
1 ardour { ["type"] = "EditorAction",
2         name = "Normalize All Tracks",
3         license     = "MIT",
4         author      = "Ardour Team",
5         description = [[Normalize all regions using a common gain-factor per track.]]
6 }
7
8 function factory () return function ()
9         -- target values -- TODO: use a LuaDialog.Dialog and ask..
10         local target_peak = -1 --dBFS
11         local target_rms = -18 --dBFS/RMS
12
13         -- prepare undo operation
14         Session:begin_reversible_command ("Normalize Tracks")
15         local add_undo = false -- keep track if something has changed
16
17         -- loop over all tracks in the session
18         for track in Session:get_tracks():iter() do
19                 local norm = 0 -- per track gain
20                 -- loop over all regions on track
21                 for r in track:to_track():playlist():region_list():iter() do
22                         -- test if it's an audio region
23                         local ar = r:to_audioregion ()
24                         if ar:isnil () then goto next end
25
26                         local peak = ar:maximum_amplitude (nil)
27                         local rms  = ar:rms (nil)
28                         -- check if region is silent
29                         if (peak > 0) then
30                                 local f_rms = rms / 10 ^ (.05 * target_rms)
31                                 local f_peak = peak / 10 ^ (.05 * target_peak)
32                                 local tg = (f_peak > f_rms) and f_peak or f_rms  -- max (f_peak, f_rms)
33                                 norm = (tg > norm) and tg or norm -- max (tg, norm)
34                         end
35                         ::next::
36                 end
37
38                 -- apply same gain to all regions on track
39                 if norm > 0 then
40                         for r in track:to_track():playlist():region_list():iter() do
41                                 local ar = r:to_audioregion ()
42                                 if ar:isnil () then goto skip end
43                                 ar:to_stateful ():clear_changes ()
44                                 ar:set_scale_amplitude (1 / norm)
45                                 add_undo = true
46                                 ::skip::
47                         end
48                 end
49         end
50
51         -- all done. now commit the combined undo operation
52         if add_undo then
53                 -- the 'nil' command here means to use all collected diffs
54                 Session:commit_reversible_command (nil)
55         else
56                 Session:abort_reversible_command ()
57         end
58 end end