b7e639b9f5fdb357b833c30f2cd086d45abc2cd4
[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 <iostream>
20 #include <cstring>
21 #include <cmath>
22 #include <algorithm>
23
24 #include "evoral/Curve.hpp"
25
26 #include "ardour/amp.h"
27 #include "ardour/audio_buffer.h"
28 #include "ardour/buffer_set.h"
29 #include "ardour/midi_buffer.h"
30 #include "ardour/rc_configuration.h"
31 #include "ardour/session.h"
32
33 #include "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, std::string type)
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_automation_buffer(0)
48         , _type (type)
49         , _midi_amp (type != "trim")
50 {
51         Evoral::Parameter p (_type == "trim" ? TrimAutomation : GainAutomation);
52         boost::shared_ptr<AutomationList> gl (new AutomationList (p));
53         _gain_control = boost::shared_ptr<GainControl> (new GainControl ((_type == "trim") ? X_("trimcontrol") : X_("gaincontrol"), s, this, p, gl));
54         _gain_control->set_flags (Controllable::GainLike);
55
56         add_control(_gain_control);
57 }
58
59 std::string
60 Amp::display_name() const
61 {
62         return _("Fader");
63 }
64
65 bool
66 Amp::can_support_io_configuration (const ChanCount& in, ChanCount& out)
67 {
68         out = in;
69         return true;
70 }
71
72 bool
73 Amp::configure_io (ChanCount in, ChanCount out)
74 {
75         if (out != in) { // always 1:1
76                 return false;
77         }
78
79         return Processor::configure_io (in, out);
80 }
81
82 void
83 Amp::run (BufferSet& bufs, framepos_t /*start_frame*/, framepos_t /*end_frame*/, pframes_t nframes, bool)
84 {
85         if (!_active && !_pending_active) {
86                 return;
87         }
88
89         if (_apply_gain) {
90
91                 if (_apply_gain_automation) {
92
93                         gain_t* gab = _gain_automation_buffer;
94                         assert (gab);
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::MIDIEvent<MidiBuffer::TimeType> ev = *m;
101                                                 if (ev.is_note_on()) {
102                                                         assert(ev.time() >= 0 && ev.time() < nframes);
103                                                         ev.scale_velocity (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->user_double();
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                         } else if (_current_gain == GAIN_COEFF_ZERO) {
137
138                                 /* gain has not changed, and is zero. small
139                                  * optimization here.
140                                  */
141
142                                 bufs.silence (nframes, 0);
143
144                         } else if (_current_gain != GAIN_COEFF_UNITY) {
145
146                                 /* gain has not changed, but its non-unity and
147                                  * isn't zero, so we have to do something
148                                  */
149
150                                 if (_midi_amp) {
151                                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
152                                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
153
154                                                 MidiBuffer& mb (*i);
155
156                                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
157                                                         Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *m;
158                                                         if (ev.is_note_on()) {
159                                                                 ev.scale_velocity (fabsf (_current_gain));
160                                                         }
161                                                 }
162                                         }
163                                 }
164
165                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
166                                         apply_gain_to_buffer (i->data(), nframes, _current_gain);
167                                 }
168                         }
169                 }
170         }
171
172         _active = _pending_active;
173 }
174
175 gain_t
176 Amp::apply_gain (BufferSet& bufs, framecnt_t sample_rate, framecnt_t nframes, gain_t initial, gain_t target, bool midi_amp)
177 {
178         /** Apply a (potentially) declicked gain to the buffers of @a bufs */
179         gain_t rv = target;
180
181         if (nframes == 0 || bufs.count().n_total() == 0) {
182                 return initial;
183         }
184
185         // if we don't need to declick, defer to apply_simple_gain
186         if (initial == target) {
187                 apply_simple_gain (bufs, nframes, target);
188                 return target;
189         }
190
191         /* MIDI Gain */
192         if (midi_amp) {
193                 /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
194                 for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
195
196                         gain_t  delta;
197                         if (target < initial) {
198                                 /* fade out: remove more and more of delta from initial */
199                                 delta = -(initial - target);
200                         } else {
201                                 /* fade in: add more and more of delta from initial */
202                                 delta = target - initial;
203                         }
204
205                         MidiBuffer& mb (*i);
206
207                         for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
208                                 Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *m;
209
210                                 if (ev.is_note_on()) {
211                                         const gain_t scale = delta * (ev.time()/(double) nframes);
212                                         ev.scale_velocity (fabsf (initial+scale));
213                                 }
214                         }
215                 }
216         }
217
218         /* Audio Gain */
219
220         /* Low pass filter coefficient: 1.0 - e^(-2.0 * Ï€ * f / 48000) f in Hz.
221          * for f << SR,  approx a ~= 6.2 * f / SR;
222          */
223         const double a = 156.825 / sample_rate; // 25 Hz LPF
224
225         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
226                 Sample* const buffer = i->data();
227                 double lpf = initial;
228
229                 for (pframes_t nx = 0; nx < nframes; ++nx) {
230                         buffer[nx] *= lpf;
231                         lpf += a * (target - lpf);
232                 }
233                 if (i == bufs.audio_begin()) {
234                         rv = lpf;
235                 }
236         }
237         if (fabsf (rv - target) < GAIN_COEFF_TINY) return target;
238         if (fabsf (rv) < GAIN_COEFF_TINY) return GAIN_COEFF_ZERO;
239         return rv;
240 }
241
242 void
243 Amp::declick (BufferSet& bufs, framecnt_t nframes, int dir)
244 {
245         if (nframes == 0 || bufs.count().n_total() == 0) {
246                 return;
247         }
248
249         const framecnt_t declick = std::min ((framecnt_t) 512, nframes);
250         const double     fractional_shift = 1.0 / declick ;
251         gain_t           delta, initial;
252
253         if (dir < 0) {
254                 /* fade out: remove more and more of delta from initial */
255                 delta = -1.0;
256                 initial = GAIN_COEFF_UNITY;
257         } else {
258                 /* fade in: add more and more of delta from initial */
259                 delta = 1.0;
260                 initial = GAIN_COEFF_ZERO;
261         }
262
263         /* Audio Gain */
264         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
265                 Sample* const buffer = i->data();
266
267                 double fractional_pos = 0.0;
268
269                 for (pframes_t nx = 0; nx < declick; ++nx) {
270                         buffer[nx] *= initial + (delta * fractional_pos);
271                         fractional_pos += fractional_shift;
272                 }
273
274                 /* now ensure the rest of the buffer has the target value applied, if necessary. */
275                 if (declick != nframes) {
276                         if (dir < 0) {
277                                 memset (&buffer[declick], 0, sizeof (Sample) * (nframes - declick));
278                         }
279                 }
280         }
281 }
282
283
284 gain_t
285 Amp::apply_gain (AudioBuffer& buf, framecnt_t sample_rate, framecnt_t nframes, gain_t initial, gain_t target)
286 {
287         /* Apply a (potentially) declicked gain to the contents of @a buf
288          * -- used by MonitorProcessor::run()
289          */
290
291         if (nframes == 0) {
292                 return initial;
293         }
294
295         // if we don't need to declick, defer to apply_simple_gain
296         if (initial == target) {
297                 apply_simple_gain (buf, nframes, target);
298                 return target;
299         }
300
301         Sample* const buffer = buf.data();
302         const double a = 156.825 / sample_rate; // 25 Hz LPF, see [other] Amp::apply_gain() above for details
303
304         double lpf = initial;
305         for (pframes_t nx = 0; nx < nframes; ++nx) {
306                 buffer[nx] *= lpf;
307                 lpf += a * (target - lpf);
308         }
309
310         if (fabs (lpf - target) < GAIN_COEFF_TINY) return target;
311         if (fabs (lpf) < GAIN_COEFF_TINY) return GAIN_COEFF_ZERO;
312         return lpf;
313 }
314
315 void
316 Amp::apply_simple_gain (BufferSet& bufs, framecnt_t nframes, gain_t target, bool midi_amp)
317 {
318         if (fabsf (target) < GAIN_COEFF_SMALL) {
319
320                 if (midi_amp) {
321                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
322                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
323                                 MidiBuffer& mb (*i);
324
325                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
326                                         Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *m;
327                                         if (ev.is_note_on()) {
328                                                 ev.set_velocity (0);
329                                         }
330                                 }
331                         }
332                 }
333
334                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
335                         memset (i->data(), 0, sizeof (Sample) * nframes);
336                 }
337
338         } else if (target != GAIN_COEFF_UNITY) {
339
340                 if (midi_amp) {
341                         /* don't Trim midi velocity -- only relevant for Midi on Audio tracks */
342                         for (BufferSet::midi_iterator i = bufs.midi_begin(); i != bufs.midi_end(); ++i) {
343                                 MidiBuffer& mb (*i);
344
345                                 for (MidiBuffer::iterator m = mb.begin(); m != mb.end(); ++m) {
346                                         Evoral::MIDIEvent<MidiBuffer::TimeType> ev = *m;
347                                         if (ev.is_note_on()) {
348                                                 ev.scale_velocity (fabsf (target));
349                                         }
350                                 }
351                         }
352                 }
353
354                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
355                         apply_gain_to_buffer (i->data(), nframes, target);
356                 }
357         }
358 }
359
360 void
361 Amp::apply_simple_gain (AudioBuffer& buf, framecnt_t nframes, gain_t target)
362 {
363         if (fabsf (target) < GAIN_COEFF_SMALL) {
364                 memset (buf.data(), 0, sizeof (Sample) * nframes);
365         } else if (target != GAIN_COEFF_UNITY) {
366                 apply_gain_to_buffer (buf.data(), nframes, target);
367         }
368 }
369
370 void
371 Amp::inc_gain (gain_t factor, void *src)
372 {
373         float desired_gain = _gain_control->user_double();
374
375         if (fabsf (desired_gain) < GAIN_COEFF_SMALL) {
376                 // really?! what's the idea here?
377                 set_gain (0.000001f + (0.000001f * factor), src);
378         } else {
379                 set_gain (desired_gain + (desired_gain * factor), src);
380         }
381 }
382
383 void
384 Amp::set_gain (gain_t val, void *)
385 {
386         _gain_control->set_value (val);
387 }
388
389 XMLNode&
390 Amp::state (bool full_state)
391 {
392         XMLNode& node (Processor::state (full_state));
393         node.add_property("type", _type);
394         node.add_child_nocopy (_gain_control->get_state());
395
396         return node;
397 }
398
399 int
400 Amp::set_state (const XMLNode& node, int version)
401 {
402         XMLNode* gain_node;
403
404         Processor::set_state (node, version);
405
406         if ((gain_node = node.child (Controllable::xml_node_name.c_str())) != 0) {
407                 _gain_control->set_state (*gain_node, version);
408         }
409
410         return 0;
411 }
412
413 void
414 Amp::GainControl::set_value (double val)
415 {
416         AutomationControl::set_value (std::max (std::min (val, (double)_desc.upper), (double)_desc.lower));
417         _amp->session().set_dirty ();
418 }
419
420 double
421 Amp::GainControl::internal_to_interface (double v) const
422 {
423         if (_desc.type == GainAutomation) {
424                 return gain_to_slider_position (v);
425         } else {
426                 return (accurate_coefficient_to_dB (v) - lower_db) / range_db;
427         }
428 }
429
430 double
431 Amp::GainControl::interface_to_internal (double v) const
432 {
433         if (_desc.type == GainAutomation) {
434                 return slider_position_to_gain (v);
435         } else {
436                 return dB_to_coefficient (lower_db + v * range_db);
437         }
438 }
439
440 double
441 Amp::GainControl::internal_to_user (double v) const
442 {
443         return accurate_coefficient_to_dB (v);
444 }
445
446 double
447 Amp::GainControl::user_to_internal (double u) const
448 {
449         return dB_to_coefficient (u);
450 }
451
452 std::string
453 Amp::GainControl::get_user_string () const
454 {
455         char theBuf[32]; sprintf( theBuf, _("%3.1f dB"), accurate_coefficient_to_dB (get_value()));
456         return std::string(theBuf);
457 }
458
459 /** Write gain automation for this cycle into the buffer previously passed in to
460  *  set_gain_automation_buffer (if we are in automation playback mode and the
461  *  transport is rolling).
462  */
463 void
464 Amp::setup_gain_automation (framepos_t start_frame, framepos_t end_frame, framecnt_t nframes)
465 {
466         Glib::Threads::Mutex::Lock am (control_lock(), Glib::Threads::TRY_LOCK);
467
468         if (am.locked()
469             && (_session.transport_rolling() || _session.bounce_processing())
470             && _gain_control->automation_playback())
471         {
472                 assert (_gain_automation_buffer);
473                 _apply_gain_automation = _gain_control->list()->curve().rt_safe_get_vector (
474                         start_frame, end_frame, _gain_automation_buffer, nframes);
475                 if (start_frame != _current_automation_frame) {
476                         _current_gain = _gain_automation_buffer[0];
477                 }
478                 _current_automation_frame = end_frame;
479         } else {
480                 _apply_gain_automation = false;
481                 _current_automation_frame = INT64_MAX;
482         }
483 }
484
485 bool
486 Amp::visible() const
487 {
488         return true;
489 }
490
491 std::string
492 Amp::value_as_string (boost::shared_ptr<AutomationControl> ac) const
493 {
494         if (ac == _gain_control) {
495                 char buffer[32];
496                 snprintf (buffer, sizeof (buffer), _("%.2fdB"), ac->internal_to_user (ac->get_value ()));
497                 return buffer;
498         }
499
500         return Automatable::value_as_string (ac);
501 }
502
503 /** Sets up the buffer that setup_gain_automation and ::run will use for
504  *  gain automationc curves.  Must be called before setup_gain_automation,
505  *  and must be called with process lock held.
506  */
507
508 void
509 Amp::set_gain_automation_buffer (gain_t* g)
510 {
511         _gain_automation_buffer = g;
512 }