make "exclusive solo" apply to listen as well as SiP
[ardour.git] / libs / ardour / route.cc
1 /*
2     Copyright (C) 2000 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 <cmath>
21 #include <fstream>
22 #include <cassert>
23 #include <algorithm>
24
25 #include "pbd/xml++.h"
26 #include "pbd/enumwriter.h"
27 #include "pbd/memento_command.h"
28 #include "pbd/stacktrace.h"
29 #include "pbd/convert.h"
30
31 #include "evoral/Curve.hpp"
32
33 #include "ardour/amp.h"
34 #include "ardour/audio_port.h"
35 #include "ardour/audioengine.h"
36 #include "ardour/buffer.h"
37 #include "ardour/buffer_set.h"
38 #include "ardour/configuration.h"
39 #include "ardour/cycle_timer.h"
40 #include "ardour/debug.h"
41 #include "ardour/delivery.h"
42 #include "ardour/dB.h"
43 #include "ardour/internal_send.h"
44 #include "ardour/internal_return.h"
45 #include "ardour/ladspa_plugin.h"
46 #include "ardour/meter.h"
47 #include "ardour/mix.h"
48 #include "ardour/monitor_processor.h"
49 #include "ardour/panner.h"
50 #include "ardour/plugin_insert.h"
51 #include "ardour/port.h"
52 #include "ardour/port_insert.h"
53 #include "ardour/processor.h"
54 #include "ardour/profile.h"
55 #include "ardour/route.h"
56 #include "ardour/route_group.h"
57 #include "ardour/send.h"
58 #include "ardour/session.h"
59 #include "ardour/timestamps.h"
60 #include "ardour/utils.h"
61
62 #include "i18n.h"
63
64 using namespace std;
65 using namespace ARDOUR;
66 using namespace PBD;
67
68 uint32_t Route::order_key_cnt = 0;
69 PBD::Signal1<void,string const&> Route::SyncOrderKeys;
70 PBD::Signal0<void> Route::RemoteControlIDChange;
71
72 Route::Route (Session& sess, string name, Flag flg, DataType default_type)
73         : SessionObject (sess, name)
74         , AutomatableControls (sess)
75         , _active (true)
76         , _initial_delay (0)
77         , _roll_delay (0)
78         , _flags (flg)
79         , _pending_declick (true)
80         , _meter_point (MeterPostFader)
81         , _phase_invert (0)
82         , _self_solo (false)
83         , _soloed_by_others_upstream (0)
84         , _soloed_by_others_downstream (0)
85         , _solo_isolated (0)
86         , _denormal_protection (false)
87         , _recordable (true)
88         , _silent (false)
89         , _declickable (false)
90         , _solo_control (new SoloControllable (X_("solo"), *this))
91         , _mute_control (new MuteControllable (X_("mute"), *this))
92         , _mute_master (new MuteMaster (sess, name))
93         , _mute_points (MuteMaster::AllPoints)
94         , _have_internal_generator (false)
95         , _physically_connected (false)
96         , _graph_level (-1)
97         , _solo_safe (false)
98         , _default_type (default_type)
99         , _remote_control_id (0)
100         , _in_configure_processors (false)
101 {
102         processor_max_streams.reset();
103         order_keys[N_("signal")] = order_key_cnt++;
104 }
105
106 int
107 Route::init ()
108 {
109         /* add standard controls */
110
111         _solo_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
112         _mute_control->set_flags (Controllable::Flag (_solo_control->flags() | Controllable::Toggle));
113         
114         add_control (_solo_control);
115         add_control (_mute_control);
116
117         /* input and output objects */
118
119         _input.reset (new IO (_session, _name, IO::Input, _default_type));
120         _output.reset (new IO (_session, _name, IO::Output, _default_type));
121
122         _input->changed.connect_same_thread (*this, boost::bind (&Route::input_change_handler, this, _1, _2));
123         _output->changed.connect_same_thread (*this, boost::bind (&Route::output_change_handler, this, _1, _2));
124
125         /* add amp processor  */
126
127         _amp.reset (new Amp (_session, _mute_master));
128         add_processor (_amp, PostFader);
129
130         /* add standard processors: meter, main outs, monitor out */
131
132         _meter.reset (new PeakMeter (_session));
133         _meter->set_display_to_user (false);
134
135         add_processor (_meter, PostFader);
136
137         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
138
139         add_processor (_main_outs, PostFader);
140
141         if (is_monitor()) {
142                 /* where we listen to tracks */
143                 _intreturn.reset (new InternalReturn (_session));
144                 add_processor (_intreturn, PreFader);
145
146                 ProcessorList::iterator i;
147
148                 for (i = _processors.begin(); i != _processors.end(); ++i) {
149                         if (*i == _intreturn) {
150                                 ++i;
151                                 break;
152                         }
153                 }
154
155                 /* the thing that provides proper control over a control/monitor/listen bus 
156                    (such as per-channel cut, dim, solo, invert, etc).
157                    It always goes right after the internal return;
158                  */
159                 _monitor_control.reset (new MonitorProcessor (_session));
160                 add_processor (_monitor_control, i);
161
162                 /* no panning on the monitor main outs */
163
164                 _main_outs->panner()->set_bypassed (true);
165         }
166
167         if (is_master() || is_monitor() || is_hidden()) {
168                 _mute_master->set_solo_ignore (true);
169         }
170
171         /* now that we have _meter, its safe to connect to this */
172
173         Metering::Meter.connect_same_thread (*this, (boost::bind (&Route::meter, this)));
174
175         return 0;
176 }
177
178 Route::~Route ()
179 {
180         DEBUG_TRACE (DEBUG::Destruction, string_compose ("route %1 destructor\n", _name));
181
182         /* do this early so that we don't get incoming signals as we are going through destruction 
183          */
184
185         drop_connections ();
186
187         /* don't use clear_processors here, as it depends on the session which may
188            be half-destroyed by now 
189         */
190
191         Glib::RWLock::WriterLock lm (_processor_lock);
192         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
193                 (*i)->drop_references ();
194         }
195
196         _processors.clear ();
197 }
198
199 void
200 Route::set_remote_control_id (uint32_t id, bool notify_class_listeners)
201 {
202         if (id != _remote_control_id) {
203                 _remote_control_id = id;
204                 RemoteControlIDChanged ();
205                 if (notify_class_listeners) {
206                         RemoteControlIDChange ();
207                 }
208         }
209 }
210
211 uint32_t
212 Route::remote_control_id() const
213 {
214         return _remote_control_id;
215 }
216
217 long
218 Route::order_key (std::string const & name) const
219 {
220         OrderKeys::const_iterator i = order_keys.find (name);
221         if (i == order_keys.end()) {
222                 return -1;
223         }
224
225         return i->second;
226 }
227
228 void
229 Route::set_order_key (std::string const & name, long n)
230 {
231         order_keys[name] = n;
232
233         if (Config->get_sync_all_route_ordering()) {
234                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
235                         x->second = n;
236                 }
237         }
238
239         _session.set_dirty ();
240 }
241
242 /** Set all order keys to be the same as that for `base', if such a key
243  *  exists in this route.
244  *  @param base Base key.
245  */
246 void
247 Route::sync_order_keys (std::string const & base)
248 {
249         if (order_keys.empty()) {
250                 return;
251         }
252
253         OrderKeys::iterator i;
254         uint32_t key;
255
256         if ((i = order_keys.find (base)) == order_keys.end()) {
257                 /* key doesn't exist, use the first existing key (during session initialization) */
258                 i = order_keys.begin();
259                 key = i->second;
260                 ++i;
261         } else {
262                 /* key exists - use it and reset all others (actually, itself included) */
263                 key = i->second;
264                 i = order_keys.begin();
265         }
266
267         for (; i != order_keys.end(); ++i) {
268                 i->second = key;
269         }
270 }
271
272 string
273 Route::ensure_track_or_route_name(string name, Session &session)
274 {
275         string newname = name;
276
277         while (!session.io_name_is_legal (newname)) {
278                 newname = bump_name_once (newname);
279         }
280
281         return newname;
282 }
283
284
285 void
286 Route::inc_gain (gain_t fraction, void *src)
287 {
288         _amp->inc_gain (fraction, src);
289 }
290
291 void
292 Route::set_gain (gain_t val, void *src)
293 {
294         if (src != 0 && _route_group && src != _route_group && _route_group->is_active() && _route_group->is_gain()) {
295
296                 if (_route_group->is_relative()) {
297
298                         gain_t usable_gain = _amp->gain();
299                         if (usable_gain < 0.000001f) {
300                                 usable_gain = 0.000001f;
301                         }
302
303                         gain_t delta = val;
304                         if (delta < 0.000001f) {
305                                 delta = 0.000001f;
306                         }
307
308                         delta -= usable_gain;
309
310                         if (delta == 0.0f)
311                                 return;
312
313                         gain_t factor = delta / usable_gain;
314
315                         if (factor > 0.0f) {
316                                 factor = _route_group->get_max_factor(factor);
317                                 if (factor == 0.0f) {
318                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
319                                         return;
320                                 }
321                         } else {
322                                 factor = _route_group->get_min_factor(factor);
323                                 if (factor == 0.0f) {
324                                         _amp->gain_control()->Changed(); /* EMIT SIGNAL */
325                                         return;
326                                 }
327                         }
328
329                         _route_group->apply (&Route::inc_gain, factor, _route_group);
330
331                 } else {
332
333                         _route_group->apply (&Route::set_gain, val, _route_group);
334                 }
335
336                 return;
337         }
338
339         if (val == _amp->gain()) {
340                 return;
341         }
342
343         _amp->set_gain (val, src);
344 }
345
346 /** Process this route for one (sub) cycle (process thread)
347  *
348  * @param bufs Scratch buffers to use for the signal path
349  * @param start_frame Initial transport frame
350  * @param end_frame Final transport frame
351  * @param nframes Number of frames to output (to ports)
352  *
353  * Note that (end_frame - start_frame) may not be equal to nframes when the
354  * transport speed isn't 1.0 (eg varispeed).
355  */
356 void
357 Route::process_output_buffers (BufferSet& bufs,
358                                sframes_t start_frame, sframes_t end_frame, nframes_t nframes,
359                                bool /*with_processors*/, int declick)
360 {
361         bool monitor;
362
363         bufs.is_silent (false);
364
365         switch (Config->get_monitoring_model()) {
366         case HardwareMonitoring:
367         case ExternalMonitoring:
368                 monitor = !record_enabled() || (_session.config.get_auto_input() && !_session.actively_recording());
369                 break;
370         default:
371                 monitor = true;
372         }
373
374         if (!declick) {
375                 declick = _pending_declick;
376         }
377
378         /* figure out if we're going to use gain automation */
379         _amp->setup_gain_automation (start_frame, end_frame, nframes);
380
381
382         /* tell main outs what to do about monitoring */
383         _main_outs->no_outs_cuz_we_no_monitor (!monitor);
384
385
386         /* -------------------------------------------------------------------------------------------
387            GLOBAL DECLICK (for transport changes etc.)
388            ----------------------------------------------------------------------------------------- */
389
390         if (declick > 0) {
391                 Amp::apply_gain (bufs, nframes, 0.0, 1.0);
392         } else if (declick < 0) {
393                 Amp::apply_gain (bufs, nframes, 1.0, 0.0);
394         }
395
396         _pending_declick = 0;
397
398         /* -------------------------------------------------------------------------------------------
399            DENORMAL CONTROL/PHASE INVERT
400            ----------------------------------------------------------------------------------------- */
401
402         if (_phase_invert) {
403
404                 int chn = 0;
405
406                 if (_denormal_protection || Config->get_denormal_protection()) {
407
408                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
409                                 Sample* const sp = i->data();
410
411                                 if (_phase_invert & chn) {
412                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
413                                                 sp[nx]  = -sp[nx];
414                                                 sp[nx] += 1.0e-27f;
415                                         }
416                                 } else {
417                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
418                                                 sp[nx] += 1.0e-27f;
419                                         }
420                                 }
421                         }
422
423                 } else {
424
425                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i, ++chn) {
426                                 Sample* const sp = i->data();
427
428                                 if (_phase_invert & (1<<chn)) {
429                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
430                                                 sp[nx] = -sp[nx];
431                                         }
432                                 }
433                         }
434                 }
435
436         } else {
437
438                 if (_denormal_protection || Config->get_denormal_protection()) {
439
440                         for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
441                                 Sample* const sp = i->data();
442                                 for (nframes_t nx = 0; nx < nframes; ++nx) {
443                                         sp[nx] += 1.0e-27f;
444                                 }
445                         }
446
447                 }
448         }
449
450         /* -------------------------------------------------------------------------------------------
451            and go ....
452            ----------------------------------------------------------------------------------------- */
453
454         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
455
456         if (rm.locked()) {
457                 //cerr << name() << " upstream solo " << _soloed_by_others_upstream
458                 // << " downstream solo " << _soloed_by_others_downstream
459                 // << " self " << _self_solo
460                 //<< endl;
461                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
462
463                         if (bufs.count() != (*i)->input_streams()) {
464                                 cerr << _name << " bufs = " << bufs.count()
465                                      << " input for " << (*i)->name() << " = " << (*i)->input_streams()
466                                      << endl;
467                         }
468                         assert (bufs.count() == (*i)->input_streams());
469
470                         (*i)->run (bufs, start_frame, end_frame, nframes, *i != _processors.back());
471                         bufs.set_count ((*i)->output_streams());
472                 }
473         }
474 }
475
476 ChanCount
477 Route::n_process_buffers ()
478 {
479         return max (_input->n_ports(), processor_max_streams);
480 }
481
482 void
483 Route::passthru (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
484 {
485         BufferSet& bufs = _session.get_scratch_buffers (n_process_buffers());
486
487         _silent = false;
488
489         assert (bufs.available() >= input_streams());
490
491         if (_input->n_ports() == ChanCount::ZERO) {
492                 silence (nframes);
493         }
494
495         bufs.set_count (input_streams());
496
497         if (is_monitor() && _session.listening() && !_session.is_auditioning()) {
498
499                 /* control/monitor bus ignores input ports when something is
500                    feeding the listen "stream". data will "arrive" into the
501                    route from the intreturn processor element.
502                 */
503                 bufs.silence (nframes, 0);
504
505         } else {
506
507                 for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
508
509                         BufferSet::iterator o = bufs.begin(*t);
510                         PortSet& ports (_input->ports());
511
512                         for (PortSet::iterator i = ports.begin(*t); i != ports.end(*t); ++i, ++o) {
513                                 o->read_from (i->get_buffer(nframes), nframes);
514                         }
515                 }
516         }
517
518         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
519         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
520 }
521
522 void
523 Route::passthru_silence (sframes_t start_frame, sframes_t end_frame, nframes_t nframes, int declick)
524 {
525         BufferSet& bufs (_session.get_silent_buffers (n_process_buffers()));
526         bufs.set_count (_input->n_ports());
527         write_out_of_band_data (bufs, start_frame, end_frame, nframes);
528         process_output_buffers (bufs, start_frame, end_frame, nframes, true, declick);
529 }
530
531 void
532 Route::set_listen (bool yn, void* src)
533 {
534         if (_solo_safe) {
535                 return;
536         }
537
538         if (_monitor_send) {
539                 cerr << name() << " set listen = " << yn << " current = " << _monitor_send->active() << endl;
540                 if (yn != _monitor_send->active()) {
541                         if (yn) {
542                                 _monitor_send->activate ();
543                                 _mute_master->set_soloed (true);
544                         } else {
545                                 _monitor_send->deactivate ();
546                                 _mute_master->set_soloed (false);
547                         }
548
549                         listen_changed (src); /* EMIT SIGNAL */
550                 }
551         }
552 }
553
554 bool
555 Route::listening () const
556 {
557         if (_monitor_send) {
558                 return _monitor_send->active ();
559         } else {
560                 return false;
561         }
562 }
563
564 void
565 Route::set_solo_safe (bool yn, void *src)
566 {
567         if (_solo_safe != yn) {
568                 _solo_safe = yn;
569                 solo_safe_changed (src);
570         } 
571 }
572
573 bool
574 Route::solo_safe() const
575 {
576         return _solo_safe;
577 }
578
579 void
580 Route::set_solo (bool yn, void *src)
581 {
582         if (_solo_safe) {
583                 return;
584         }
585
586         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
587                 _route_group->apply (&Route::set_solo, yn, _route_group);
588                 return;
589         }
590
591         if (self_soloed() != yn) {
592                 set_self_solo (yn);
593                 set_mute_master_solo ();
594                 solo_changed (true, src); /* EMIT SIGNAL */
595                 _solo_control->Changed (); /* EMIT SIGNAL */
596         }
597 }
598
599 void
600 Route::set_self_solo (bool yn)
601 {
602         _self_solo = yn;
603 }
604
605 void
606 Route::mod_solo_by_others_upstream (int32_t delta)
607 {
608         if (_solo_safe) {
609                 return;
610         }
611
612         uint32_t old_sbu = _soloed_by_others_upstream;
613
614         if (delta < 0) {
615                 if (_soloed_by_others_upstream >= (uint32_t) abs (delta)) {
616                         _soloed_by_others_upstream += delta;
617                 } else {
618                         _soloed_by_others_upstream = 0;
619                 }
620         } else {
621                 _soloed_by_others_upstream += delta;
622         }
623
624         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 SbU delta %2 = %3 old = %4 sbd %5 ss %6 exclusive %7\n",
625                                                   name(), delta, _soloed_by_others_upstream, old_sbu, 
626                                                   _soloed_by_others_downstream, _self_solo, Config->get_exclusive_solo()));
627
628         /* push the inverse solo change to everything that feeds us. 
629            
630            This is important for solo-within-group. When we solo 1 track out of N that
631            feed a bus, that track will cause mod_solo_by_upstream (+1) to be called
632            on the bus. The bus then needs to call mod_solo_by_downstream (-1) on all
633            tracks that feed it. This will silence them if they were audible because
634            of a bus solo, but the newly soloed track will still be audible (because 
635            it is self-soloed).
636            
637            but .. do this only when we are being told to solo-by-upstream (i.e delta = +1),
638            not in reverse.
639          */
640
641         if ((_self_solo || _soloed_by_others_downstream) &&
642             ((old_sbu == 0 && _soloed_by_others_upstream > 0) || 
643              (old_sbu > 0 && _soloed_by_others_upstream == 0))) {
644                 
645                 if (delta > 0 || !Config->get_exclusive_solo()) {
646                         DEBUG_TRACE (DEBUG::Solo, "\t ... INVERT push\n");
647                         for (FedBy::iterator i = _fed_by.begin(); i != _fed_by.end(); ++i) {
648                                 boost::shared_ptr<Route> sr = i->r.lock();
649                                 if (sr) {
650                                         sr->mod_solo_by_others_downstream (-delta);
651                                 }
652                         }
653                 } 
654         }
655
656         set_mute_master_solo ();
657         solo_changed (false, this);
658 }
659
660 void
661 Route::mod_solo_by_others_downstream (int32_t delta)
662 {
663         if (_solo_safe) {
664                 return;
665         }
666
667         if (delta < 0) {
668                 if (_soloed_by_others_downstream >= (uint32_t) abs (delta)) {
669                         _soloed_by_others_downstream += delta;
670                 } else {
671                         _soloed_by_others_downstream = 0;
672                 }
673         } else {
674                 _soloed_by_others_downstream += delta;
675         }
676
677         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 SbD delta %2 = %3\n", name(), delta, _soloed_by_others_downstream));
678
679         set_mute_master_solo ();
680         solo_changed (false, this);
681 }
682
683 void
684 Route::set_mute_master_solo ()
685 {
686         _mute_master->set_soloed (self_soloed() || soloed_by_others_downstream() || soloed_by_others_upstream());
687 }
688
689 void
690 Route::set_solo_isolated (bool yn, void *src)
691 {
692         if (is_master() || is_monitor() || is_hidden()) {
693                 return;
694         }
695
696         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_solo()) {
697                 _route_group->apply (&Route::set_solo_isolated, yn, _route_group);
698                 return;
699         }
700         
701         /* forward propagate solo-isolate status to everything fed by this route, but not those via sends only */
702
703         boost::shared_ptr<RouteList> routes = _session.get_routes ();
704         for (RouteList::iterator i = routes->begin(); i != routes->end(); ++i) {
705
706                 if ((*i).get() == this || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
707                         continue;
708                 }
709
710                 bool sends_only;
711                 bool does_feed = direct_feeds (*i, &sends_only); // we will recurse anyway, so don't use ::feeds()
712                 
713                 if (does_feed && !sends_only) {
714                         (*i)->set_solo_isolated (yn, (*i)->route_group());
715                 }
716         }
717
718         /* XXX should we back-propagate as well? (April 2010: myself and chris goddard think not) */
719
720         if (yn) {
721                 if (_solo_isolated == 0) {
722                         _mute_master->set_solo_ignore (true);
723                 }
724                 _solo_isolated++;
725                 solo_isolated_changed (src);
726         } else {
727                 if (_solo_isolated > 0) {
728                         _solo_isolated--;
729                         if (_solo_isolated == 0) {
730                                 _mute_master->set_solo_ignore (false);
731                         }
732                         solo_isolated_changed (src);
733                 }
734         }
735
736 }
737
738 bool
739 Route::solo_isolated () const
740 {
741         return _solo_isolated > 0;
742 }
743
744 void
745 Route::set_mute_points (MuteMaster::MutePoint mp)
746 {
747         _mute_points = mp;
748         _mute_master->set_mute_points (MuteMaster::AllPoints);
749         mute_points_changed (); /* EMIT SIGNAL */
750         
751         if (_mute_master->muted()) {
752                 mute_changed (this); /* EMIT SIGNAL */
753         }
754 }
755
756 void
757 Route::set_mute (bool yn, void *src)
758 {
759         if (_route_group && src != _route_group && _route_group->is_active() && _route_group->is_mute()) {
760                 _route_group->apply (&Route::set_mute, yn, _route_group);
761                 return;
762         }
763
764         if (muted() != yn) {
765                 _mute_master->set_muted (yn);
766                 mute_changed (src); /* EMIT SIGNAL */
767         }
768 }
769
770 bool
771 Route::muted () const
772 {
773         return _mute_master->muted();
774 }
775
776 #if 0
777 static void
778 dump_processors(const string& name, const list<boost::shared_ptr<Processor> >& procs)
779 {
780         cerr << name << " {" << endl;
781         for (list<boost::shared_ptr<Processor> >::const_iterator p = procs.begin();
782                         p != procs.end(); ++p) {
783                 cerr << "\t" << (*p)->name() << " ID = " << (*p)->id() << endl;
784         }
785         cerr << "}" << endl;
786 }
787 #endif
788
789 int
790 Route::add_processor (boost::shared_ptr<Processor> processor, Placement placement, ProcessorStreams* err)
791 {
792         ProcessorList::iterator loc;
793
794         /* XXX this is not thread safe - we don't hold the lock across determining the iter
795            to add before and actually doing the insertion. dammit.
796         */
797
798         if (placement == PreFader) {
799                 /* generic pre-fader: insert immediately before the amp */
800                 loc = find (_processors.begin(), _processors.end(), _amp);
801         } else {
802                 /* generic post-fader: insert right before the main outs */
803                 loc = find (_processors.begin(), _processors.end(), _main_outs);
804         }
805
806         return add_processor (processor, loc, err);
807 }
808
809
810 /** Add a processor to the route.
811  * @a iter must point to an iterator in _processors and the new
812  * processor will be inserted immediately before this location.  Otherwise,
813  * @a position is used.
814  */
815 int
816 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorList::iterator iter, ProcessorStreams* err, bool activation_allowed)
817 {
818         ChanCount old_pms = processor_max_streams;
819
820         if (!_session.engine().connected() || !processor) {
821                 return 1;
822         }
823
824         {
825                 Glib::RWLock::WriterLock lm (_processor_lock);
826
827                 boost::shared_ptr<PluginInsert> pi;
828                 boost::shared_ptr<PortInsert> porti;
829
830                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), processor);
831
832                 if (processor == _amp || processor == _meter || processor == _main_outs) {
833                         // Ensure only one of these are in the list at any time
834                         if (loc != _processors.end()) {
835                                 if (iter == loc) { // Already in place, do nothing
836                                         return 0;
837                                 } else { // New position given, relocate
838                                         _processors.erase (loc);
839                                 }
840                         }
841
842                 } else {
843                         if (loc != _processors.end()) {
844                                 cerr << "ERROR: Processor added to route twice!" << endl;
845                                 return 1;
846                         }
847
848                         loc = iter;
849                 }
850
851                 _processors.insert (loc, processor);
852
853                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
854                 // configure redirect ports properly, etc.
855
856                 if (configure_processors_unlocked (err)) {
857                         ProcessorList::iterator ploc = loc;
858                         --ploc;
859                         _processors.erase(ploc);
860                         configure_processors_unlocked (0); // it worked before we tried to add it ...
861                         cerr << "configure failed\n";
862                         return -1;
863                 }
864
865                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
866
867                         if (pi->natural_input_streams() == ChanCount::ZERO) {
868                                 /* generator plugin */
869                                 _have_internal_generator = true;
870                         }
871
872                 }
873
874                 /* is this the monitor send ? if so, make sure we keep track of it */
875
876                 boost::shared_ptr<InternalSend> isend = boost::dynamic_pointer_cast<InternalSend> (processor);
877
878                 if (isend && _session.monitor_out() && (isend->target_id() == _session.monitor_out()->id())) {
879                         _monitor_send = isend;
880                 }
881
882                 if (activation_allowed && (processor != _monitor_send)) {
883                         processor->activate ();
884                 }
885
886                 processor->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
887
888                 _output->set_user_latency (0);
889         }
890
891         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
892
893         return 0;
894 }
895
896 bool
897 Route::add_processor_from_xml_2X (const XMLNode& node, int version, ProcessorList::iterator iter)
898 {
899         const XMLProperty *prop;
900
901         try {
902                 boost::shared_ptr<Processor> processor;
903
904                 if (node.name() == "Insert") {
905
906                         if ((prop = node.property ("type")) != 0) {
907
908                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
909                                                 prop->value() == "lv2" ||
910                                                 prop->value() == "vst" ||
911                                                 prop->value() == "audiounit") {
912
913                                         processor.reset (new PluginInsert (_session));
914
915                                 } else {
916
917                                         processor.reset (new PortInsert (_session, _mute_master));
918                                 }
919
920                         }
921
922                 } else if (node.name() == "Send") {
923
924                         processor.reset (new Send (_session, _mute_master));
925
926                 } else {
927
928                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), node.name()) << endmsg;
929                         return false;
930                 }
931
932                 if (processor->set_state (node, version)) {
933                         return false;
934                 }
935
936                 if (iter == _processors.end() && processor->display_to_user() && !_processors.empty()) {
937                         /* check for invisible processors stacked at the end and leave them there */
938                         ProcessorList::iterator p;
939                         p = _processors.end();
940                         --p;
941                         while (!(*p)->display_to_user() && p != _processors.begin()) {
942                                 --p;
943                         }
944                         ++p;
945                         iter = p;
946                 }
947
948                 return (add_processor (processor, iter) == 0);
949         }
950
951         catch (failed_constructor &err) {
952                 warning << _("processor could not be created. Ignored.") << endmsg;
953                 return false;
954         }
955 }
956
957 int
958 Route::add_processors (const ProcessorList& others, boost::shared_ptr<Processor> before, ProcessorStreams* err)
959 {
960         ProcessorList::iterator loc;
961
962         if (before) {
963                 loc = find(_processors.begin(), _processors.end(), before);
964         } else {
965                 /* nothing specified - at end but before main outs */
966                 loc = find (_processors.begin(), _processors.end(), _main_outs);
967         }
968
969         return add_processors (others, loc, err);
970 }
971
972 int
973 Route::add_processors (const ProcessorList& others, ProcessorList::iterator iter, ProcessorStreams* err)
974 {
975         /* NOTE: this is intended to be used ONLY when copying
976            processors from another Route. Hence the subtle
977            differences between this and ::add_processor()
978         */
979
980         ChanCount old_pms = processor_max_streams;
981
982         if (!_session.engine().connected()) {
983                 return 1;
984         }
985
986         if (others.empty()) {
987                 return 0;
988         }
989
990         {
991                 Glib::RWLock::WriterLock lm (_processor_lock);
992
993                 ChanCount potential_max_streams = ChanCount::max (_input->n_ports(), _output->n_ports());
994
995                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
996
997                         // Ensure meter only appears in the list once
998                         if (*i == _meter) {
999                                 ProcessorList::iterator m = find(_processors.begin(), _processors.end(), *i);
1000                                 if (m != _processors.end()) {
1001                                         _processors.erase(m);
1002                                 }
1003                         }
1004
1005                         boost::shared_ptr<PluginInsert> pi;
1006
1007                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1008                                 pi->set_count (1);
1009
1010                                 ChanCount m = max (pi->input_streams(), pi->output_streams());
1011
1012                                 if (m > potential_max_streams) {
1013                                         potential_max_streams = m;
1014                                 }
1015                         }
1016
1017                         ProcessorList::iterator inserted = _processors.insert (iter, *i);
1018
1019                         if ((*i)->active()) {
1020                                 (*i)->activate ();
1021                         }
1022
1023                         if (configure_processors_unlocked (err)) {
1024                                 _processors.erase (inserted);
1025                                 configure_processors_unlocked (0); // it worked before we tried to add it ...
1026                                 return -1;
1027                         }
1028
1029                         (*i)->ActiveChanged.connect_same_thread (*this, boost::bind (&Session::update_latency_compensation, &_session, false, false));
1030                 }
1031
1032                 _output->set_user_latency (0);
1033         }
1034
1035         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1036
1037         return 0;
1038 }
1039
1040 void
1041 Route::placement_range(Placement p, ProcessorList::iterator& start, ProcessorList::iterator& end)
1042 {
1043         if (p == PreFader) {
1044                 start = _processors.begin();
1045                 end = find(_processors.begin(), _processors.end(), _amp);
1046         } else {
1047                 start = find(_processors.begin(), _processors.end(), _amp);
1048                 ++start;
1049                 end = _processors.end();
1050         }
1051 }
1052
1053 /** Turn off all processors with a given placement
1054  * @param p Placement of processors to disable
1055  */
1056 void
1057 Route::disable_processors (Placement p)
1058 {
1059         Glib::RWLock::ReaderLock lm (_processor_lock);
1060
1061         ProcessorList::iterator start, end;
1062         placement_range(p, start, end);
1063
1064         for (ProcessorList::iterator i = start; i != end; ++i) {
1065                 (*i)->deactivate ();
1066         }
1067
1068         _session.set_dirty ();
1069 }
1070
1071 /** Turn off all redirects
1072  */
1073 void
1074 Route::disable_processors ()
1075 {
1076         Glib::RWLock::ReaderLock lm (_processor_lock);
1077
1078         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1079                 (*i)->deactivate ();
1080         }
1081
1082         _session.set_dirty ();
1083 }
1084
1085 /** Turn off all redirects with a given placement
1086  * @param p Placement of redirects to disable
1087  */
1088 void
1089 Route::disable_plugins (Placement p)
1090 {
1091         Glib::RWLock::ReaderLock lm (_processor_lock);
1092
1093         ProcessorList::iterator start, end;
1094         placement_range(p, start, end);
1095
1096         for (ProcessorList::iterator i = start; i != end; ++i) {
1097                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1098                         (*i)->deactivate ();
1099                 }
1100         }
1101
1102         _session.set_dirty ();
1103 }
1104
1105 /** Turn off all plugins
1106  */
1107 void
1108 Route::disable_plugins ()
1109 {
1110         Glib::RWLock::ReaderLock lm (_processor_lock);
1111
1112         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1113                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1114                         (*i)->deactivate ();
1115                 }
1116         }
1117
1118         _session.set_dirty ();
1119 }
1120
1121
1122 void
1123 Route::ab_plugins (bool forward)
1124 {
1125         Glib::RWLock::ReaderLock lm (_processor_lock);
1126
1127         if (forward) {
1128
1129                 /* forward = turn off all active redirects, and mark them so that the next time
1130                    we go the other way, we will revert them
1131                 */
1132
1133                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1134                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1135                                 continue;
1136                         }
1137
1138                         if ((*i)->active()) {
1139                                 (*i)->deactivate ();
1140                                 (*i)->set_next_ab_is_active (true);
1141                         } else {
1142                                 (*i)->set_next_ab_is_active (false);
1143                         }
1144                 }
1145
1146         } else {
1147
1148                 /* backward = if the redirect was marked to go active on the next ab, do so */
1149
1150                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1151
1152                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1153                                 continue;
1154                         }
1155
1156                         if ((*i)->get_next_ab_is_active()) {
1157                                 (*i)->activate ();
1158                         } else {
1159                                 (*i)->deactivate ();
1160                         }
1161                 }
1162         }
1163
1164         _session.set_dirty ();
1165 }
1166
1167
1168 /** Remove processors with a given placement.
1169  * @param p Placement of processors to remove.
1170  */
1171 void
1172 Route::clear_processors (Placement p)
1173 {
1174         const ChanCount old_pms = processor_max_streams;
1175
1176         if (!_session.engine().connected()) {
1177                 return;
1178         }
1179
1180         bool already_deleting = _session.deletion_in_progress();
1181         if (!already_deleting) {
1182                 _session.set_deletion_in_progress();
1183         }
1184
1185         {
1186                 Glib::RWLock::WriterLock lm (_processor_lock);
1187                 ProcessorList new_list;
1188                 ProcessorStreams err;
1189                 bool seen_amp = false;
1190
1191                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1192
1193                         if (*i == _amp) {
1194                                 seen_amp = true;
1195                         }
1196
1197                         if ((*i) == _amp || (*i) == _meter || (*i) == _main_outs) {
1198
1199                                 /* you can't remove these */
1200
1201                                 new_list.push_back (*i);
1202
1203                         } else {
1204                                 if (seen_amp) {
1205
1206                                         switch (p) {
1207                                         case PreFader:
1208                                                 new_list.push_back (*i);
1209                                                 break;
1210                                         case PostFader:
1211                                                 (*i)->drop_references ();
1212                                                 break;
1213                                         }
1214
1215                                 } else {
1216
1217                                         switch (p) {
1218                                         case PreFader:
1219                                                 (*i)->drop_references ();
1220                                                 break;
1221                                         case PostFader:
1222                                                 new_list.push_back (*i);
1223                                                 break;
1224                                         }
1225                                 }
1226                         }
1227                 }
1228
1229                 _processors = new_list;
1230                 configure_processors_unlocked (&err); // this can't fail
1231         }
1232
1233         processor_max_streams.reset();
1234         _have_internal_generator = false;
1235         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1236
1237         if (!already_deleting) {
1238                 _session.clear_deletion_in_progress();
1239         }
1240 }
1241
1242 int
1243 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1244 {
1245         /* these can never be removed */
1246
1247         if (processor == _amp || processor == _meter || processor == _main_outs) {
1248                 return 0;
1249         }
1250
1251         ChanCount old_pms = processor_max_streams;
1252
1253         if (!_session.engine().connected()) {
1254                 return 1;
1255         }
1256
1257         processor_max_streams.reset();
1258
1259         {
1260                 Glib::RWLock::WriterLock lm (_processor_lock);
1261                 ProcessorList::iterator i;
1262                 bool removed = false;
1263
1264                 for (i = _processors.begin(); i != _processors.end(); ) {
1265                         if (*i == processor) {
1266
1267                                 /* move along, see failure case for configure_processors()
1268                                    where we may need to reconfigure the processor.
1269                                 */
1270
1271                                 /* stop redirects that send signals to JACK ports
1272                                    from causing noise as a result of no longer being
1273                                    run.
1274                                 */
1275
1276                                 boost::shared_ptr<IOProcessor> iop;
1277
1278                                 if ((iop = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1279                                         if (iop->input()) {
1280                                                 iop->input()->disconnect (this);
1281                                         }
1282                                         if (iop->output()) {
1283                                                 iop->output()->disconnect (this);
1284                                         }
1285                                 }
1286
1287                                 i = _processors.erase (i);
1288                                 removed = true;
1289                                 break;
1290
1291                         } else {
1292                                 ++i;
1293                         }
1294
1295                         _output->set_user_latency (0);
1296                 }
1297
1298                 if (!removed) {
1299                         /* what? */
1300                         return 1;
1301                 }
1302
1303                 if (configure_processors_unlocked (err)) {
1304                         /* get back to where we where */
1305                         _processors.insert (i, processor);
1306                         /* we know this will work, because it worked before :) */
1307                         configure_processors_unlocked (0);
1308                         return -1;
1309                 }
1310
1311                 _have_internal_generator = false;
1312
1313                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1314                         boost::shared_ptr<PluginInsert> pi;
1315
1316                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1317                                 if (pi->is_generator()) {
1318                                         _have_internal_generator = true;
1319                                         break;
1320                                 }
1321                         }
1322                 }
1323         }
1324
1325         processor->drop_references ();
1326         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1327
1328         return 0;
1329 }
1330
1331 int
1332 Route::remove_processors (const ProcessorList& to_be_deleted, ProcessorStreams* err)
1333 {
1334         ProcessorList deleted;
1335
1336         if (!_session.engine().connected()) {
1337                 return 1;
1338         }
1339
1340         processor_max_streams.reset();
1341
1342         {
1343                 Glib::RWLock::WriterLock lm (_processor_lock);
1344                 ProcessorList::iterator i;
1345                 boost::shared_ptr<Processor> processor;
1346
1347                 ProcessorList as_we_were = _processors;
1348
1349                 for (i = _processors.begin(); i != _processors.end(); ) {
1350
1351                         processor = *i;
1352
1353                         /* these can never be removed */
1354
1355                         if (processor == _amp || processor == _meter || processor == _main_outs) {
1356                                 ++i;
1357                                 continue;
1358                         }
1359
1360                         /* see if its in the list of processors to delete */
1361
1362                         if (find (to_be_deleted.begin(), to_be_deleted.end(), processor) == to_be_deleted.end()) {
1363                                 ++i;
1364                                 continue;
1365                         }
1366
1367                         /* stop IOProcessors that send to JACK ports
1368                            from causing noise as a result of no longer being
1369                            run.
1370                         */
1371
1372                         boost::shared_ptr<IOProcessor> iop;
1373
1374                         if ((iop = boost::dynamic_pointer_cast<IOProcessor> (processor)) != 0) {
1375                                 iop->disconnect ();
1376                         }
1377
1378                         deleted.push_back (processor);
1379                         i = _processors.erase (i);
1380                 }
1381
1382                 if (deleted.empty()) {
1383                         /* none of those in the requested list were found */
1384                         return 0;
1385                 }
1386
1387                 _output->set_user_latency (0);
1388
1389                 if (configure_processors_unlocked (err)) {
1390                         /* get back to where we where */
1391                         _processors = as_we_were;
1392                         /* we know this will work, because it worked before :) */
1393                         configure_processors_unlocked (0);
1394                         return -1;
1395                 }
1396
1397                 _have_internal_generator = false;
1398
1399                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1400                         boost::shared_ptr<PluginInsert> pi;
1401
1402                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1403                                 if (pi->is_generator()) {
1404                                         _have_internal_generator = true;
1405                                         break;
1406                                 }
1407                         }
1408                 }
1409         }
1410
1411         /* now try to do what we need to so that those that were removed will be deleted */
1412
1413         for (ProcessorList::iterator i = deleted.begin(); i != deleted.end(); ++i) {
1414                 (*i)->drop_references ();
1415         }
1416
1417         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1418
1419         return 0;
1420 }
1421
1422
1423 int
1424 Route::configure_processors (ProcessorStreams* err)
1425 {
1426         if (!_in_configure_processors) {
1427                 Glib::RWLock::WriterLock lm (_processor_lock);
1428                 return configure_processors_unlocked (err);
1429         }
1430         return 0;
1431 }
1432
1433 ChanCount
1434 Route::input_streams () const
1435 {
1436         return _input->n_ports ();
1437 }
1438
1439 /** Configure the input/output configuration of each processor in the processors list.
1440  * Return 0 on success, otherwise configuration is impossible.
1441  */
1442 int
1443 Route::configure_processors_unlocked (ProcessorStreams* err)
1444 {
1445         if (_in_configure_processors) {
1446            return 0;
1447         }
1448
1449         _in_configure_processors = true;
1450
1451         // Check each processor in order to see if we can configure as requested
1452         ChanCount in = input_streams ();
1453         ChanCount out;
1454         list< pair<ChanCount,ChanCount> > configuration;
1455         uint32_t index = 0;
1456
1457         DEBUG_TRACE (DEBUG::Processors, string_compose ("%1: configure processors\n", _name));
1458 #ifndef NDEBUG
1459         DEBUG_TRACE (DEBUG::Processors, "{\n");
1460         for (list<boost::shared_ptr<Processor> >::const_iterator p = _processors.begin(); p != _processors.end(); ++p) {
1461                 DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1 ID = %2\n", (*p)->name(), (*p)->id()));
1462         }
1463         DEBUG_TRACE (DEBUG::Processors, "}\n");
1464 #endif
1465
1466         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++index) {
1467
1468                 if ((*p)->can_support_io_configuration(in, out)) {
1469                         DEBUG_TRACE (DEBUG::Processors, string_compose ("\t%1in = %2 out = %3\n",(*p)->name(), in, out));
1470                         configuration.push_back(make_pair(in, out));
1471                         in = out;
1472                 } else {
1473                         if (err) {
1474                                 err->index = index;
1475                                 err->count = in;
1476                         }
1477                         _in_configure_processors = false;
1478                         return -1;
1479                 }
1480         }
1481
1482         // We can, so configure everything
1483         list< pair<ChanCount,ChanCount> >::iterator c = configuration.begin();
1484         for (ProcessorList::iterator p = _processors.begin(); p != _processors.end(); ++p, ++c) {
1485                 (*p)->configure_io(c->first, c->second);
1486                 processor_max_streams = ChanCount::max(processor_max_streams, c->first);
1487                 processor_max_streams = ChanCount::max(processor_max_streams, c->second);
1488                 out = c->second;
1489         }
1490
1491         if (_meter) {
1492                 _meter->reset_max_channels (processor_max_streams);
1493         }
1494
1495         /* make sure we have sufficient scratch buffers to cope with the new processor
1496            configuration */
1497         {
1498                 Glib::Mutex::Lock em (_session.engine().process_lock ());
1499                 _session.ensure_buffers (n_process_buffers ());
1500         }
1501
1502         _in_configure_processors = false;
1503         return 0;
1504 }
1505
1506 void
1507 Route::all_processors_flip ()
1508 {
1509         Glib::RWLock::ReaderLock lm (_processor_lock);
1510
1511         if (_processors.empty()) {
1512                 return;
1513         }
1514
1515         bool first_is_on = _processors.front()->active();
1516
1517         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1518                 if (first_is_on) {
1519                         (*i)->deactivate ();
1520                 } else {
1521                         (*i)->activate ();
1522                 }
1523         }
1524
1525         _session.set_dirty ();
1526 }
1527
1528 /** Set all processors with a given placement to a given active state.
1529  * @param p Placement of processors to change.
1530  * @param state New active state for those processors.
1531  */
1532 void
1533 Route::all_processors_active (Placement p, bool state)
1534 {
1535         Glib::RWLock::ReaderLock lm (_processor_lock);
1536
1537         if (_processors.empty()) {
1538                 return;
1539         }
1540         ProcessorList::iterator start, end;
1541         placement_range(p, start, end);
1542
1543         bool before_amp = true;
1544         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1545                 if ((*i) == _amp) {
1546                         before_amp = false;
1547                         continue;
1548                 }
1549                 if (p == PreFader && before_amp) {
1550                         if (state) {
1551                                 (*i)->activate ();
1552                         } else {
1553                                 (*i)->deactivate ();
1554                         }
1555                 }
1556         }
1557
1558         _session.set_dirty ();
1559 }
1560
1561 bool
1562 Route::processor_is_prefader (boost::shared_ptr<Processor> p)
1563 {
1564         bool pre_fader = true;
1565         Glib::RWLock::ReaderLock lm (_processor_lock);
1566
1567         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1568
1569                 /* semantic note: if p == amp, we want to return true, so test
1570                    for equality before checking if this is the amp
1571                 */
1572
1573                 if ((*i) == p) {
1574                         break;
1575                 }
1576
1577                 if ((*i) == _amp) {
1578                         pre_fader = false;
1579                         break;
1580                 }
1581         }
1582
1583         return pre_fader;
1584 }
1585
1586 int
1587 Route::reorder_processors (const ProcessorList& new_order, ProcessorStreams* err)
1588 {
1589         /* "new_order" is an ordered list of processors to be positioned according to "placement".
1590            NOTE: all processors in "new_order" MUST be marked as display_to_user(). There maybe additional
1591            processors in the current actual processor list that are hidden. Any visible processors
1592            in the current list but not in "new_order" will be assumed to be deleted.
1593         */
1594
1595         {
1596                 Glib::RWLock::WriterLock lm (_processor_lock);
1597                 ChanCount old_pms = processor_max_streams;
1598                 ProcessorList::iterator oiter;
1599                 ProcessorList::const_iterator niter;
1600                 ProcessorList as_it_was_before = _processors;
1601                 ProcessorList as_it_will_be;
1602
1603                 oiter = _processors.begin();
1604                 niter = new_order.begin();
1605
1606                 while (niter !=  new_order.end()) {
1607
1608                         /* if the next processor in the old list is invisible (i.e. should not be in the new order)
1609                            then append it to the temp list.
1610
1611                            Otherwise, see if the next processor in the old list is in the new list. if not,
1612                            its been deleted. If its there, append it to the temp list.
1613                         */
1614
1615                         if (oiter == _processors.end()) {
1616
1617                                 /* no more elements in the old list, so just stick the rest of
1618                                    the new order onto the temp list.
1619                                 */
1620
1621                                 as_it_will_be.insert (as_it_will_be.end(), niter, new_order.end());
1622                                 while (niter != new_order.end()) {
1623                                         ++niter;
1624                                 }
1625                                 break;
1626
1627                         } else {
1628
1629                                 if (!(*oiter)->display_to_user()) {
1630
1631                                         as_it_will_be.push_back (*oiter);
1632
1633                                 } else {
1634
1635                                         /* visible processor: check that its in the new order */
1636
1637                                         if (find (new_order.begin(), new_order.end(), (*oiter)) == new_order.end()) {
1638                                                 /* deleted: do nothing, shared_ptr<> will clean up */
1639                                         } else {
1640                                                 /* ignore this one, and add the next item from the new order instead */
1641                                                 as_it_will_be.push_back (*niter);
1642                                                 ++niter;
1643                                         }
1644                                 }
1645
1646                                 /* now remove from old order - its taken care of no matter what */
1647                                 oiter = _processors.erase (oiter);
1648                         }
1649
1650                 }
1651
1652                 _processors.insert (oiter, as_it_will_be.begin(), as_it_will_be.end());
1653
1654                 if (configure_processors_unlocked (err)) {
1655                         _processors = as_it_was_before;
1656                         processor_max_streams = old_pms;
1657                         return -1;
1658                 }
1659         }
1660
1661         if (true) {
1662                 processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
1663         }
1664
1665         return 0;
1666 }
1667
1668 XMLNode&
1669 Route::get_state()
1670 {
1671         return state(true);
1672 }
1673
1674 XMLNode&
1675 Route::get_template()
1676 {
1677         return state(false);
1678 }
1679
1680 XMLNode&
1681 Route::state(bool full_state)
1682 {
1683         XMLNode *node = new XMLNode("Route");
1684         ProcessorList::iterator i;
1685         char buf[32];
1686
1687         id().print (buf, sizeof (buf));
1688         node->add_property("id", buf);
1689         node->add_property ("name", _name);
1690         node->add_property("default-type", _default_type.to_string());
1691
1692         if (_flags) {
1693                 node->add_property("flags", enum_2_string (_flags));
1694         }
1695
1696         node->add_property("active", _active?"yes":"no");
1697         node->add_property("phase-invert", _phase_invert?"yes":"no");
1698         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1699         node->add_property("meter-point", enum_2_string (_meter_point));
1700
1701         if (_route_group) {
1702                 node->add_property("route-group", _route_group->name());
1703         }
1704
1705         string order_string;
1706         OrderKeys::iterator x = order_keys.begin();
1707
1708         while (x != order_keys.end()) {
1709                 order_string += string ((*x).first);
1710                 order_string += '=';
1711                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1712                 order_string += buf;
1713
1714                 ++x;
1715
1716                 if (x == order_keys.end()) {
1717                         break;
1718                 }
1719
1720                 order_string += ':';
1721         }
1722         node->add_property ("order-keys", order_string);
1723         node->add_property ("self-solo", (_self_solo ? "yes" : "no"));
1724         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_upstream);
1725         node->add_property ("soloed-by-upstream", buf);
1726         snprintf (buf, sizeof (buf), "%d", _soloed_by_others_downstream);
1727         node->add_property ("soloed-by-downstream", buf);
1728
1729         node->add_child_nocopy (_input->state (full_state));
1730         node->add_child_nocopy (_output->state (full_state));
1731         node->add_child_nocopy (_solo_control->get_state ());
1732         node->add_child_nocopy (_mute_master->get_state ());
1733
1734         XMLNode* remote_control_node = new XMLNode (X_("RemoteControl"));
1735         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1736         remote_control_node->add_property (X_("id"), buf);
1737         node->add_child_nocopy (*remote_control_node);
1738
1739         if (_comment.length()) {
1740                 XMLNode *cmt = node->add_child ("Comment");
1741                 cmt->add_content (_comment);
1742         }
1743
1744         for (i = _processors.begin(); i != _processors.end(); ++i) {
1745                 node->add_child_nocopy((*i)->state (full_state));
1746         }
1747
1748         if (_extra_xml){
1749                 node->add_child_copy (*_extra_xml);
1750         }
1751
1752         return *node;
1753 }
1754
1755 int
1756 Route::set_state (const XMLNode& node, int version)
1757 {
1758         return _set_state (node, version, true);
1759 }
1760
1761 int
1762 Route::_set_state (const XMLNode& node, int version, bool /*call_base*/)
1763 {
1764         if (version < 3000) {
1765                 return _set_state_2X (node, version);
1766         }
1767
1768         XMLNodeList nlist;
1769         XMLNodeConstIterator niter;
1770         XMLNode *child;
1771         XMLPropertyList plist;
1772         const XMLProperty *prop;
1773
1774         if (node.name() != "Route"){
1775                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1776                 return -1;
1777         }
1778
1779         if ((prop = node.property (X_("name"))) != 0) {
1780                 Route::set_name (prop->value());
1781         }
1782
1783         if ((prop = node.property ("id")) != 0) {
1784                 _id = prop->value ();
1785         }
1786
1787         if ((prop = node.property (X_("flags"))) != 0) {
1788                 _flags = Flag (string_2_enum (prop->value(), _flags));
1789         } else {
1790                 _flags = Flag (0);
1791         }
1792
1793         if (is_master() || is_monitor() || is_hidden()) {
1794                 _mute_master->set_solo_ignore (true);
1795         }
1796
1797         /* add all processors (except amp, which is always present) */
1798
1799         nlist = node.children();
1800         XMLNode processor_state (X_("processor_state"));
1801
1802         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1803
1804                 child = *niter;
1805
1806                 if (child->name() == IO::state_node_name) {
1807                         if ((prop = child->property (X_("direction"))) == 0) {
1808                                 continue;
1809                         }
1810
1811                         if (prop->value() == "Input") {
1812                                 _input->set_state (*child, version);
1813                         } else if (prop->value() == "Output") {
1814                                 _output->set_state (*child, version);
1815                         }
1816                 }
1817
1818                 if (child->name() == X_("Processor")) {
1819                         processor_state.add_child_copy (*child);
1820                 }
1821         }
1822
1823         set_processor_state (processor_state);
1824
1825         if ((prop = node.property ("self-solo")) != 0) {
1826                 set_self_solo (string_is_affirmative (prop->value()));
1827         }
1828
1829         if ((prop = node.property ("soloed-by-upstream")) != 0) {
1830                 _soloed_by_others_upstream = 0; // needed for mod_.... () to work
1831                 mod_solo_by_others_upstream (atoi (prop->value()));
1832         }
1833
1834         if ((prop = node.property ("soloed-by-downstream")) != 0) {
1835                 _soloed_by_others_downstream = 0; // needed for mod_.... () to work
1836                 mod_solo_by_others_downstream (atoi (prop->value()));
1837         }
1838
1839         if ((prop = node.property ("solo-isolated")) != 0) {
1840                 set_solo_isolated (string_is_affirmative (prop->value()), this);
1841         }
1842
1843         if ((prop = node.property (X_("phase-invert"))) != 0) {
1844                 set_phase_invert (string_is_affirmative (prop->value()));
1845         }
1846
1847         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1848                 set_denormal_protection (string_is_affirmative (prop->value()));
1849         }
1850
1851         if ((prop = node.property (X_("active"))) != 0) {
1852                 bool yn = string_is_affirmative (prop->value());
1853                 _active = !yn; // force switch
1854                 set_active (yn);
1855         }
1856
1857         if ((prop = node.property (X_("meter-point"))) != 0) {
1858                 MeterPoint mp = MeterPoint (string_2_enum (prop->value (), _meter_point));
1859                 set_meter_point (mp);
1860                 if (_meter) {
1861                         _meter->set_display_to_user (_meter_point == MeterCustom);
1862                 }
1863         }
1864
1865         if ((prop = node.property (X_("order-keys"))) != 0) {
1866
1867                 long n;
1868
1869                 string::size_type colon, equal;
1870                 string remaining = prop->value();
1871
1872                 while (remaining.length()) {
1873
1874                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1875                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1876                                       << endmsg;
1877                         } else {
1878                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1879                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1880                                               << endmsg;
1881                                 } else {
1882                                         set_order_key (remaining.substr (0, equal), n);
1883                                 }
1884                         }
1885
1886                         colon = remaining.find_first_of (':');
1887
1888                         if (colon != string::npos) {
1889                                 remaining = remaining.substr (colon+1);
1890                         } else {
1891                                 break;
1892                         }
1893                 }
1894         }
1895
1896         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1897                 child = *niter;
1898
1899                 if (child->name() == X_("Comment")) {
1900
1901                         /* XXX this is a terrible API design in libxml++ */
1902
1903                         XMLNode *cmt = *(child->children().begin());
1904                         _comment = cmt->content();
1905
1906                 } else if (child->name() == X_("Extra")) {
1907
1908                         _extra_xml = new XMLNode (*child);
1909
1910                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
1911
1912                         if (prop->value() == "solo") {
1913                                 _solo_control->set_state (*child, version);
1914                                 _session.add_controllable (_solo_control);
1915                         }
1916
1917                 } else if (child->name() == X_("RemoteControl")) {
1918                         if ((prop = child->property (X_("id"))) != 0) {
1919                                 int32_t x;
1920                                 sscanf (prop->value().c_str(), "%d", &x);
1921                                 set_remote_control_id (x);
1922                         }
1923
1924                 } else if (child->name() == X_("MuteMaster")) {
1925                         _mute_master->set_state (*child, version);
1926                 }
1927         }
1928
1929         return 0;
1930 }
1931
1932 int
1933 Route::_set_state_2X (const XMLNode& node, int version)
1934 {
1935         XMLNodeList nlist;
1936         XMLNodeConstIterator niter;
1937         XMLNode *child;
1938         XMLPropertyList plist;
1939         const XMLProperty *prop;
1940
1941         /* 2X things which still remain to be handled:
1942          * default-type
1943          * automation
1944          * controlouts
1945          */
1946
1947         if (node.name() != "Route") {
1948                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1949                 return -1;
1950         }
1951
1952         if ((prop = node.property (X_("flags"))) != 0) {
1953                 _flags = Flag (string_2_enum (prop->value(), _flags));
1954         } else {
1955                 _flags = Flag (0);
1956         }
1957         
1958         if ((prop = node.property (X_("phase-invert"))) != 0) {
1959                 set_phase_invert (string_is_affirmative (prop->value()));
1960         }
1961
1962         if ((prop = node.property (X_("denormal-protection"))) != 0) {
1963                 set_denormal_protection (string_is_affirmative (prop->value()));
1964         }
1965
1966         if ((prop = node.property (X_("soloed"))) != 0) {
1967                 bool yn = string_is_affirmative (prop->value());
1968
1969                 /* XXX force reset of solo status */
1970
1971                 set_solo (yn, this);
1972         }
1973
1974         if ((prop = node.property (X_("muted"))) != 0) {
1975                 
1976                 bool first = true;
1977                 bool muted = string_is_affirmative (prop->value());
1978                 
1979                 if (muted){
1980                   
1981                         string mute_point;
1982                         
1983                         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1984                           
1985                                 if (string_is_affirmative (prop->value())){
1986                                         mute_point = mute_point + "PreFader";
1987                                         first = false;
1988                                 }
1989                         }
1990                         
1991                         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1992                           
1993                                 if (string_is_affirmative (prop->value())){
1994                                   
1995                                         if (!first) {
1996                                                 mute_point = mute_point + ",";
1997                                         }
1998                                         
1999                                         mute_point = mute_point + "PostFader";
2000                                         first = false;
2001                                 }
2002                         }
2003
2004                         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
2005                           
2006                                 if (string_is_affirmative (prop->value())){
2007                                   
2008                                         if (!first) {
2009                                                 mute_point = mute_point + ",";
2010                                         }
2011                                         
2012                                         mute_point = mute_point + "Listen";
2013                                         first = false;
2014                                 }
2015                         }
2016
2017                         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
2018                           
2019                                 if (string_is_affirmative (prop->value())){
2020                                   
2021                                         if (!first) {
2022                                                 mute_point = mute_point + ",";
2023                                         }
2024                                         
2025                                         mute_point = mute_point + "Main";
2026                                 }
2027                         }
2028                         
2029                         _mute_master->set_mute_points (mute_point);
2030                 }
2031         }
2032
2033         if ((prop = node.property (X_("meter-point"))) != 0) {
2034                 _meter_point = MeterPoint (string_2_enum (prop->value (), _meter_point));
2035         }
2036
2037         /* do not carry over edit/mix groups from 2.X because (a) its hard (b) they
2038            don't mean the same thing.
2039         */
2040
2041         if ((prop = node.property (X_("order-keys"))) != 0) {
2042
2043                 long n;
2044
2045                 string::size_type colon, equal;
2046                 string remaining = prop->value();
2047
2048                 while (remaining.length()) {
2049
2050                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2051                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2052                                         << endmsg;
2053                         } else {
2054                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
2055                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2056                                                 << endmsg;
2057                                 } else {
2058                                         set_order_key (remaining.substr (0, equal), n);
2059                                 }
2060                         }
2061
2062                         colon = remaining.find_first_of (':');
2063
2064                         if (colon != string::npos) {
2065                                 remaining = remaining.substr (colon+1);
2066                         } else {
2067                                 break;
2068                         }
2069                 }
2070         }
2071
2072         /* add standard processors */
2073
2074         //_meter.reset (new PeakMeter (_session));
2075         //add_processor (_meter, PreFader);
2076
2077         if (is_monitor()) {
2078                 /* where we listen to tracks */
2079                 _intreturn.reset (new InternalReturn (_session));
2080                 add_processor (_intreturn, PreFader);
2081
2082                 _monitor_control.reset (new MonitorProcessor (_session));
2083                 add_processor (_monitor_control, PostFader);
2084         }
2085
2086         _main_outs.reset (new Delivery (_session, _output, _mute_master, _name, Delivery::Main));
2087         add_processor (_main_outs, PostFader);
2088
2089         /* IOs */
2090
2091         nlist = node.children ();
2092         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2093
2094                 child = *niter;
2095
2096                 if (child->name() == IO::state_node_name) {
2097
2098                         /* there is a note in IO::set_state_2X() about why we have to call
2099                            this directly.
2100                            */
2101
2102                         _input->set_state_2X (*child, version, true);
2103                         _output->set_state_2X (*child, version, false);
2104
2105                         if ((prop = child->property (X_("name"))) != 0) {
2106                                 Route::set_name (prop->value ());
2107                         }
2108
2109                         if ((prop = child->property (X_("id"))) != 0) {
2110                                 _id = prop->value ();
2111                         }
2112
2113                         if ((prop = child->property (X_("active"))) != 0) {
2114                                 bool yn = string_is_affirmative (prop->value());
2115                                 _active = !yn; // force switch
2116                                 set_active (yn);
2117                         }
2118                         
2119                         if ((prop = child->property (X_("gain"))) != 0) {
2120                                 gain_t val;
2121
2122                                 if (sscanf (prop->value().c_str(), "%f", &val) == 1) {
2123                                         _amp->gain_control()->set_value (val);
2124                                 }
2125                         }
2126                         
2127                         /* Set up Panners in the IO */
2128                         XMLNodeList io_nlist = child->children ();
2129                         
2130                         XMLNodeConstIterator io_niter;
2131                         XMLNode *io_child;
2132                         
2133                         for (io_niter = io_nlist.begin(); io_niter != io_nlist.end(); ++io_niter) {
2134
2135                                 io_child = *io_niter;
2136                                 
2137                                 if (io_child->name() == X_("Panner")) {
2138                                         _main_outs->panner()->set_state(*io_child, version);
2139                                 }
2140                         }
2141                 }
2142         }
2143
2144         XMLNodeList redirect_nodes;
2145
2146         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2147
2148                 child = *niter;
2149
2150                 if (child->name() == X_("Send") || child->name() == X_("Insert")) {
2151                         redirect_nodes.push_back(child);
2152                 }
2153
2154         }
2155
2156         set_processor_state_2X (redirect_nodes, version);
2157
2158         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2159                 child = *niter;
2160
2161                 if (child->name() == X_("Comment")) {
2162
2163                         /* XXX this is a terrible API design in libxml++ */
2164
2165                         XMLNode *cmt = *(child->children().begin());
2166                         _comment = cmt->content();
2167
2168                 } else if (child->name() == X_("Extra")) {
2169
2170                         _extra_xml = new XMLNode (*child);
2171
2172                 } else if (child->name() == X_("Controllable") && (prop = child->property("name")) != 0) {
2173
2174                         if (prop->value() == "solo") {
2175                                 _solo_control->set_state (*child, version);
2176                                 _session.add_controllable (_solo_control);
2177                         }
2178
2179                 } else if (child->name() == X_("RemoteControl")) {
2180                         if ((prop = child->property (X_("id"))) != 0) {
2181                                 int32_t x;
2182                                 sscanf (prop->value().c_str(), "%d", &x);
2183                                 set_remote_control_id (x);
2184                         }
2185
2186                 } 
2187         }
2188
2189         return 0;
2190 }
2191
2192 XMLNode&
2193 Route::get_processor_state ()
2194 {
2195         XMLNode* root = new XMLNode (X_("redirects"));
2196         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2197                 root->add_child_nocopy ((*i)->state (true));
2198         }
2199
2200         return *root;
2201 }
2202
2203 void
2204 Route::set_processor_state_2X (XMLNodeList const & nList, int version)
2205 {
2206         /* We don't bother removing existing processors not in nList, as this
2207            method will only be called when creating a Route from scratch, not
2208            for undo purposes.  Just put processors in at the appropriate place
2209            in the list.
2210         */
2211
2212         for (XMLNodeConstIterator i = nList.begin(); i != nList.end(); ++i) {
2213                 add_processor_from_xml_2X (**i, version, _processors.begin ());
2214         }
2215 }
2216
2217 void
2218 Route::set_processor_state (const XMLNode& node)
2219 {
2220         const XMLNodeList &nlist = node.children();
2221         XMLNodeConstIterator niter;
2222         ProcessorList new_order;
2223         bool must_configure = false;
2224
2225         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2226
2227                 XMLProperty* prop = (*niter)->property ("type");
2228
2229                 if (prop->value() == "amp") {
2230                         _amp->set_state (**niter, Stateful::current_state_version);
2231                         new_order.push_back (_amp);
2232                 } else if (prop->value() == "meter") {
2233                         _meter->set_state (**niter, Stateful::current_state_version);
2234                         new_order.push_back (_meter);
2235                 } else if (prop->value() == "main-outs") {
2236                         _main_outs->set_state (**niter, Stateful::current_state_version);
2237                         new_order.push_back (_main_outs);
2238                 } else if (prop->value() == "intreturn") {
2239                         if (!_intreturn) {
2240                                 _intreturn.reset (new InternalReturn (_session));
2241                                 must_configure = true;
2242                         }
2243                         _intreturn->set_state (**niter, Stateful::current_state_version);
2244                         new_order.push_back (_intreturn);
2245                 } else if (is_monitor() && prop->value() == "monitor") {
2246                         if (!_monitor_control) {
2247                                 _monitor_control.reset (new MonitorProcessor (_session));
2248                                 must_configure = true;
2249                         }
2250                         _monitor_control->set_state (**niter, Stateful::current_state_version);
2251                         new_order.push_back (_monitor_control);
2252                 } else {
2253                         ProcessorList::iterator o;
2254
2255                         for (o = _processors.begin(); o != _processors.end(); ++o) {
2256                                 XMLProperty* id_prop = (*niter)->property(X_("id"));
2257                                 if (id_prop && (*o)->id() == id_prop->value()) {
2258                                         (*o)->set_state (**niter, Stateful::current_state_version);
2259                                         new_order.push_back (*o);
2260                                         break;
2261                                 }
2262                         }
2263
2264                         // If the processor (*niter) is not on the route then create it 
2265                         
2266                         if (o == _processors.end()) {
2267                                 
2268                                 boost::shared_ptr<Processor> processor;
2269
2270                                 if (prop->value() == "intsend") {
2271                                         
2272                                         processor.reset (new InternalSend (_session, _mute_master, boost::shared_ptr<Route>(), Delivery::Role (0)));
2273                                         
2274                                 } else if (prop->value() == "ladspa" || prop->value() == "Ladspa" ||
2275                                            prop->value() == "lv2" ||
2276                                            prop->value() == "vst" ||
2277                                            prop->value() == "audiounit") {
2278                                         
2279                                         processor.reset (new PluginInsert(_session));
2280                                         
2281                                 } else if (prop->value() == "port") {
2282                                         
2283                                         processor.reset (new PortInsert (_session, _mute_master));
2284                                         
2285                                 } else if (prop->value() == "send") {
2286                                         
2287                                         processor.reset (new Send (_session, _mute_master));
2288                                         
2289                                 } else {
2290                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
2291                                         continue;
2292                                 }
2293
2294                                 processor->set_state (**niter, Stateful::current_state_version);
2295                                 new_order.push_back (processor);
2296                                 must_configure = true;
2297                         }
2298                 }
2299         }
2300
2301         { 
2302                 Glib::RWLock::WriterLock lm (_processor_lock);
2303                 _processors = new_order;
2304                 if (must_configure) {
2305                         configure_processors_unlocked (0);
2306                 }
2307         }
2308
2309         processors_changed (RouteProcessorChange ());
2310 }
2311
2312 void
2313 Route::curve_reallocate ()
2314 {
2315 //      _gain_automation_curve.finish_resize ();
2316 //      _pan_automation_curve.finish_resize ();
2317 }
2318
2319 void
2320 Route::silence (nframes_t nframes)
2321 {
2322         if (!_silent) {
2323
2324                 _output->silence (nframes);
2325
2326                 {
2327                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2328
2329                         if (lm.locked()) {
2330                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2331                                         boost::shared_ptr<PluginInsert> pi;
2332
2333                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2334                                                 // skip plugins, they don't need anything when we're not active
2335                                                 continue;
2336                                         }
2337
2338                                         (*i)->silence (nframes);
2339                                 }
2340
2341                                 if (nframes == _session.get_block_size()) {
2342                                         // _silent = true;
2343                                 }
2344                         }
2345                 }
2346
2347         }
2348 }
2349
2350 void
2351 Route::add_internal_return ()
2352 {
2353         if (!_intreturn) {
2354                 _intreturn.reset (new InternalReturn (_session));
2355                 add_processor (_intreturn, PreFader);
2356         }
2357 }
2358
2359 BufferSet*
2360 Route::get_return_buffer () const
2361 {
2362         Glib::RWLock::ReaderLock rm (_processor_lock);
2363
2364         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2365                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2366
2367                 if (d) {
2368                         BufferSet* bs = d->get_buffers ();
2369                         return bs;
2370                 }
2371         }
2372
2373         return 0;
2374 }
2375
2376 void
2377 Route::release_return_buffer () const
2378 {
2379         Glib::RWLock::ReaderLock rm (_processor_lock);
2380
2381         for (ProcessorList::const_iterator x = _processors.begin(); x != _processors.end(); ++x) {
2382                 boost::shared_ptr<InternalReturn> d = boost::dynamic_pointer_cast<InternalReturn>(*x);
2383
2384                 if (d) {
2385                         return d->release_buffers ();
2386                 }
2387         }
2388 }
2389
2390 int
2391 Route::listen_via (boost::shared_ptr<Route> route, Placement placement, bool /*active*/, bool aux)
2392 {
2393         vector<string> ports;
2394         vector<string>::const_iterator i;
2395
2396         {
2397                 Glib::RWLock::ReaderLock rm (_processor_lock);
2398
2399                 for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ++x) {
2400
2401                         boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2402
2403                         if (d && d->target_route() == route) {
2404
2405                                 /* if the target is the control outs, then make sure
2406                                    we take note of which i-send is doing that.
2407                                 */
2408
2409                                 if (route == _session.monitor_out()) {
2410                                         _monitor_send = boost::dynamic_pointer_cast<Delivery>(d);
2411                                 }
2412
2413                                 /* already listening via the specified IO: do nothing */
2414
2415                                 return 0;
2416                         }
2417                 }
2418         }
2419
2420         boost::shared_ptr<InternalSend> listener;
2421
2422         try {
2423
2424                 if (is_master()) {
2425                         
2426                         if (route == _session.monitor_out()) {
2427                                 /* master never sends to control outs */
2428                                 return 0;
2429                         } else {
2430                                 listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2431                         }
2432
2433                 } else {
2434                         listener.reset (new InternalSend (_session, _mute_master, route, (aux ? Delivery::Aux : Delivery::Listen)));
2435                 }
2436
2437         } catch (failed_constructor& err) {
2438                 return -1;
2439         }
2440
2441         if (route == _session.monitor_out()) {
2442                 _monitor_send = listener;
2443         }
2444
2445         if (placement == PostFader) {
2446                 /* put it *really* at the end, not just after the panner (main outs)
2447                  */
2448                 add_processor (listener, _processors.end());
2449         } else {
2450                 add_processor (listener, PreFader);
2451         }
2452
2453         return 0;
2454 }
2455
2456 void
2457 Route::drop_listen (boost::shared_ptr<Route> route)
2458 {
2459         ProcessorStreams err;
2460         ProcessorList::iterator tmp;
2461
2462         Glib::RWLock::ReaderLock rl(_processor_lock);
2463         rl.acquire ();
2464
2465   again:
2466         for (ProcessorList::iterator x = _processors.begin(); x != _processors.end(); ) {
2467
2468                 boost::shared_ptr<InternalSend> d = boost::dynamic_pointer_cast<InternalSend>(*x);
2469
2470                 if (d && d->target_route() == route) {
2471                         rl.release ();
2472                         remove_processor (*x, &err);
2473                         rl.acquire ();
2474
2475                         /* list could have been demolished while we dropped the lock
2476                            so start over.
2477                         */
2478
2479                         goto again;
2480                 }
2481         }
2482
2483         rl.release ();
2484
2485         if (route == _session.monitor_out()) {
2486                 _monitor_send.reset ();
2487         }
2488 }
2489
2490 void
2491 Route::set_comment (string cmt, void *src)
2492 {
2493         _comment = cmt;
2494         comment_changed (src);
2495         _session.set_dirty ();
2496 }
2497
2498 bool
2499 Route::add_fed_by (boost::shared_ptr<Route> other, bool via_sends_only)
2500 {
2501         FeedRecord fr (other, via_sends_only);
2502
2503         pair<FedBy::iterator,bool> result =  _fed_by.insert (fr);
2504
2505         if (!result.second) {
2506
2507                 /* already a record for "other" - make sure sends-only information is correct */
2508                 if (!via_sends_only && result.first->sends_only) {
2509                         FeedRecord* frp = const_cast<FeedRecord*>(&(*result.first));
2510                         frp->sends_only = false;
2511                 }
2512         }
2513         
2514         return result.second;
2515 }
2516
2517 void
2518 Route::clear_fed_by ()
2519 {
2520         _fed_by.clear ();
2521 }
2522
2523 bool
2524 Route::feeds (boost::shared_ptr<Route> other, bool* via_sends_only)
2525 {
2526         const FedBy& fed_by (other->fed_by());
2527
2528         for (FedBy::iterator f = fed_by.begin(); f != fed_by.end(); ++f) {
2529                 boost::shared_ptr<Route> sr = f->r.lock();
2530
2531                 if (sr && (sr.get() == this)) {
2532
2533                         if (via_sends_only) {
2534                                 *via_sends_only = f->sends_only;
2535                         }
2536
2537                         return true;
2538                 }
2539         }
2540
2541         return false;
2542 }
2543
2544 bool
2545 Route::direct_feeds (boost::shared_ptr<Route> other, bool* only_send)
2546 {
2547         DEBUG_TRACE (DEBUG::Graph, string_compose ("Feeds? %1\n", _name));
2548
2549         if (_output->connected_to (other->input())) {
2550                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\tdirect FEEDS %2\n", other->name()));
2551                 if (only_send) {
2552                         *only_send = false;
2553                 }
2554
2555                 return true;
2556         }
2557
2558         
2559         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); ++r) {
2560
2561                 boost::shared_ptr<IOProcessor> iop;
2562
2563                 if ((iop = boost::dynamic_pointer_cast<IOProcessor>(*r)) != 0) {
2564                         if (iop->feeds (other)) {
2565                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does feed %2\n", iop->name(), other->name()));
2566                                 if (only_send) {
2567                                         *only_send = true;
2568                                 }
2569                                 return true;
2570                         } else {
2571                                 DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tIOP %1 does NOT feed %2\n", iop->name(), other->name()));
2572                         }
2573                 } else {
2574                         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tPROC %1 is not an IOP\n", (*r)->name()));
2575                 }
2576                         
2577         }
2578
2579         DEBUG_TRACE (DEBUG::Graph,  string_compose ("\tdoes NOT feed %1\n", other->name()));
2580         return false;
2581 }
2582
2583 void
2584 Route::check_physical_connections ()
2585 {
2586         _physically_connected = _output->physically_connected ();
2587 }
2588
2589 void
2590 Route::handle_transport_stopped (bool /*abort_ignored*/, bool did_locate, bool can_flush_processors)
2591 {
2592         nframes_t now = _session.transport_frame();
2593
2594         {
2595                 Glib::RWLock::ReaderLock lm (_processor_lock);
2596
2597                 if (!did_locate) {
2598                         automation_snapshot (now, true);
2599                 }
2600
2601                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2602
2603                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2604                                 (*i)->deactivate ();
2605                                 (*i)->activate ();
2606                         }
2607
2608                         (*i)->transport_stopped (now);
2609                 }
2610         }
2611
2612         _roll_delay = _initial_delay;
2613 }
2614
2615 void
2616 Route::input_change_handler (IOChange change, void * /*src*/)
2617 {
2618         if ((change & ConfigurationChanged)) {
2619                 configure_processors (0);
2620         }
2621 }
2622
2623 void
2624 Route::output_change_handler (IOChange change, void * /*src*/)
2625 {
2626         if ((change & ConfigurationChanged)) {
2627
2628                 /* XXX resize all listeners to match _main_outs? */
2629
2630                 // configure_processors (0);
2631         }
2632 }
2633
2634 uint32_t
2635 Route::pans_required () const
2636 {
2637         if (n_outputs().n_audio() < 2) {
2638                 return 0;
2639         }
2640
2641         return max (n_inputs ().n_audio(), processor_max_streams.n_audio());
2642 }
2643
2644 int
2645 Route::no_roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame,
2646                 bool session_state_changing, bool /*can_record*/, bool /*rec_monitors_input*/)
2647 {
2648         if (n_outputs().n_total() == 0) {
2649                 return 0;
2650         }
2651
2652         if (!_active || n_inputs() == ChanCount::ZERO)  {
2653                 silence (nframes);
2654                 return 0;
2655         }
2656         if (session_state_changing) {
2657                 if (_session.transport_speed() != 0.0f) {
2658                         /* we're rolling but some state is changing (e.g. our diskstream contents)
2659                            so we cannot use them. Be silent till this is over.
2660                            
2661                            XXX note the absurdity of ::no_roll() being called when we ARE rolling!
2662                         */
2663                         silence (nframes);
2664                         return 0;
2665                 }
2666                 /* we're really not rolling, so we're either delivery silence or actually
2667                    monitoring, both of which are safe to do while session_state_changing is true.
2668                 */
2669         }
2670
2671         _amp->apply_gain_automation (false);
2672         passthru (start_frame, end_frame, nframes, 0);
2673
2674         return 0;
2675 }
2676
2677 nframes_t
2678 Route::check_initial_delay (nframes_t nframes, nframes_t& transport_frame)
2679 {
2680         if (_roll_delay > nframes) {
2681
2682                 _roll_delay -= nframes;
2683                 silence (nframes);
2684                 /* transport frame is not legal for caller to use */
2685                 return 0;
2686
2687         } else if (_roll_delay > 0) {
2688
2689                 nframes -= _roll_delay;
2690                 silence (_roll_delay);
2691                 /* we've written _roll_delay of samples into the
2692                    output ports, so make a note of that for
2693                    future reference.
2694                 */
2695                 _main_outs->increment_output_offset (_roll_delay);
2696                 transport_frame += _roll_delay;
2697
2698                 _roll_delay = 0;
2699         }
2700
2701         return nframes;
2702 }
2703
2704 int
2705 Route::roll (nframes_t nframes, sframes_t start_frame, sframes_t end_frame, int declick,
2706              bool /*can_record*/, bool /*rec_monitors_input*/, bool& /* need_butler */)
2707 {
2708         {
2709                 // automation snapshot can also be called from the non-rt context
2710                 // and it uses the processor list, so we try to acquire the lock here
2711                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2712
2713                 if (lm.locked()) {
2714                         automation_snapshot (_session.transport_frame(), false);
2715                 }
2716         }
2717
2718         if (n_outputs().n_total() == 0) {
2719                 return 0;
2720         }
2721
2722         if (!_active || n_inputs().n_total() == 0) {
2723                 silence (nframes);
2724                 return 0;
2725         }
2726
2727         nframes_t unused = 0;
2728
2729         if ((nframes = check_initial_delay (nframes, unused)) == 0) {
2730                 return 0;
2731         }
2732
2733         _silent = false;
2734
2735         passthru (start_frame, end_frame, nframes, declick);
2736
2737         return 0;
2738 }
2739
2740 int
2741 Route::silent_roll (nframes_t nframes, sframes_t /*start_frame*/, sframes_t /*end_frame*/,
2742                     bool /*can_record*/, bool /*rec_monitors_input*/, bool& /* need_butler */)
2743 {
2744         silence (nframes);
2745         return 0;
2746 }
2747
2748 void
2749 Route::toggle_monitor_input ()
2750 {
2751         for (PortSet::iterator i = _input->ports().begin(); i != _input->ports().end(); ++i) {
2752                 i->ensure_monitor_input( ! i->monitoring_input());
2753         }
2754 }
2755
2756 bool
2757 Route::has_external_redirects () const
2758 {
2759         // FIXME: what about sends? - they don't return a signal back to ardour?
2760
2761         boost::shared_ptr<const PortInsert> pi;
2762
2763         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2764
2765                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2766
2767                         for (PortSet::const_iterator port = pi->output()->ports().begin(); port != pi->output()->ports().end(); ++port) {
2768
2769                                 string port_name = port->name();
2770                                 string client_name = port_name.substr (0, port_name.find(':'));
2771
2772                                 /* only say "yes" if the redirect is actually in use */
2773
2774                                 if (client_name != "ardour" && pi->active()) {
2775                                         return true;
2776                                 }
2777                         }
2778                 }
2779         }
2780
2781         return false;
2782 }
2783
2784 void
2785 Route::flush_processors ()
2786 {
2787         /* XXX shouldn't really try to take this lock, since
2788            this is called from the RT audio thread.
2789         */
2790
2791         Glib::RWLock::ReaderLock lm (_processor_lock);
2792
2793         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2794                 (*i)->deactivate ();
2795                 (*i)->activate ();
2796         }
2797 }
2798
2799 void
2800 Route::set_meter_point (MeterPoint p)
2801 {
2802         /* CAN BE CALLED FROM PROCESS CONTEXT */
2803
2804         if (_meter_point == p) {
2805                 return;
2806         }
2807
2808         bool meter_was_visible_to_user = _meter->display_to_user ();
2809
2810         {
2811                 Glib::RWLock::WriterLock lm (_processor_lock);
2812         
2813                 if (p != MeterCustom) {
2814                         // Move meter in the processors list to reflect the new position
2815                         ProcessorList::iterator loc = find (_processors.begin(), _processors.end(), _meter);
2816                         _processors.erase(loc);
2817                         switch (p) {
2818                         case MeterInput:
2819                                 loc = _processors.begin();
2820                                 break;
2821                         case MeterPreFader:
2822                                 loc = find (_processors.begin(), _processors.end(), _amp);
2823                                 break;
2824                         case MeterPostFader:
2825                                 loc = _processors.end();
2826                                 break;
2827                         default:
2828                                 break;
2829                         }
2830                         
2831                         ChanCount m_in;
2832                         
2833                         if (loc == _processors.begin()) {
2834                                 m_in = _input->n_ports();
2835                         } else {
2836                                 ProcessorList::iterator before = loc;
2837                                 --before;
2838                                 m_in = (*before)->output_streams ();
2839                         }
2840                         
2841                         _meter->reflect_inputs (m_in);
2842                         
2843                         _processors.insert (loc, _meter);
2844                         
2845                         /* we do not need to reconfigure the processors, because the meter
2846                            (a) is always ready to handle processor_max_streams
2847                            (b) is always an N-in/N-out processor, and thus moving
2848                            it doesn't require any changes to the other processors.
2849                         */
2850                         
2851                         _meter->set_display_to_user (false);
2852                         
2853                 } else {
2854                         
2855                         // just make it visible and let the user move it
2856                         
2857                         _meter->set_display_to_user (true);
2858                 }
2859         }
2860
2861         _meter_point = p;
2862         meter_change (); /* EMIT SIGNAL */
2863
2864         bool const meter_visibly_changed = (_meter->display_to_user() != meter_was_visible_to_user);
2865         
2866         processors_changed (RouteProcessorChange (RouteProcessorChange::MeterPointChange, meter_visibly_changed)); /* EMIT SIGNAL */
2867 }
2868
2869 void
2870 Route::put_monitor_send_at (Placement p)
2871 {
2872         if (!_monitor_send) {
2873                 return;
2874         }
2875
2876         {
2877                 Glib::RWLock::WriterLock lm (_processor_lock);
2878                 ProcessorList as_it_was (_processors);
2879                 ProcessorList::iterator loc = find(_processors.begin(), _processors.end(), _monitor_send);
2880                 _processors.erase(loc);
2881                 
2882                 switch (p) {
2883                 case PreFader:
2884                         loc = find(_processors.begin(), _processors.end(), _amp);
2885                         if (loc != _processors.begin()) {
2886                                 --loc;
2887                         }
2888                         break;
2889                 case PostFader:
2890                         loc = _processors.end();
2891                         break;
2892                 }
2893                 
2894                 _processors.insert (loc, _monitor_send);
2895
2896                 if (configure_processors_unlocked (0)) {
2897                         _processors = as_it_was;
2898                         configure_processors_unlocked (0); // it worked before we tried to add it ...
2899                         return;
2900                 }
2901         }
2902
2903         processors_changed (RouteProcessorChange ()); /* EMIT SIGNAL */
2904         _session.set_dirty ();
2905 }
2906
2907 nframes_t
2908 Route::update_total_latency ()
2909 {
2910         nframes_t old = _output->effective_latency();
2911         nframes_t own_latency = _output->user_latency();
2912
2913         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2914                 if ((*i)->active ()) {
2915                         own_latency += (*i)->signal_latency ();
2916                 }
2917         }
2918
2919         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: internal redirect latency = %2\n", _name, own_latency));
2920
2921         _output->set_port_latency (own_latency);
2922
2923         if (_output->user_latency() == 0) {
2924
2925                 /* this (virtual) function is used for pure Routes,
2926                    not derived classes like AudioTrack.  this means
2927                    that the data processed here comes from an input
2928                    port, not prerecorded material, and therefore we
2929                    have to take into account any input latency.
2930                 */
2931
2932                 own_latency += _input->signal_latency ();
2933         }
2934
2935         if (old != own_latency) {
2936                 _output->set_latency_delay (own_latency);
2937                 signal_latency_changed (); /* EMIT SIGNAL */
2938         }
2939
2940         DEBUG_TRACE (DEBUG::Latency, string_compose ("%1: input latency = %2 total = %3\n", _name, _input->signal_latency(), own_latency));
2941
2942         return _output->effective_latency ();
2943 }
2944
2945 void
2946 Route::set_user_latency (nframes_t nframes)
2947 {
2948         _output->set_user_latency (nframes);
2949         _session.update_latency_compensation (false, false);
2950 }
2951
2952 void
2953 Route::set_latency_delay (nframes_t longest_session_latency)
2954 {
2955         nframes_t old = _initial_delay;
2956
2957         if (_output->effective_latency() < longest_session_latency) {
2958                 _initial_delay = longest_session_latency - _output->effective_latency();
2959         } else {
2960                 _initial_delay = 0;
2961         }
2962
2963         if (_initial_delay != old) {
2964                 initial_delay_changed (); /* EMIT SIGNAL */
2965         }
2966
2967         if (_session.transport_stopped()) {
2968                 _roll_delay = _initial_delay;
2969         }
2970 }
2971
2972 void
2973 Route::automation_snapshot (nframes_t now, bool force)
2974 {
2975         panner()->automation_snapshot (now, force);
2976         
2977         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2978                 (*i)->automation_snapshot (now, force);
2979         }
2980 }
2981
2982 Route::SoloControllable::SoloControllable (std::string name, Route& r)
2983         : AutomationControl (r.session(), Evoral::Parameter (SoloAutomation),
2984                              boost::shared_ptr<AutomationList>(), name)
2985         , route (r)
2986 {
2987         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(SoloAutomation)));
2988         set_list (gl);
2989 }
2990
2991 void
2992 Route::SoloControllable::set_value (float val)
2993 {
2994         bool bval = ((val >= 0.5f) ? true: false);
2995 # if 0
2996         this is how it should be done 
2997
2998         boost::shared_ptr<RouteList> rl (new RouteList);
2999         rl->push_back (route);
3000
3001         if (Config->get_solo_control_is_listen_control()) {
3002                 _session.set_listen (rl, bval);
3003         } else {
3004                 _session.set_solo (rl, bval);
3005         }
3006 #else
3007         route.set_solo (bval, this);
3008 #endif
3009 }
3010
3011 float
3012 Route::SoloControllable::get_value (void) const
3013 {
3014         if (Config->get_solo_control_is_listen_control()) {
3015                 return route.listening() ? 1.0f : 0.0f;
3016         } else {
3017                 return route.self_soloed() ? 1.0f : 0.0f;
3018         }
3019 }
3020
3021 Route::MuteControllable::MuteControllable (std::string name, Route& r)
3022         : AutomationControl (r.session(), Evoral::Parameter (MuteAutomation),
3023                              boost::shared_ptr<AutomationList>(), name)
3024         , route (r)
3025 {
3026         boost::shared_ptr<AutomationList> gl(new AutomationList(Evoral::Parameter(MuteAutomation)));
3027         set_list (gl);
3028 }
3029
3030 void
3031 Route::MuteControllable::set_value (float val)
3032 {
3033         bool bval = ((val >= 0.5f) ? true: false);
3034 # if 0
3035         this is how it should be done 
3036
3037         boost::shared_ptr<RouteList> rl (new RouteList);
3038         rl->push_back (route);
3039         _session.set_mute (rl, bval);
3040 #else
3041         route.set_mute (bval, this);
3042 #endif
3043 }
3044
3045 float
3046 Route::MuteControllable::get_value (void) const
3047 {
3048         return route.muted() ? 1.0f : 0.0f;
3049 }
3050
3051 void
3052 Route::set_block_size (nframes_t nframes)
3053 {
3054         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3055                 (*i)->set_block_size (nframes);
3056         }
3057         
3058         _session.ensure_buffers (n_process_buffers ());
3059 }
3060
3061 void
3062 Route::protect_automation ()
3063 {
3064         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
3065                 (*i)->protect_automation();
3066 }
3067
3068 void
3069 Route::set_pending_declick (int declick)
3070 {
3071         if (_declickable) {
3072                 /* this call is not allowed to turn off a pending declick unless "force" is true */
3073                 if (declick) {
3074                         _pending_declick = declick;
3075                 }
3076                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
3077         } else {
3078                 _pending_declick = 0;
3079         }
3080
3081 }
3082
3083 /** Shift automation forwards from a particular place, thereby inserting time.
3084  *  Adds undo commands for any shifts that are performed.
3085  *
3086  * @param pos Position to start shifting from.
3087  * @param frames Amount to shift forwards by.
3088  */
3089
3090 void
3091 Route::shift (nframes64_t /*pos*/, nframes64_t /*frames*/)
3092 {
3093 #ifdef THIS_NEEDS_FIXING_FOR_V3
3094
3095         /* gain automation */
3096         XMLNode &before = _gain_control->get_state ();
3097         _gain_control->shift (pos, frames);
3098         XMLNode &after = _gain_control->get_state ();
3099         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
3100
3101         /* pan automation */
3102         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
3103                 Curve & c = (*i)->automation ();
3104                 XMLNode &before = c.get_state ();
3105                 c.shift (pos, frames);
3106                 XMLNode &after = c.get_state ();
3107                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
3108         }
3109
3110         /* redirect automation */
3111         {
3112                 Glib::RWLock::ReaderLock lm (redirect_lock);
3113                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
3114
3115                         set<uint32_t> a;
3116                         (*i)->what_has_automation (a);
3117
3118                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
3119                                 AutomationList & al = (*i)->automation_list (*j);
3120                                 XMLNode &before = al.get_state ();
3121                                 al.shift (pos, frames);
3122                                 XMLNode &after = al.get_state ();
3123                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
3124                         }
3125                 }
3126         }
3127 #endif
3128
3129 }
3130
3131
3132 int
3133 Route::save_as_template (const string& path, const string& name)
3134 {
3135         XMLNode& node (state (false));
3136         XMLTree tree;
3137
3138         IO::set_name_in_state (*node.children().front(), name);
3139
3140         tree.set_root (&node);
3141         return tree.write (path.c_str());
3142 }
3143
3144
3145 bool
3146 Route::set_name (const string& str)
3147 {
3148         bool ret;
3149         string ioproc_name;
3150         string name;
3151
3152         name = Route::ensure_track_or_route_name (str, _session);
3153         SessionObject::set_name (name);
3154
3155         ret = (_input->set_name(name) && _output->set_name(name));
3156
3157         if (ret) {
3158
3159                 Glib::RWLock::ReaderLock lm (_processor_lock);
3160
3161                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3162
3163                         /* rename all I/O processors that have inputs or outputs */
3164
3165                         boost::shared_ptr<IOProcessor> iop = boost::dynamic_pointer_cast<IOProcessor> (*i);
3166
3167                         if (iop && (iop->output() || iop->input())) {
3168                                 if (!iop->set_name (name)) {
3169                                         ret = false;
3170                                 }
3171                         }
3172                 }
3173
3174         }
3175
3176         return ret;
3177 }
3178
3179 boost::shared_ptr<Send>
3180 Route::internal_send_for (boost::shared_ptr<const Route> target) const
3181 {
3182         Glib::RWLock::ReaderLock lm (_processor_lock);
3183
3184         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
3185                 boost::shared_ptr<InternalSend> send;
3186
3187                 if ((send = boost::dynamic_pointer_cast<InternalSend>(*i)) != 0) {
3188                         if (send->target_route() == target) {
3189                                 return send;
3190                         }
3191                 }
3192         }
3193
3194         return boost::shared_ptr<Send>();
3195 }
3196
3197 void
3198 Route::set_phase_invert (bool yn)
3199 {
3200         if (_phase_invert != yn) {
3201                 if (yn) {
3202                         _phase_invert = 0xffff; // XXX all channels
3203                 } else {
3204                         _phase_invert = 0; // XXX no channels
3205                 }
3206
3207                 phase_invert_changed (); /* EMIT SIGNAL */
3208                 _session.set_dirty ();
3209         }
3210 }
3211
3212 bool
3213 Route::phase_invert () const
3214 {
3215         return _phase_invert != 0;
3216 }
3217
3218 void
3219 Route::set_denormal_protection (bool yn)
3220 {
3221         if (_denormal_protection != yn) {
3222                 _denormal_protection = yn;
3223                 denormal_protection_changed (); /* EMIT SIGNAL */
3224         }
3225 }
3226
3227 bool
3228 Route::denormal_protection () const
3229 {
3230         return _denormal_protection;
3231 }
3232
3233 void
3234 Route::set_active (bool yn)
3235 {
3236         if (_active != yn) {
3237                 _active = yn;
3238                 _input->set_active (yn);
3239                 _output->set_active (yn);
3240                 active_changed (); // EMIT SIGNAL
3241         }
3242 }
3243
3244 void
3245 Route::meter ()
3246 {
3247         Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3248
3249         assert (_meter);
3250
3251         _meter->meter ();
3252
3253         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3254
3255                 boost::shared_ptr<Send> s;
3256                 boost::shared_ptr<Return> r;
3257
3258                 if ((s = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
3259                         s->meter()->meter();
3260                 } else if ((r = boost::dynamic_pointer_cast<Return> (*i)) != 0) {
3261                         r->meter()->meter ();
3262                 }
3263         }
3264 }
3265
3266 boost::shared_ptr<Panner>
3267 Route::panner() const
3268 {
3269         return _main_outs->panner();
3270 }
3271
3272 boost::shared_ptr<AutomationControl>
3273 Route::gain_control() const
3274 {
3275         return _amp->gain_control();
3276 }
3277
3278 boost::shared_ptr<AutomationControl>
3279 Route::get_control (const Evoral::Parameter& param)
3280 {
3281         /* either we own the control or .... */
3282
3283         boost::shared_ptr<AutomationControl> c = boost::dynamic_pointer_cast<AutomationControl>(control (param));
3284
3285         if (!c) {
3286
3287                 /* maybe one of our processors does or ... */
3288
3289                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
3290                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3291                         if ((c = boost::dynamic_pointer_cast<AutomationControl>((*i)->control (param))) != 0) {
3292                                 break;
3293                         }
3294                 }
3295         }
3296
3297         if (!c) {
3298
3299                 /* nobody does so we'll make a new one */
3300
3301                 c = boost::dynamic_pointer_cast<AutomationControl>(control_factory(param));
3302                 add_control(c);
3303         }
3304
3305         return c;
3306 }
3307
3308 boost::shared_ptr<Processor>
3309 Route::nth_plugin (uint32_t n)
3310 {
3311         Glib::RWLock::ReaderLock lm (_processor_lock);
3312         ProcessorList::iterator i;
3313
3314         for (i = _processors.begin(); i != _processors.end(); ++i) {
3315                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
3316                         if (n-- == 0) {
3317                                 return *i;
3318                         }
3319                 }
3320         }
3321
3322         return boost::shared_ptr<Processor> ();
3323 }
3324
3325 boost::shared_ptr<Processor>
3326 Route::nth_send (uint32_t n)
3327 {
3328         Glib::RWLock::ReaderLock lm (_processor_lock);
3329         ProcessorList::iterator i;
3330
3331         for (i = _processors.begin(); i != _processors.end(); ++i) {
3332                 if (boost::dynamic_pointer_cast<Send> (*i)) {
3333                         if (n-- == 0) {
3334                                 return *i;
3335                         }
3336                 } 
3337         }
3338
3339         return boost::shared_ptr<Processor> ();
3340 }
3341
3342 bool
3343 Route::has_io_processor_named (const string& name)
3344 {
3345         Glib::RWLock::ReaderLock lm (_processor_lock);
3346         ProcessorList::iterator i;
3347         
3348         for (i = _processors.begin(); i != _processors.end(); ++i) {
3349                 if (boost::dynamic_pointer_cast<Send> (*i) ||
3350                     boost::dynamic_pointer_cast<PortInsert> (*i)) {
3351                         if ((*i)->name() == name) {
3352                                 return true;
3353                         }
3354                 }
3355         }
3356         
3357         return false;
3358 }
3359
3360 void
3361 Route::set_graph_level (int32_t l)
3362 {
3363         _graph_level = l;
3364 }