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