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