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