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