Implement basic libardour convolution DSP
[ardour.git] / libs / ardour / convolver.cc
1 /*
2  * Copyright (C) 2018 Robin Gareus <robin@gareus.org>
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software
16  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
17  *
18  */
19
20 #include <assert.h>
21
22 #include "pbd/error.h"
23 #include "pbd/pthread_utils.h"
24
25 #include "ardour/audioengine.h"
26 #include "ardour/audiofilesource.h"
27 #include "ardour/convolver.h"
28 #include "ardour/session.h"
29 #include "ardour/srcfilesource.h"
30 #include "ardour/source_factory.h"
31
32 #include "pbd/i18n.h"
33
34 using namespace ARDOUR::DSP;
35 using namespace ArdourZita;
36
37 Convolver::Convolver (Session& session, std::string const& path, IRChannelConfig irc, uint32_t pre_delay)
38         : SessionHandleRef (session)
39         , _irc (irc)
40         , _initial_delay (pre_delay)
41         , _n_samples (0)
42         , _max_size (0)
43         , _offset (0)
44         , _configured (false)
45 {
46         ARDOUR::SoundFileInfo sf_info;
47         std::string error_msg;
48
49         if (!AudioFileSource::get_soundfile_info (path, sf_info, error_msg)) {
50                 PBD::error << string_compose(_("Convolver: cannot open IR \"%1\": %2"), path, error_msg) << endmsg;
51                 throw failed_constructor ();
52         }
53
54         if (sf_info.length > 0x1000000 /*2^24*/) {
55                 PBD::error << string_compose(_("Convolver: IR \"%1\" file too long."), path) << endmsg;
56                 throw failed_constructor ();
57         }
58
59         for (unsigned int n = 0; n < sf_info.channels; ++n) {
60                 try {
61                         boost::shared_ptr<AudioFileSource> afs;
62                         afs = boost::dynamic_pointer_cast<AudioFileSource> (
63                                         SourceFactory::createExternal (DataType::AUDIO, _session,
64                                                 path, n,
65                                                 Source::Flag (ARDOUR::AudioFileSource::NoPeakFile), false));
66
67                         if (afs->sample_rate() != _session.nominal_sample_rate()) {
68                                 boost::shared_ptr<SrcFileSource> sfs (new SrcFileSource(_session, afs, ARDOUR::SrcBest));
69                                 _readables.push_back(sfs);
70                         } else {
71                                 _readables.push_back(afs);
72                         }
73                 } catch (failed_constructor& err) {
74                         PBD::error << string_compose(_("Convolver: Could not open IR \"%1\"."), path) << endmsg;
75                         throw failed_constructor ();
76                 }
77         }
78
79         if (_readables.empty()) {
80                 PBD::error << string_compose (_("Convolver: IR \"%1\" no usable audio-channels sound."), path) << endmsg;
81                 throw failed_constructor ();
82         }
83
84         AudioEngine::instance ()->BufferSizeChanged.connect_same_thread (*this, boost::bind (&Convolver::reconfigure, this));
85
86         reconfigure ();
87 }
88
89 void
90 Convolver::reconfigure ()
91 {
92         _convproc.stop_process ();
93         _convproc.cleanup ();
94         _convproc.set_options (0);
95
96         assert (!_readables.empty());
97
98         _offset = 0;
99         _n_samples = _session.get_block_size();
100         _max_size = _readables[0]->readable_length();
101
102         uint32_t power_of_two;
103         for (power_of_two = 1; 1U << power_of_two < _n_samples; ++power_of_two);
104         _n_samples = 1 << power_of_two;
105
106         int n_part = std::min ((uint32_t)Convproc::MAXPART, 4 * _n_samples);
107         int rv = _convproc.configure (
108                         /*in*/  n_inputs (),
109                         /*out*/ n_outputs (),
110                         /*max-convolution length */ _max_size,
111                         /*quantum, nominal-buffersize*/ _n_samples,
112                         /*Convproc::MINPART*/ _n_samples,
113                         /*Convproc::MAXPART*/ n_part,
114                         /*density*/ 0);
115
116         /* map channels
117          * - Mono:
118          *    always use first only
119          * - MonoToStereo:
120          *    mono-file: use 1st for M -> L, M -> R
121          *    else: use first two channels
122          * - Stereo
123          *    mono-file: use 1st for both L -> L, R -> R, no x-over
124          *    stereo-file: L -> L, R -> R  -- no L/R, R/L x-over
125          *    3chan-file: ignore 3rd channel, use as stereo-file.
126          *    4chan file:  L -> L, L -> R, R -> R, R -> L
127          */
128
129         uint32_t n_imp = n_inputs() * n_outputs ();
130         uint32_t n_chn = _readables.size();
131
132         if (_irc == Stereo && n_chn == 3) {
133                 /* ignore 3rd channel */
134                 n_chn = 2;
135         }
136         if (_irc == Stereo && n_chn <= 2) {
137                 /* ignore x-over */
138                 n_imp = 2;
139         }
140
141         for (uint32_t c = 0; c < n_imp && rv == 0; ++c) {
142                 int ir_c = c % n_chn;
143                 int io_o = c % n_outputs();
144                 int io_i;
145
146                 if (n_imp > n_chn && _irc == Stereo) {
147                         /*           (imp, in, out)
148                          * Stereo       (2, 2, 2)    1: L -> L, 2: R -> R
149                          */
150                         io_i = c % n_inputs();
151                 } else {
152                         /*           (imp, in, out)
153                          * Mono         (1, 1, 1)   1: M -> M
154                          * MonoToStereo (2, 1, 2)   1: M -> L, 2: M -> R
155                          * Stereo       (4, 2, 2)   1: L -> L, 2: L -> R, 3: R -> L, 4: R -> R
156                          */
157                         io_i = (c / n_outputs()) % n_inputs();
158                 }
159
160 #ifndef NDEBUG
161                 printf ("Convolver map: IR-chn %d: in %d -> out %d\n", ir_c + 1, io_i + 1, io_o + 1);
162 #endif
163
164                 boost::shared_ptr<Readable> r = _readables[ir_c % n_chn];
165                 assert (r->readable_length () == _max_size);
166                 assert (r->n_channels () == 1);
167
168                 uint32_t pos = 0;
169                 while (true) {
170                         float ir[8192];
171                         samplecnt_t to_read = std::min ((uint32_t)8192, _max_size - pos);
172                         samplecnt_t ns = r->read (ir, pos, to_read, 0);
173
174                         if (ns == 0) {
175                                 assert (pos == _max_size);
176                                 break;
177                         }
178
179                         rv = _convproc.impdata_create (
180                                         /*i/o map */ io_i, io_o,
181                                         /*stride, de-interleave */1,
182                                         ir,
183                                         _initial_delay + pos, _initial_delay + pos + ns);
184
185                         if (rv != 0) {
186                                 break;
187                         }
188
189                         pos += ns;
190
191                         if (pos == _max_size) {
192                                 break;
193                         }
194                 };
195         }
196
197         if (rv == 0) {
198                 rv = _convproc.start_process (pbd_absolute_rt_priority (PBD_SCHED_FIFO, AudioEngine::instance()->client_real_time_priority() - 2), PBD_SCHED_FIFO);
199         }
200
201         assert (rv == 0); // bail out in debug builds
202
203         if (rv != 0) {
204                 _convproc.stop_process ();
205                 _convproc.cleanup ();
206                 _configured = false;
207                 return;
208         }
209
210         _configured = true;
211
212 #ifndef NDEBUG
213         _convproc.print (stdout);
214 #endif
215 }
216
217 bool
218 Convolver::ready () const {
219         return _configured && _convproc.state () == Convproc::ST_PROC;
220 }
221
222 void
223 Convolver::run (float* buf, uint32_t n_samples)
224 {
225         assert (_convproc.state () == Convproc::ST_PROC);
226         assert (_irc == Mono);
227
228         uint32_t done = 0;
229         uint32_t remain = n_samples;
230
231         while (remain > 0) {
232                 uint32_t ns = std::min (remain, _n_samples - _offset);
233
234                 float* const       in  = _convproc.inpdata (/*channel*/0);
235                 float const* const out = _convproc.outdata (/*channel*/0);
236
237                 memcpy (&in[_offset], &buf[done], sizeof (float) * ns);
238                 memcpy (&buf[done], &out[_offset], sizeof (float) * ns);
239
240                 _offset += ns;
241                 done    += ns;
242                 remain  -= ns;
243
244                 if (_offset == _n_samples) {
245                         _convproc.process (/*sync, freewheeling*/ true);
246                         _offset = 0;
247                 }
248         }
249 }
250
251 void
252 Convolver::run_stereo (float* left, float* right, uint32_t n_samples)
253 {
254         assert (_convproc.state () == Convproc::ST_PROC);
255         assert (_irc != Mono);
256
257         uint32_t done = 0;
258         uint32_t remain = n_samples;
259
260         while (remain > 0) {
261                 uint32_t ns = std::min (remain, _n_samples - _offset);
262
263                 memcpy (&_convproc.inpdata(0)[_offset], &left[done], sizeof (float) * ns);
264                 if (_irc >= Stereo) {
265                         memcpy (&_convproc.inpdata(1)[_offset], &right[done], sizeof (float) * ns);
266                 }
267                 memcpy (&left[done],  &_convproc.outdata(0)[_offset], sizeof (float) * ns);
268                 memcpy (&right[done], &_convproc.outdata(1)[_offset], sizeof (float) * ns);
269
270                 _offset += ns;
271                 done    += ns;
272                 remain  -= ns;
273
274                 if (_offset == _n_samples) {
275                         _convproc.process (true);
276                         _offset = 0;
277                 }
278         }
279 }