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