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