Consistent Automation evaluation:
[ardour.git] / libs / ardour / amp.cc
1 /*
2     Copyright (C) 2006 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify it
5     under the terms of the GNU General Public License as published by the Free
6     Software Foundation; either version 2 of the License, or (at your option)
7     any later version.
8
9     This program is distributed in the hope that it will be useful, but WITHOUT
10     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12     for more details.
13
14     You should have received a copy of the GNU General Public License along
15     with this program; if not, write to the Free Software Foundation, Inc.,
16     675 Mass Ave, Cambridge, MA 02139, USA.
17 */
18
19 #include <cstring>
20 #include <cmath>
21 #include <algorithm>
22
23 #include "evoral/Curve.hpp"
24
25 #include "ardour/amp.h"
26 #include "ardour/audio_buffer.h"
27 #include "ardour/buffer_set.h"
28 #include "ardour/gain_control.h"
29 #include "ardour/midi_buffer.h"
30 #include "ardour/rc_configuration.h"
31 #include "ardour/session.h"
32
33 #include "pbd/i18n.h"
34
35 using namespace ARDOUR;
36 using namespace PBD;
37
38 // used for low-pass filter denormal protection
39 #define GAIN_COEFF_TINY (1e-10) // -200dB
40
41 Amp::Amp (Session& s, const std::string& name, boost::shared_ptr<GainControl> gc, bool control_midi_also)
42         : Processor(s, "Amp")
43         , _apply_gain(true)
44         , _apply_gain_automation(false)
45         , _current_gain(GAIN_COEFF_ZERO)
46         , _current_automation_frame (INT64_MAX)
47         , _gain_control (gc)
48         , _gain_automation_buffer(0)
49         , _midi_amp (control_midi_also)
50 {
51         set_display_name (name);
52         add_control (_gain_control);
53 }
54
55 bool
56 Amp::can_support_io_configuration (const ChanCount& in, ChanCount& out)
57 {
58         out = in;
59         return true;
60 }
61
62 bool
63 Amp::configure_io (ChanCount in, ChanCount out)
64 {
65         if (out != in) { // always 1:1
66                 return false;
67         }
68
69         return Processor::configure_io (in, out);
70 }
71
72 static void
73 scale_midi_velocity(Evoral::Event<MidiBuffer::TimeType>& ev, float factor)
74 {
75         factor = std::max(factor, 0.0f);
76         ev.set_velocity(std::min(127L, lrintf(ev.velocity() * factor)));
77 }
78
79 void
80 Amp::run (BufferSet& bufs, framepos_t /*start_frame*/, framepos_t /*end_frame*/, double /*speed*/, pframes_t nframes, bool)
81 {
82         if (!_active && !_pending_active) {
83                 return;
84         }
85
86         if (_apply_gain) {
87
88                 if (_apply_gain_automation) {
89
90                         gain_t* gab = _gain_automation_buffer;
91                         assert (gab);
92
93                         /* see note in PluginInsert::connect_and_run -- emit Changed signal */
94                         _gain_control->set_value_unchecked (gab[0]);
95
96                         if (_midi_amp) {
97                                 for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
98                                         MidiBuffer& mb (*i);
99                                         for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
100                                                 Evoral::Event<MidiBuffer::TimeType> ev = *m;
101                                                 if (ev.is_note_on()) {
102                                                         assert(ev.time() >= 0 && ev.time() < nframes);
103                                                         scale_midi_velocity (ev, fabsf (gab[ev.time()]));
104                                                 }
105                                         }
106                                 }
107                         }
108
109
110                         const double a = 156.825 / _session.nominal_frame_rate(); // 25 Hz LPF; see Amp::apply_gain for details
111                         double lpf = _current_gain;
112
113                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
114                                 Sample* const sp = i->data();
115                                 lpf = _current_gain;
116                                 for (pframes_t nx = 0; nx < nframes; ++nx) {
117                                         sp[nx] *= lpf;
118                                         lpf += a * (gab[nx] - lpf);
119                                 }
120                         }
121
122                         if (fabs (lpf) < GAIN_COEFF_TINY) {
123                                 _current_gain = GAIN_COEFF_ZERO;
124                         } else {
125                                 _current_gain = lpf;
126                         }
127
128                 } else { /* manual (scalar) gain */
129
130                         gain_t const dg = _gain_control->get_value();
131
132                         if (_current_gain != dg) {
133
134                                 _current_gain = Amp::apply_gain (bufs, _session.nominal_frame_rate(), nframes, _current_gain, dg, _midi_amp);
135
136                                 /* see note in PluginInsert::connect_and_run ()
137                                  * set_value_unchecked() won't emit a signal since the value is effectively unchanged
138                                  */
139
140                                 _gain_control->Changed (false, PBD::Controllable::NoGroup);
141
142                         } else if (_current_gain != GAIN_COEFF_UNITY) {
143
144                                 /* gain has not changed, but its non-unity */
145
146                                 if (_midi_amp) {
147                                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
148                                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
149
150                                                 MidiBuffer& mb (*i);
151
152                                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
153                                                         Evoral::Event<MidiBuffer::TimeType> ev = *m;
154                                                         if (ev.is_note_on()) {
155                                                                 scale_midi_velocity (ev, fabsf (_current_gain));
156                                                         }
157                                                 }
158                                         }
159                                 }
160
161                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
162                                         apply_gain_to_buffer (i->data(), nframes, _current_gain);
163                                 }
164                         }
165                 }
166         }
167
168         _active = _pending_active;
169 }
170
171 gain_t
172 Amp::apply_gain (BufferSet& bufs, framecnt_t sample_rate, framecnt_t nframes, gain_t initial, gain_t target, bool midi_amp)
173 {
174         /** Apply a (potentially) declicked gain to the buffers of @a bufs */
175         gain_t rv = target;
176
177         if (nframes == 0 || bufs.count().n_total() == 0) {
178                 return initial;
179         }
180
181         // if we don't need to declick, defer to apply_simple_gain
182         if (initial == target) {
183                 apply_simple_gain (bufs, nframes, target);
184                 return target;
185         }
186
187         /* MIDI Gain */
188         if (midi_amp) {
189                 /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
190                 for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
191
192                         gain_t  delta;
193                         if (target < initial) {
194                                 /* fade out: remove more and more of delta from initial */
195                                 delta = -(initial - target);
196                         } else {
197                                 /* fade in: add more and more of delta from initial */
198                                 delta = target - initial;
199                         }
200
201                         MidiBuffer& mb (*i);
202
203                         for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
204                                 Evoral::Event<MidiBuffer::TimeType> ev = *m;
205
206                                 if (ev.is_note_on()) {
207                                         const gain_t scale = delta * (ev.time()/(double) nframes);
208                                         scale_midi_velocity (ev, fabsf (initial + scale));
209                                 }
210                         }
211                 }
212         }
213
214         /* Audio Gain */
215
216         /* Low pass filter coefficient: 1.0 - e^(-2.0 * π * f / 48000) f in Hz.
217          * for f << SR,  approx a ~= 6.2 * f / SR;
218          */
219         const double a = 156.825 / sample_rate; // 25 Hz LPF
220
221         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
222                 Sample* const buffer = i->data();
223                 double lpf = initial;
224
225                 for (pframes_t nx = 0; nx < nframes; ++nx) {
226                         buffer[nx] *= lpf;
227                         lpf += a * (target - lpf);
228                 }
229                 if (i == bufs.audio_begin()) {
230                         rv = lpf;
231                 }
232         }
233         if (fabsf (rv - target) < GAIN_COEFF_TINY) return target;
234         if (fabsf (rv) < GAIN_COEFF_TINY) return GAIN_COEFF_ZERO;
235         return rv;
236 }
237
238 void
239 Amp::declick (BufferSet& bufs, framecnt_t nframes, int dir)
240 {
241         if (nframes == 0 || bufs.count().n_total() == 0) {
242                 return;
243         }
244
245         const framecnt_t declick = std::min ((framecnt_t) 512, nframes);
246         const double     fractional_shift = 1.0 / declick ;
247         gain_t           delta, initial;
248
249         if (dir < 0) {
250                 /* fade out: remove more and more of delta from initial */
251                 delta = -1.0;
252                 initial = GAIN_COEFF_UNITY;
253         } else {
254                 /* fade in: add more and more of delta from initial */
255                 delta = 1.0;
256                 initial = GAIN_COEFF_ZERO;
257         }
258
259         /* Audio Gain */
260         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
261                 Sample* const buffer = i->data();
262
263                 double fractional_pos = 0.0;
264
265                 for (pframes_t nx = 0; nx < declick; ++nx) {
266                         buffer[nx] *= initial + (delta * fractional_pos);
267                         fractional_pos += fractional_shift;
268                 }
269
270                 /* now ensure the rest of the buffer has the target value applied, if necessary. */
271                 if (declick != nframes) {
272                         if (dir < 0) {
273                                 memset (&buffer[declick], 0, sizeof (Sample) * (nframes - declick));
274                         }
275                 }
276         }
277 }
278
279
280 gain_t
281 Amp::apply_gain (AudioBuffer& buf, framecnt_t sample_rate, framecnt_t nframes, gain_t initial, gain_t target)
282 {
283         /* Apply a (potentially) declicked gain to the contents of @a buf
284          * -- used by MonitorProcessor::run()
285          */
286
287         if (nframes == 0) {
288                 return initial;
289         }
290
291         // if we don't need to declick, defer to apply_simple_gain
292         if (initial == target) {
293                 apply_simple_gain (buf, nframes, target);
294                 return target;
295         }
296
297         Sample* const buffer = buf.data();
298         const double a = 156.825 / sample_rate; // 25 Hz LPF, see [other] Amp::apply_gain() above for details
299
300         double lpf = initial;
301         for (pframes_t nx = 0; nx < nframes; ++nx) {
302                 buffer[nx] *= lpf;
303                 lpf += a * (target - lpf);
304         }
305
306         if (fabs (lpf - target) < GAIN_COEFF_TINY) return target;
307         if (fabs (lpf) < GAIN_COEFF_TINY) return GAIN_COEFF_ZERO;
308         return lpf;
309 }
310
311 void
312 Amp::apply_simple_gain (BufferSet& bufs, framecnt_t nframes, gain_t target, bool midi_amp)
313 {
314         if (fabsf (target) < GAIN_COEFF_SMALL) {
315
316                 if (midi_amp) {
317                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
318                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
319                                 MidiBuffer& mb (*i);
320
321                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
322                                         Evoral::Event<MidiBuffer::TimeType> ev = *m;
323                                         if (ev.is_note_on()) {
324                                                 ev.set_velocity (0);
325                                         }
326                                 }
327                         }
328                 }
329
330                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
331                         memset (i->data(), 0, sizeof (Sample) * nframes);
332                 }
333
334         } else if (target != GAIN_COEFF_UNITY) {
335
336                 if (midi_amp) {
337                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
338                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
339                                 MidiBuffer& mb (*i);
340
341                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
342                                         Evoral::Event<MidiBuffer::TimeType> ev = *m;
343                                         if (ev.is_note_on()) {
344                                                 scale_midi_velocity(ev, fabsf (target));
345                                         }
346                                 }
347                         }
348                 }
349
350                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
351                         apply_gain_to_buffer (i->data(), nframes, target);
352                 }
353         }
354 }
355
356 void
357 Amp::apply_simple_gain (AudioBuffer& buf, framecnt_t nframes, gain_t target)
358 {
359         if (fabsf (target) < GAIN_COEFF_SMALL) {
360                 memset (buf.data(), 0, sizeof (Sample) * nframes);
361         } else if (target != GAIN_COEFF_UNITY) {
362                 apply_gain_to_buffer (buf.data(), nframes, target);
363         }
364 }
365
366 XMLNode&
367 Amp::state (bool full_state)
368 {
369         XMLNode& node (Processor::state (full_state));
370         node.set_property("type", _gain_control->parameter().type() == GainAutomation ? "amp" : "trim");
371         node.add_child_nocopy (_gain_control->get_state());
372
373         return node;
374 }
375
376 int
377 Amp::set_state (const XMLNode& node, int version)
378 {
379         XMLNode* gain_node;
380
381         Processor::set_state (node, version);
382
383         if ((gain_node = node.child (Controllable::xml_node_name.c_str ())) != 0) {
384                 _gain_control->set_state (*gain_node, version);
385         }
386
387         return 0;
388 }
389
390 /** Write gain automation for this cycle into the buffer previously passed in to
391  *  set_gain_automation_buffer (if we are in automation playback mode and the
392  *  transport is rolling).
393  */
394 void
395 Amp::setup_gain_automation (framepos_t start_frame, framepos_t end_frame, framecnt_t nframes)
396 {
397         Glib::Threads::Mutex::Lock am (control_lock(), Glib::Threads::TRY_LOCK);
398
399         if (am.locked()
400             && (_session.transport_rolling() || _session.bounce_processing())
401             && _gain_control->automation_playback())
402         {
403                 assert (_gain_automation_buffer);
404
405                 _apply_gain_automation = _gain_control->get_masters_curve ( start_frame, end_frame, _gain_automation_buffer, nframes);
406
407                 if (start_frame != _current_automation_frame && _session.bounce_processing ()) {
408                         _current_gain = _gain_automation_buffer[0];
409                 }
410                 _current_automation_frame = end_frame;
411         } else {
412                 _apply_gain_automation = false;
413                 _current_automation_frame = INT64_MAX;
414         }
415 }
416
417 bool
418 Amp::visible() const
419 {
420         return true;
421 }
422
423 /** Sets up the buffer that setup_gain_automation and ::run will use for
424  *  gain automationc curves.  Must be called before setup_gain_automation,
425  *  and must be called with process lock held.
426  */
427
428 void
429 Amp::set_gain_automation_buffer (gain_t* g)
430 {
431         _gain_automation_buffer = g;
432 }