configurable midi audition synth
[ardour.git] / libs / ardour / auditioner.cc
1 /*
2     Copyright (C) 2001 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (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., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <glibmm/threads.h>
21
22 #include "pbd/error.h"
23
24 #include "ardour/amp.h"
25 #include "ardour/audioregion.h"
26 #include "ardour/audioengine.h"
27 #include "ardour/audioplaylist.h"
28 #include "ardour/auditioner.h"
29 #include "ardour/audio_port.h"
30 #include "ardour/data_type.h"
31 #include "ardour/delivery.h"
32 #include "ardour/plugin.h"
33 #include "ardour/region_factory.h"
34 #include "ardour/route.h"
35 #include "ardour/session.h"
36
37 using namespace std;
38 using namespace ARDOUR;
39 using namespace PBD;
40
41 #include "i18n.h"
42
43 Auditioner::Auditioner (Session& s)
44         : Track (s, "auditioner", Route::Auditioner)
45         , current_frame (0)
46         , _auditioning (0)
47         , length (0)
48         , _seek_frame (-1)
49         , _seeking (false)
50         , _seek_complete (false)
51         , via_monitor (false)
52         , _midi_audition (false)
53         , _synth_added (false)
54         , _synth_changed (false)
55         , _queue_panic (false)
56 {
57 }
58
59 int
60 Auditioner::init ()
61 {
62         if (Track::init ()) {
63                 return -1;
64         }
65
66         if (connect ()) {
67                 return -1;
68         }
69
70         _output->add_port ("Midiaudition", this, DataType::MIDI);
71
72         lookup_synth();
73
74         _output->changed.connect_same_thread (*this, boost::bind (&Auditioner::output_changed, this, _1, _2));
75         Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Auditioner::config_changed, this, _1));
76
77         return 0;
78 }
79
80 Auditioner::~Auditioner ()
81 {
82 }
83
84 void
85 Auditioner::lookup_synth ()
86 {
87         string plugin_id = Config->get_midi_audition_synth_uri();
88         boost::shared_ptr<Plugin> p;
89         if (!plugin_id.empty()) {
90                 p = find_plugin (_session, plugin_id, ARDOUR::LV2);
91                 if (!p) {
92                         p = find_plugin (_session, "https://community.ardour.org/node/7596", ARDOUR::LV2);
93                         if (p) {
94                                 warning << _("Falling back to Reasonable Synth for Midi Audition") << endmsg;
95                         } else {
96                                 warning << _("No synth for midi-audition found.") << endmsg;
97                         }
98                 }
99         }
100         if (p) {
101                 asynth = boost::shared_ptr<Processor> (new PluginInsert (_session, p));
102         }
103 }
104
105 void
106 Auditioner::config_changed (std::string p)
107 {
108         if (p == "midi-audition-synth-uri") {
109                 _synth_changed = true;
110         }
111 }
112
113 int
114 Auditioner::connect ()
115 {
116         string left = Config->get_auditioner_output_left();
117         string right = Config->get_auditioner_output_right();
118
119         vector<string> outputs;
120         _session.engine().get_physical_outputs (DataType::AUDIO, outputs);
121
122         via_monitor = false;
123
124         if (left.empty() || left == "default") {
125                 if (_session.monitor_out()) {
126                         left = _session.monitor_out()->input()->audio (0)->name();
127                         via_monitor = true;
128                 } else {
129                         if (outputs.size() > 0) {
130                                 left = outputs[0];
131                         }
132                 }
133         }
134
135         if (right.empty() || right == "default") {
136                 if (_session.monitor_out()) {
137                         right = _session.monitor_out()->input()->audio (1)->name();
138                         via_monitor = true;
139                 } else {
140                         if (outputs.size() > 1) {
141                                 right = outputs[1];
142                         }
143                 }
144         }
145
146         _output->disconnect (this);
147
148         if (left.empty() && right.empty()) {
149                 if (_output->n_ports().n_audio() == 0) {
150                         /* ports not set up, so must be during startup */
151                         warning << _("no outputs available for auditioner - manual connection required") << endmsg;
152                 }
153         } else {
154
155                 if (_output->n_ports().n_audio() == 0) {
156
157                         /* create (and connect) new ports */
158
159                         _main_outs->defer_pan_reset ();
160                         
161                         if (left.length()) {
162                                 _output->add_port (left, this, DataType::AUDIO);
163                         }
164                         
165                         if (right.length()) {
166                                 _output->add_port (right, this, DataType::AUDIO);
167                         }
168                         
169                         _main_outs->allow_pan_reset ();
170                         _main_outs->reset_panner ();
171
172                 } else {
173                         
174                         /* reconnect existing ports */
175
176                         boost::shared_ptr<Port> oleft (_output->nth (0));
177                         boost::shared_ptr<Port> oright (_output->nth (1));
178                         if (oleft) {
179                                 oleft->connect (left);
180                         }
181                         if (oright) {
182                                 oright->connect (right);
183                         }
184                 }
185                         
186         }
187
188         return 0;
189 }
190
191
192 DataType
193 Auditioner::data_type () const {
194         if (_midi_audition) {
195                 return DataType::MIDI;
196         } else {
197                 return DataType::AUDIO;
198         }
199 }
200
201 boost::shared_ptr<Diskstream>
202 Auditioner::create_diskstream () {
203
204         {
205                 AudioDiskstream::Flag dflags = AudioDiskstream::Flag (0);
206                 dflags = AudioDiskstream::Flag (dflags | AudioDiskstream::Hidden);
207                 _diskstream_audio = boost::shared_ptr<AudioDiskstream> (new AudioDiskstream (_session, name(), dflags));
208         }
209
210         {
211                 MidiDiskstream::Flag dflags = MidiDiskstream::Flag (0);
212                 dflags = MidiDiskstream::Flag (dflags | MidiDiskstream::Hidden);
213                 _diskstream_midi = boost::shared_ptr<Diskstream> (new MidiDiskstream (_session, name(), dflags));
214                 _diskstream_midi->do_refill_with_alloc ();
215                 _diskstream_midi->playlist()->set_orig_track_id (id());
216         }
217
218         return _diskstream_audio;
219 }
220
221 int
222 Auditioner::roll (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler) {
223         if (_midi_audition) {
224                 return roll_midi(nframes, start_frame, end_frame, declick, need_butler);
225         } else {
226                 return roll_audio(nframes, start_frame, end_frame, declick, need_butler);
227         }
228 }
229
230 int
231 Auditioner::roll_midi (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler)
232 {
233         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
234         if (!lm.locked()) {
235                 return 0;
236         }
237
238         assert(_active);
239
240         framecnt_t playback_distance = nframes;
241         boost::shared_ptr<MidiDiskstream> diskstream = midi_diskstream();
242         BufferSet& bufs = _session.get_route_buffers (n_process_buffers());
243         MidiBuffer& mbuf (bufs.get_midi (0));
244         _silent = false;
245
246         ChanCount cnt (DataType::MIDI, 1);
247         cnt.set (DataType::AUDIO, bufs.count().n_audio());
248         bufs.set_count (cnt);
249
250         if (_queue_panic) {
251                 _queue_panic = false;
252                 for (uint8_t chn = 0; chn < 0xf; ++chn) {
253                         uint8_t buf[3] = { ((uint8_t) (MIDI_CMD_CONTROL | chn)), ((uint8_t) MIDI_CTL_SUSTAIN), 0 };
254                         mbuf.push_back(0, 3, buf);
255                         buf[1] = MIDI_CTL_ALL_NOTES_OFF;
256                         mbuf.push_back(0, 3, buf);
257                         buf[1] = MIDI_CTL_RESET_CONTROLLERS;
258                         mbuf.push_back(0, 3, buf);
259                 }
260                 process_output_buffers (bufs, start_frame, start_frame+1, 1, false, false);
261
262                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
263                         boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
264                         if (d) {
265                                 d->flush_buffers (nframes);
266                         }
267                 }
268         }
269
270         diskstream->get_playback (mbuf, nframes);
271
272         process_output_buffers (bufs, start_frame, end_frame, nframes,
273                                 declick, (!diskstream->record_enabled() && !_session.transport_stopped()));
274
275         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
276                 boost::shared_ptr<Delivery> d = boost::dynamic_pointer_cast<Delivery> (*i);
277                 if (d) {
278                         d->flush_buffers (nframes);
279                 }
280         }
281
282         need_butler = diskstream->commit (playback_distance);
283         return 0;
284 }
285
286
287 int
288 Auditioner::roll_audio (pframes_t nframes, framepos_t start_frame, framepos_t end_frame, int declick, bool& need_butler) {
289         Glib::Threads::RWLock::ReaderLock lm (_processor_lock, Glib::Threads::TRY_LOCK);
290         if (!lm.locked()) {
291                 return 0;
292         }
293
294         assert(n_outputs().n_total() > 0);
295         assert(_active);
296
297         int dret;
298         framecnt_t playback_distance;
299         framepos_t transport_frame = _session.transport_frame();
300         boost::shared_ptr<AudioDiskstream> diskstream = audio_diskstream();
301         BufferSet& bufs = _session.get_route_buffers (n_process_buffers ());
302
303         _silent = false;
304         _amp->apply_gain_automation(false);
305
306         if ((dret = diskstream->process (bufs, transport_frame, nframes, playback_distance, (monitoring_state() == MonitoringDisk))) != 0) {
307                 need_butler = diskstream->commit (playback_distance);
308                 silence (nframes);
309                 return dret;
310         }
311
312         process_output_buffers (bufs, start_frame, end_frame, nframes, declick, (!diskstream->record_enabled() && _session.transport_rolling()));
313         need_butler = diskstream->commit (playback_distance);
314         return 0;
315 }
316
317 void
318 Auditioner::set_diskstream (boost::shared_ptr<Diskstream> ds)
319 {
320         Track::set_diskstream (ds);
321
322         _diskstream->set_track (this);
323         _diskstream->set_destructive (_mode == Destructive);
324         _diskstream->set_non_layered (_mode == NonLayered);
325         _diskstream->set_record_enabled (false);
326         _diskstream->request_input_monitoring (false);
327
328         DiskstreamChanged (); /* EMIT SIGNAL */
329 }
330
331 AudioPlaylist&
332 Auditioner::prepare_playlist ()
333 {
334         // used by CrossfadeEditor::audition()
335
336         _midi_audition = false;
337         set_diskstream(_diskstream_audio);
338         if (_synth_added) {
339                 remove_processor(asynth);
340                 _synth_added = false;
341         }
342
343         // FIXME auditioner is still audio-only
344         boost::shared_ptr<AudioPlaylist> apl = boost::dynamic_pointer_cast<AudioPlaylist>(_diskstream->playlist());
345         assert(apl);
346
347         apl->clear ();
348         return *apl;
349 }
350
351 void
352 Auditioner::audition_region (boost::shared_ptr<Region> region)
353 {
354         if (g_atomic_int_get (&_auditioning)) {
355                 /* don't go via session for this, because we are going
356                    to remain active.
357                 */
358                 cancel_audition ();
359         }
360
361         Glib::Threads::Mutex::Lock lm (lock);
362
363         if (boost::dynamic_pointer_cast<AudioRegion>(region) != 0) {
364
365                 _midi_audition = false;
366                 set_diskstream(_diskstream_audio);
367                 if (_synth_added) {
368                         remove_processor(asynth);
369                         _synth_added = false;
370                 }
371                 midi_region.reset();
372
373                 /* copy it */
374                 the_region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region));
375                 the_region->set_position (0);
376
377                 _diskstream->playlist()->drop_regions ();
378                 _diskstream->playlist()->add_region (the_region, 0, 1);
379
380                 if (_diskstream->n_channels().n_audio() < the_region->n_channels()) {
381                         audio_diskstream()->add_channel (the_region->n_channels() - _diskstream->n_channels().n_audio());
382                 } else if (_diskstream->n_channels().n_audio() > the_region->n_channels()) {
383                         audio_diskstream()->remove_channel (_diskstream->n_channels().n_audio() - the_region->n_channels());
384                 }
385
386                 ProcessorStreams ps;
387                 {
388                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
389
390                         if (configure_processors (&ps)) {
391                                 error << string_compose (_("Cannot setup auditioner processing flow for %1 channels"),
392                                                          _diskstream->n_channels()) << endmsg;
393                                 return;
394                         }
395                 }
396
397         } else if (boost::dynamic_pointer_cast<MidiRegion>(region)) {
398                 _midi_audition = true;
399                 set_diskstream(_diskstream_midi);
400                 the_region.reset();
401
402                 /* copy it */
403                 midi_region = (boost::dynamic_pointer_cast<MidiRegion> (RegionFactory::create (region)));
404                 midi_region->set_position (0);
405
406                 _diskstream->playlist()->drop_regions ();
407                 _diskstream->playlist()->add_region (midi_region, 0, 1);
408                 midi_diskstream()->reset_tracker();
409
410                 ProcessorStreams ps;
411
412                 if (_synth_changed && _synth_added) {
413                         remove_processor(asynth);
414                         _synth_added = false;
415                 }
416                 if (_synth_changed && !_synth_added) {
417                         _synth_added = false;
418                         lookup_synth();
419                 }
420
421
422                 if (!_synth_added && asynth) {
423                         int rv = add_processor_by_index(asynth, PreFader, &ps, true);
424                         if (rv) {
425                                 error << _("Failed to load synth for MIDI-Audition.") << endmsg;
426                         } else {
427                                 _synth_added = true;
428                         }
429                 } else {
430                         _queue_panic = true;
431                 }
432
433                 {
434                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
435
436                         if (configure_processors (&ps)) {
437                                 error << string_compose (_("Cannot setup auditioner processing flow for %1 channels"),
438                                                          _diskstream->n_channels()) << endmsg;
439                                 return;
440                         }
441                 }
442
443         } else {
444                 error << _("Auditioning of regions other than Audio or Midi is not supported.") << endmsg;
445                 return;
446         }
447
448         /* force a panner reset now that we have all channels */
449         _main_outs->reset_panner();
450
451         _seek_frame = -1;
452         _seeking = false;
453
454         int dir;
455         framecnt_t offset;
456
457         if (_midi_audition) {
458                 length = midi_region->length();
459                 offset = midi_region->sync_offset (dir);
460         } else {
461                 length = the_region->length();
462                 offset = the_region->sync_offset (dir);
463         }
464
465         /* can't audition from a negative sync point */
466
467         if (dir < 0) {
468                 offset = 0;
469         }
470
471         _diskstream->seek (offset);
472         current_frame = offset;
473
474         g_atomic_int_set (&_auditioning, 1);
475 }
476
477 int
478 Auditioner::play_audition (framecnt_t nframes)
479 {
480         bool need_butler = false;
481         framecnt_t this_nframes;
482         int ret;
483
484         if (g_atomic_int_get (&_auditioning) == 0) {
485                 silence (nframes);
486                 return 0;
487         }
488
489 #if 0 // TODO
490         if (_seeking && _seek_complete) {
491                 // set FADE-IN
492         } else if (_seek_frame >= 0 && _seek_frame < length && !_seeking) {
493                 // set FADE-OUT -- use/override amp? || use region-gain ?
494         }
495 #endif
496
497         if (_seeking && _seek_complete) {
498                 _seek_complete = false;
499                 _seeking = false;
500                 _seek_frame = -1;
501                 if (_midi_audition && midi_diskstream()) {
502                         midi_diskstream()->reset_tracker();
503                 }
504         }
505
506         if(!_seeking) {
507                 /* process audio */
508                 this_nframes = min (nframes, length - current_frame);
509
510                 if ((ret = roll (this_nframes, current_frame, current_frame + nframes, false, need_butler)) != 0) {
511                         silence (nframes);
512                         return ret;
513                 }
514
515                 current_frame += this_nframes;
516
517         } else {
518                 silence (nframes);
519         }
520
521         if (_seek_frame >= 0 && _seek_frame < length && !_seeking) {
522                 _queue_panic = true;
523                 _seek_complete = false;
524                 _seeking = true;
525                 need_butler = true;
526         }
527
528         if (!_seeking) {
529                 AuditionProgress(current_frame, length); /* emit */
530         }
531
532         if (current_frame >= length) {
533                 _session.cancel_audition ();
534                 return 0;
535         } else {
536                 return need_butler ? 1 : 0;
537         }
538 }
539
540 void
541 Auditioner::output_changed (IOChange change, void* /*src*/)
542 {
543         if (change.type & IOChange::ConnectionsChanged) {
544                 string phys;
545                 vector<string> connections;
546                 vector<string> outputs;
547                 _session.engine().get_physical_outputs (DataType::AUDIO, outputs);
548                 if (_output->nth (0)->get_connections (connections)) {
549                         if (outputs.size() > 0) {
550                                 phys = outputs[0];
551                         }
552                         if (phys != connections[0]) {
553                                 Config->set_auditioner_output_left (connections[0]);
554                         } else {
555                                 Config->set_auditioner_output_left ("default");
556                         }
557                 } else {
558                         Config->set_auditioner_output_left ("");
559                 }
560
561                 connections.clear ();
562
563                 if (_output->nth (1)->get_connections (connections)) {
564                         if (outputs.size() > 1) {
565                                 phys = outputs[1];
566                         }
567                         if (phys != connections[0]) {
568                                 Config->set_auditioner_output_right (connections[0]);
569                         } else {
570                                 Config->set_auditioner_output_right ("default");
571                         }
572                 } else {
573                         Config->set_auditioner_output_right ("");
574                 }
575         }
576 }
577
578 ChanCount
579 Auditioner::input_streams () const
580 {
581         /* auditioner never has any inputs - its channel configuration
582                  depends solely on the region we are auditioning.
583                  */
584
585         if (!_midi_audition && audio_diskstream()) {
586                 return audio_diskstream()->n_channels();
587         }
588         if (_midi_audition && midi_diskstream()) {
589                 ChanCount cnt (DataType::MIDI, 1);
590                 return cnt;
591         }
592
593         return ChanCount ();
594 }
595
596 MonitorState
597 Auditioner::monitoring_state () const
598 {
599         return MonitoringDisk;
600 }