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