94d3f4617d1a36216cdea6b07ce5b661293604b4
[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 #define GAIN_COEFF_DELTA (1e-5)
39
40 Amp::Amp (Session& s, const std::string& name, boost::shared_ptr<GainControl> gc, bool control_midi_also)
41         : Processor(s, "Amp")
42         , _apply_gain_automation(false)
43         , _current_gain(GAIN_COEFF_ZERO)
44         , _current_automation_sample (INT64_MAX)
45         , _gain_control (gc)
46         , _gain_automation_buffer(0)
47         , _midi_amp (control_midi_also)
48 {
49         set_display_name (name);
50         add_control (_gain_control);
51 }
52
53 bool
54 Amp::can_support_io_configuration (const ChanCount& in, ChanCount& out)
55 {
56         out = in;
57         return true;
58 }
59
60 bool
61 Amp::configure_io (ChanCount in, ChanCount out)
62 {
63         if (out != in) { // always 1:1
64                 return false;
65         }
66
67         return Processor::configure_io (in, out);
68 }
69
70 static void
71 scale_midi_velocity(Evoral::Event<MidiBuffer::TimeType>& ev, float factor)
72 {
73         factor = std::max(factor, 0.0f);
74         ev.set_velocity(std::min(127L, lrintf(ev.velocity() * factor)));
75 }
76
77 void
78 Amp::run (BufferSet& bufs, samplepos_t /*start_sample*/, samplepos_t /*end_sample*/, double /*speed*/, pframes_t nframes, bool)
79 {
80         if (!_active && !_pending_active) {
81                 /* disregard potentially prepared gain-automation. */
82                 _apply_gain_automation = false;
83                 return;
84         }
85
86         if (_apply_gain_automation) {
87
88                 gain_t* gab = _gain_automation_buffer;
89                 assert (gab);
90
91                 /* see note in PluginInsert::connect_and_run -- effectively emit Changed signal */
92                 _gain_control->set_value_unchecked (gab[0]);
93
94                 if (_midi_amp) {
95                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
96                                 MidiBuffer& mb (*i);
97                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
98                                         Evoral::Event<MidiBuffer::TimeType> ev = *m;
99                                         if (ev.is_note_on()) {
100                                                 assert(ev.time() >= 0 && ev.time() < nframes);
101                                                 scale_midi_velocity (ev, fabsf (gab[ev.time()]));
102                                         }
103                                 }
104                         }
105                 }
106
107                 const gain_t a = 156.825f / (gain_t)_session.nominal_sample_rate(); // 25 Hz LPF; see Amp::apply_gain for details
108                 gain_t lpf = _current_gain;
109
110                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
111                         Sample* const sp = i->data();
112                         lpf = _current_gain;
113                         for (pframes_t nx = 0; nx < nframes; ++nx) {
114                                 sp[nx] *= lpf;
115                                 lpf += a * (gab[nx] - lpf);
116                         }
117                 }
118
119                 if (fabsf (lpf) < GAIN_COEFF_SMALL) {
120                         _current_gain = GAIN_COEFF_ZERO;
121                 } else {
122                         _current_gain = lpf;
123                 }
124
125                 /* used it, don't do it again until setup_gain_automation() is
126                  * called successfully.
127                 */
128                 _apply_gain_automation = false;
129
130         } else { /* manual (scalar) gain */
131
132                 gain_t const target_gain = _gain_control->get_value();
133
134                 if (fabsf (_current_gain - target_gain) >= GAIN_COEFF_DELTA) {
135
136                         _current_gain = Amp::apply_gain (bufs, _session.nominal_sample_rate(), nframes, _current_gain, target_gain, _midi_amp);
137
138                         /* see note in PluginInsert::connect_and_run ()
139                          * set_value_unchecked() won't emit a signal since the value is effectively unchanged
140                          */
141                         _gain_control->Changed (false, PBD::Controllable::NoGroup);
142
143                 } else if (target_gain != GAIN_COEFF_UNITY) {
144
145                         _current_gain = target_gain;
146
147                         if (_midi_amp) {
148                                 /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
149                                 for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
150
151                                         MidiBuffer& mb (*i);
152
153                                         for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
154                                                 Evoral::Event<MidiBuffer::TimeType> ev = *m;
155                                                 if (ev.is_note_on()) {
156                                                         scale_midi_velocity (ev, fabsf (_current_gain));
157                                                 }
158                                         }
159                                 }
160                         }
161
162                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
163                                 apply_gain_to_buffer (i->data(), nframes, _current_gain);
164                         }
165                 } else {
166                         /* unity target gain */
167                         _current_gain = target_gain;
168                 }
169         }
170
171         _active = _pending_active;
172 }
173
174 gain_t
175 Amp::apply_gain (BufferSet& bufs, samplecnt_t sample_rate, samplecnt_t nframes, gain_t initial, gain_t target, bool midi_amp)
176 {
177         /** Apply a (potentially) declicked gain to the buffers of @a bufs */
178         gain_t rv = target;
179
180         if (nframes == 0 || bufs.count().n_total() == 0) {
181                 return initial;
182         }
183
184         // if we don't need to declick, defer to apply_simple_gain
185         if (initial == target) {
186                 apply_simple_gain (bufs, nframes, target);
187                 return target;
188         }
189
190         /* MIDI Gain */
191         if (midi_amp) {
192                 /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
193                 for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
194
195                         gain_t  delta;
196                         if (target < initial) {
197                                 /* fade out: remove more and more of delta from initial */
198                                 delta = -(initial - target);
199                         } else {
200                                 /* fade in: add more and more of delta from initial */
201                                 delta = target - initial;
202                         }
203
204                         MidiBuffer& mb (*i);
205
206                         for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
207                                 Evoral::Event<MidiBuffer::TimeType> ev = *m;
208
209                                 if (ev.is_note_on()) {
210                                         const gain_t scale = delta * (ev.time()/(double) nframes);
211                                         scale_midi_velocity (ev, fabsf (initial + scale));
212                                 }
213                         }
214                 }
215         }
216
217         /* Audio Gain */
218
219         /* Low pass filter coefficient: 1.0 - e^(-2.0 * π * f / 48000) f in Hz.
220          * for f << SR,  approx a ~= 6.2 * f / SR;
221          */
222         const gain_t a = 156.825f / (gain_t)sample_rate; // 25 Hz LPF
223
224         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
225                 Sample* const buffer = i->data();
226                 double lpf = initial;
227
228                 for (pframes_t nx = 0; nx < nframes; ++nx) {
229                         buffer[nx] *= lpf;
230                         lpf += a * (target - lpf);
231                 }
232                 if (i == bufs.audio_begin()) {
233                         rv = lpf;
234                 }
235         }
236         if (fabsf (rv - target) < GAIN_COEFF_DELTA) return target;
237         return rv;
238 }
239
240 void
241 Amp::declick (BufferSet& bufs, samplecnt_t nframes, int dir)
242 {
243         if (nframes == 0 || bufs.count().n_total() == 0) {
244                 return;
245         }
246
247         const samplecnt_t declick = std::min ((samplecnt_t) 512, nframes);
248         const double     fractional_shift = 1.0 / declick ;
249         gain_t           delta, initial;
250
251         if (dir < 0) {
252                 /* fade out: remove more and more of delta from initial */
253                 delta = -1.0;
254                 initial = GAIN_COEFF_UNITY;
255         } else {
256                 /* fade in: add more and more of delta from initial */
257                 delta = 1.0;
258                 initial = GAIN_COEFF_ZERO;
259         }
260
261         /* Audio Gain */
262         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
263                 Sample* const buffer = i->data();
264
265                 double fractional_pos = 0.0;
266
267                 for (pframes_t nx = 0; nx < declick; ++nx) {
268                         buffer[nx] *= initial + (delta * fractional_pos);
269                         fractional_pos += fractional_shift;
270                 }
271
272                 /* now ensure the rest of the buffer has the target value applied, if necessary. */
273                 if (declick != nframes) {
274                         if (dir < 0) {
275                                 memset (&buffer[declick], 0, sizeof (Sample) * (nframes - declick));
276                         }
277                 }
278         }
279 }
280
281
282 gain_t
283 Amp::apply_gain (AudioBuffer& buf, samplecnt_t sample_rate, samplecnt_t nframes, gain_t initial, gain_t target)
284 {
285         /* Apply a (potentially) declicked gain to the contents of @a buf
286          * -- used by MonitorProcessor::run()
287          */
288
289         if (nframes == 0) {
290                 return initial;
291         }
292
293         // if we don't need to declick, defer to apply_simple_gain
294         if (initial == target) {
295                 apply_simple_gain (buf, nframes, target);
296                 return target;
297         }
298
299         Sample* const buffer = buf.data();
300         const gain_t a = 156.825f / (gain_t)sample_rate; // 25 Hz LPF, see [other] Amp::apply_gain() above for details
301
302         gain_t lpf = initial;
303         for (pframes_t nx = 0; nx < nframes; ++nx) {
304                 buffer[nx] *= lpf;
305                 lpf += a * (target - lpf);
306         }
307
308         if (fabsf (lpf - target) < GAIN_COEFF_DELTA) return target;
309         return lpf;
310 }
311
312 void
313 Amp::apply_simple_gain (BufferSet& bufs, samplecnt_t nframes, gain_t target, bool midi_amp)
314 {
315         if (fabsf (target) < GAIN_COEFF_SMALL) {
316
317                 if (midi_amp) {
318                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
319                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
320                                 MidiBuffer& mb (*i);
321
322                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
323                                         Evoral::Event<MidiBuffer::TimeType> ev = *m;
324                                         if (ev.is_note_on()) {
325                                                 ev.set_velocity (0);
326                                         }
327                                 }
328                         }
329                 }
330
331                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
332                         memset (i->data(), 0, sizeof (Sample) * nframes);
333                 }
334
335         } else if (target != GAIN_COEFF_UNITY) {
336
337                 if (midi_amp) {
338                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
339                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
340                                 MidiBuffer& mb (*i);
341
342                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
343                                         Evoral::Event<MidiBuffer::TimeType> ev = *m;
344                                         if (ev.is_note_on()) {
345                                                 scale_midi_velocity(ev, fabsf (target));
346                                         }
347                                 }
348                         }
349                 }
350
351                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
352                         apply_gain_to_buffer (i->data(), nframes, target);
353                 }
354         }
355 }
356
357 void
358 Amp::apply_simple_gain (AudioBuffer& buf, samplecnt_t nframes, gain_t target)
359 {
360         if (fabsf (target) < GAIN_COEFF_SMALL) {
361                 memset (buf.data(), 0, sizeof (Sample) * nframes);
362         } else if (target != GAIN_COEFF_UNITY) {
363                 apply_gain_to_buffer (buf.data(), nframes, target);
364         }
365 }
366
367 XMLNode&
368 Amp::state (bool full_state)
369 {
370         XMLNode& node (Processor::state (full_state));
371         node.set_property("type", _gain_control->parameter().type() == GainAutomation ? "amp" : "trim");
372         node.add_child_nocopy (_gain_control->get_state());
373
374         return node;
375 }
376
377 int
378 Amp::set_state (const XMLNode& node, int version)
379 {
380         XMLNode* gain_node;
381
382         Processor::set_state (node, version);
383
384         if ((gain_node = node.child (Controllable::xml_node_name.c_str ())) != 0) {
385                 _gain_control->set_state (*gain_node, version);
386         }
387
388         return 0;
389 }
390
391 /** Write gain automation for this cycle into the buffer previously passed in to
392  *  set_gain_automation_buffer (if we are in automation playback mode and the
393  *  transport is rolling).
394  *
395  *  After calling this, the gain-automation buffer is valid for the next run.
396  *  so make sure to call ::run() which invalidates the buffer again.
397  */
398 void
399 Amp::setup_gain_automation (samplepos_t start_sample, samplepos_t end_sample, samplecnt_t nframes)
400 {
401         Glib::Threads::Mutex::Lock am (control_lock(), Glib::Threads::TRY_LOCK);
402
403         if (am.locked()
404             && (_session.transport_rolling() || _session.bounce_processing())
405             && _gain_control->automation_playback())
406         {
407                 assert (_gain_automation_buffer);
408
409                 _apply_gain_automation = _gain_control->get_masters_curve ( start_sample, end_sample, _gain_automation_buffer, nframes);
410
411                 if (start_sample != _current_automation_sample && _session.bounce_processing ()) {
412                         _current_gain = _gain_automation_buffer[0];
413                 }
414                 _current_automation_sample = end_sample;
415         } else {
416                 _apply_gain_automation = false;
417                 _current_automation_sample = INT64_MAX;
418         }
419 }
420
421 bool
422 Amp::visible() const
423 {
424         return true;
425 }
426
427 /** Sets up the buffer that setup_gain_automation and ::run will use for
428  *  gain automationc curves.  Must be called before setup_gain_automation,
429  *  and must be called with process lock held.
430  */
431 void
432 Amp::set_gain_automation_buffer (gain_t* g)
433 {
434         _gain_automation_buffer = g;
435 }