most of the 2.X->3.0 commit (up to rev 4299) except for gtk2_ardour/editor_canvas...
[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
24 #include <sigc++/bind.h>
25 #include <pbd/xml++.h>
26 #include <pbd/enumwriter.h>
27 #include <pbd/stacktrace.h>
28 #include <pbd/memento_command.h>
29
30 #include <ardour/timestamps.h>
31 #include <ardour/audioengine.h>
32 #include <ardour/route.h>
33 #include <ardour/buffer.h>
34 #include <ardour/processor.h>
35 #include <ardour/plugin_insert.h>
36 #include <ardour/port_insert.h>
37 #include <ardour/send.h>
38 #include <ardour/session.h>
39 #include <ardour/utils.h>
40 #include <ardour/configuration.h>
41 #include <ardour/cycle_timer.h>
42 #include <ardour/route_group.h>
43 #include <ardour/port.h>
44 #include <ardour/audio_port.h>
45 #include <ardour/ladspa_plugin.h>
46 #include <ardour/panner.h>
47 #include <ardour/dB.h>
48 #include <ardour/amp.h>
49 #include <ardour/meter.h>
50 #include <ardour/buffer_set.h>
51 #include <ardour/mix.h>
52 #include <ardour/profile.h>
53
54 #include "i18n.h"
55
56 using namespace std;
57 using namespace ARDOUR;
58 using namespace PBD;
59
60 uint32_t Route::order_key_cnt = 0;
61 sigc::signal<void,const char*> Route::SyncOrderKeys;
62
63 Route::Route (Session& sess, string name, int input_min, int input_max, int output_min, int output_max, Flag flg, DataType default_type)
64         : IO (sess, name, input_min, input_max, output_min, output_max, default_type),
65           _flags (flg),
66           _solo_control (new ToggleControllable (X_("solo"), *this, ToggleControllable::SoloControl)),
67           _mute_control (new ToggleControllable (X_("mute"), *this, ToggleControllable::MuteControl))
68 {
69         init ();
70 }
71
72 Route::Route (Session& sess, const XMLNode& node, DataType default_type)
73         : IO (sess, *node.child ("IO"), default_type),
74           _solo_control (new ToggleControllable (X_("solo"), *this, ToggleControllable::SoloControl)),
75           _mute_control (new ToggleControllable (X_("mute"), *this, ToggleControllable::MuteControl))
76 {
77         init ();
78         _set_state (node, false);
79 }
80
81 void
82 Route::init ()
83 {
84         processor_max_outs.reset();
85         _muted = false;
86         _soloed = false;
87         _solo_safe = false;
88         _recordable = true;
89         _active = true;
90         _phase_invert = false;
91         _denormal_protection = false;
92         order_keys[strdup (N_("signal"))] = order_key_cnt++;
93         _silent = false;
94         _meter_point = MeterPostFader;
95         _initial_delay = 0;
96         _roll_delay = 0;
97         _own_latency = 0;
98         _user_latency = 0;
99         _have_internal_generator = false;
100         _declickable = false;
101         _pending_declick = true;
102         _remote_control_id = 0;
103         
104         _edit_group = 0;
105         _mix_group = 0;
106
107         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
108         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
109         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
110         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
111         
112         solo_gain = 1.0;
113         desired_solo_gain = 1.0;
114         mute_gain = 1.0;
115         desired_mute_gain = 1.0;
116
117         _control_outs = 0;
118
119         input_changed.connect (mem_fun (this, &Route::input_change_handler));
120         output_changed.connect (mem_fun (this, &Route::output_change_handler));
121 }
122
123 Route::~Route ()
124 {
125         clear_processors (PreFader);
126         clear_processors (PostFader);
127
128         for (OrderKeys::iterator i = order_keys.begin(); i != order_keys.end(); ++i) {
129                 free ((void*)(i->first));
130         }
131
132         if (_control_outs) {
133                 delete _control_outs;
134         }
135 }
136
137 void
138 Route::set_remote_control_id (uint32_t id)
139 {
140         if (id != _remote_control_id) {
141                 _remote_control_id = id;
142                 RemoteControlIDChanged ();
143         }
144 }
145
146 uint32_t
147 Route::remote_control_id() const
148 {
149         return _remote_control_id;
150 }
151
152 long
153 Route::order_key (const char* name) const
154 {
155         OrderKeys::const_iterator i;
156         
157         for (i = order_keys.begin(); i != order_keys.end(); ++i) {
158                 if (!strcmp (name, i->first)) {
159                         return i->second;
160                 }
161         }
162
163         return -1;
164 }
165
166 void
167 Route::set_order_key (const char* name, long n)
168 {
169         order_keys[strdup(name)] = n;
170
171         if (Config->get_sync_all_route_ordering()) {
172                 for (OrderKeys::iterator x = order_keys.begin(); x != order_keys.end(); ++x) {
173                         x->second = n;
174                 }
175         } 
176
177         _session.set_dirty ();
178 }
179
180 void
181 Route::sync_order_keys (const char* base)
182 {
183         if (order_keys.empty()) {
184                 return;
185         }
186
187         OrderKeys::iterator i;
188         uint32_t key;
189
190         if ((i = order_keys.find (base)) == order_keys.end()) {
191                 /* key doesn't exist, use the first existing
192                    key (this is done during session initialization)
193                 */
194                 i = order_keys.begin();
195                 key = i->second;
196                 ++i;
197         } else {
198                 /* key exists - use it and reset all others
199                    (actually, itself included)
200                 */
201                 i = order_keys.begin();
202                 key = i->second;
203         }
204
205         for (; i != order_keys.end(); ++i) {
206                 i->second = key;
207         }
208 }
209
210 string
211 Route::ensure_track_or_route_name(string name, Session &session)
212 {
213         string newname = name;
214
215         while (session.route_by_name (newname)!=NULL)
216         {
217                 newname = bump_name_once (newname);
218         }
219
220         return newname;
221 }
222
223
224 void
225 Route::inc_gain (gain_t fraction, void *src)
226 {
227         IO::inc_gain (fraction, src);
228 }
229
230 void
231 Route::set_gain (gain_t val, void *src)
232 {
233         if (src != 0 && _mix_group && src != _mix_group && _mix_group->is_active()) {
234                 
235                 if (_mix_group->is_relative()) {
236                         
237                         gain_t usable_gain = gain();
238                         if (usable_gain < 0.000001f) {
239                                 usable_gain = 0.000001f;
240                         }
241                                                 
242                         gain_t delta = val;
243                         if (delta < 0.000001f) {
244                                 delta = 0.000001f;
245                         }
246
247                         delta -= usable_gain;
248
249                         if (delta == 0.0f)
250                                 return;
251
252                         gain_t factor = delta / usable_gain;
253
254                         if (factor > 0.0f) {
255                                 factor = _mix_group->get_max_factor(factor);
256                                 if (factor == 0.0f) {
257                                         _gain_control->Changed(); /* EMIT SIGNAL */
258                                         return;
259                                 }
260                         } else {
261                                 factor = _mix_group->get_min_factor(factor);
262                                 if (factor == 0.0f) {
263                                         _gain_control->Changed(); /* EMIT SIGNAL */
264                                         return;
265                                 }
266                         }
267                                         
268                         _mix_group->apply (&Route::inc_gain, factor, _mix_group);
269
270                 } else {
271                         
272                         _mix_group->apply (&Route::set_gain, val, _mix_group);
273                 }
274
275                 return;
276         } 
277
278         if (val == gain()) {
279                 return;
280         }
281
282         IO::set_gain (val, src);
283 }
284
285 /** Process this route for one (sub) cycle (process thread)
286  *
287  * @param bufs Scratch buffers to use for the signal path
288  * @param start_frame Initial transport frame 
289  * @param end_frame Final transport frame
290  * @param nframes Number of frames to output (to ports)
291  * @param offset Output offset (of port buffers, for split cycles)
292  *
293  * Note that (end_frame - start_frame) may not be equal to nframes when the
294  * transport speed isn't 1.0 (eg varispeed).
295  */
296 void
297 Route::process_output_buffers (BufferSet& bufs,
298                                nframes_t start_frame, nframes_t end_frame, 
299                                nframes_t nframes, nframes_t offset, bool with_processors, int declick,
300                                bool meter)
301 {
302         // This is definitely very audio-only for now
303         assert(_default_type == DataType::AUDIO);
304         
305         ProcessorList::iterator i;
306         bool post_fader_work = false;
307         bool mute_declick_applied = false;
308         gain_t dmg, dsg, dg;
309         IO *co;
310         bool mute_audible;
311         bool solo_audible;
312         bool no_monitor;
313         gain_t* gab = _session.gain_automation_buffer();
314
315         switch (Config->get_monitoring_model()) {
316         case HardwareMonitoring:
317         case ExternalMonitoring:
318                 no_monitor = true;
319                 break;
320         default:
321                 no_monitor = false;
322         }
323
324         declick = _pending_declick;
325
326         {
327                 Glib::Mutex::Lock cm (_control_outs_lock, Glib::TRY_LOCK);
328                 
329                 if (cm.locked()) {
330                         co = _control_outs;
331                 } else {
332                         co = 0;
333                 }
334         }
335         
336         { 
337                 Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
338                 
339                 if (dm.locked()) {
340                         dmg = desired_mute_gain;
341                         dsg = desired_solo_gain;
342                         dg = _desired_gain;
343                 } else {
344                         dmg = mute_gain;
345                         dsg = solo_gain;
346                         dg = _gain;
347                 }
348         }
349
350         /* ----------------------------------------------------------------------------------------------------
351            GLOBAL DECLICK (for transport changes etc.)
352            -------------------------------------------------------------------------------------------------- */
353
354         if (declick > 0) {
355                 Amp::run_in_place (bufs, nframes, 0.0, 1.0, false);
356                 _pending_declick = 0;
357         } else if (declick < 0) {
358                 Amp::run_in_place (bufs, nframes, 1.0, 0.0, false);
359                 _pending_declick = 0;
360         } else {
361
362                 /* no global declick */
363
364                 if (solo_gain != dsg) {
365                         Amp::run_in_place (bufs, nframes, solo_gain, dsg, false);
366                         solo_gain = dsg;
367                 }
368         }
369
370
371         /* ----------------------------------------------------------------------------------------------------
372            INPUT METERING & MONITORING
373            -------------------------------------------------------------------------------------------------- */
374
375         if (meter && (_meter_point == MeterInput)) {
376                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
377         }
378
379         if (!_soloed && _mute_affects_pre_fader && (mute_gain != dmg)) {
380                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
381                 mute_gain = dmg;
382                 mute_declick_applied = true;
383         }
384
385         if ((_meter_point == MeterInput) && co) {
386                 
387                 solo_audible = dsg > 0;
388                 mute_audible = dmg > 0;// || !_mute_affects_pre_fader;
389                 
390                 if (    // muted by solo of another track
391                         
392                         !solo_audible || 
393                         
394                         // muted by mute of this track 
395                         
396                         !mute_audible ||
397                         
398                         // rec-enabled but not s/w monitoring 
399                         
400                         // TODO: this is probably wrong
401
402                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
403
404                         ) {
405                         
406                         co->silence (nframes, offset);
407                         
408                 } else {
409
410                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
411                         
412                 } 
413         } 
414
415         /* -----------------------------------------------------------------------------------------------------
416            DENORMAL CONTROL
417            -------------------------------------------------------------------------------------------------- */
418
419         if (_denormal_protection || Config->get_denormal_protection()) {
420
421                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
422                         Sample* const sp = i->data();
423                         
424                         for (nframes_t nx = offset; nx < nframes + offset; ++nx) {
425                                 sp[nx] += 1.0e-27f;
426                         }
427                 }
428         }
429
430         /* ----------------------------------------------------------------------------------------------------
431            PRE-FADER REDIRECTS
432            -------------------------------------------------------------------------------------------------- */
433
434         if (with_processors) {
435                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
436                 if (rm.locked()) {
437                         if (mute_gain > 0 || !_mute_affects_pre_fader) {
438                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
439                                         switch ((*i)->placement()) {
440                                         case PreFader:
441                                                 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
442                                                 break;
443                                         case PostFader:
444                                                 post_fader_work = true;
445                                                 break;
446                                         }
447                                 }
448                         } else {
449                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
450                                         switch ((*i)->placement()) {
451                                         case PreFader:
452                                                 (*i)->silence (nframes, offset);
453                                                 break;
454                                         case PostFader:
455                                                 post_fader_work = true;
456                                                 break;
457                                         }
458                                 }
459                         }
460                 } 
461         }
462
463         // This really should already be true...
464         bufs.set_count(pre_fader_streams());
465         
466         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_post_fader) {
467                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
468                 mute_gain = dmg;
469                 mute_declick_applied = true;
470         }
471
472         /* ----------------------------------------------------------------------------------------------------
473            PRE-FADER METERING & MONITORING
474            -------------------------------------------------------------------------------------------------- */
475
476         if (meter && (_meter_point == MeterPreFader)) {
477                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
478         }
479
480         
481         if ((_meter_point == MeterPreFader) && co) {
482                 
483                 solo_audible = dsg > 0;
484                 mute_audible = dmg > 0 || !_mute_affects_pre_fader;
485                 
486                 if ( // muted by solo of another track
487                         
488                         !solo_audible || 
489                         
490                         // muted by mute of this track 
491                         
492                         !mute_audible ||
493                         
494                         // rec-enabled but not s/w monitoring 
495                         
496                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
497
498                         ) {
499                         
500                         co->silence (nframes, offset);
501                         
502                 } else {
503
504                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
505                 } 
506         } 
507         
508         /* ----------------------------------------------------------------------------------------------------
509            GAIN STAGE
510            -------------------------------------------------------------------------------------------------- */
511
512         /* if not recording or recording and requiring any monitor signal, then apply gain */
513
514         if ( // not recording 
515
516                 !(record_enabled() && _session.actively_recording()) || 
517                 
518             // OR recording 
519                 
520                  // AND software monitoring required
521
522                 Config->get_monitoring_model() == SoftwareMonitoring) { 
523                 
524                 if (apply_gain_automation) {
525                         
526                         if (_phase_invert) {
527                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
528                                         Sample* const sp = i->data();
529                                         
530                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
531                                                 sp[nx] *= -gab[nx];
532                                         }
533                                 }
534                         } else {
535                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
536                                         Sample* const sp = i->data();
537                                         
538                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
539                                                 sp[nx] *= gab[nx];
540                                         }
541                                 }
542                         }
543                         
544                         if (apply_gain_automation && _session.transport_rolling() && nframes > 0) {
545                                 _effective_gain = gab[nframes-1];
546                         }
547                         
548                 } else {
549                         
550                         /* manual (scalar) gain */
551                         
552                         if (_gain != dg) {
553                                 
554                                 Amp::run_in_place (bufs, nframes, _gain, dg, _phase_invert);
555                                 _gain = dg;
556                                 
557                         } else if (_gain != 0 && (_phase_invert || _gain != 1.0)) {
558                                 
559                                 /* no need to interpolate current gain value,
560                                    but its non-unity, so apply it. if the gain
561                                    is zero, do nothing because we'll ship silence
562                                    below.
563                                 */
564
565                                 gain_t this_gain;
566                                 
567                                 if (_phase_invert) {
568                                         this_gain = -_gain;
569                                 } else {
570                                         this_gain = _gain;
571                                 }
572                                 
573                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
574                                         Sample* const sp = i->data();
575                                         apply_gain_to_buffer(sp,nframes,this_gain);
576                                 }
577
578                         } else if (_gain == 0) {
579                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
580                                         i->clear();
581                                 }
582                         }
583                 }
584
585         } else {
586
587                 /* actively recording, no monitoring required; leave buffers as-is to save CPU cycles */
588
589         }
590
591         /* ----------------------------------------------------------------------------------------------------
592            POST-FADER REDIRECTS
593            -------------------------------------------------------------------------------------------------- */
594
595         /* note that post_fader_work cannot be true unless with_processors was also true, so don't test both */
596
597         if (post_fader_work) {
598
599                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
600                 if (rm.locked()) {
601                         if (mute_gain > 0 || !_mute_affects_post_fader) {
602                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
603                                         switch ((*i)->placement()) {
604                                         case PreFader:
605                                                 break;
606                                         case PostFader:
607                                                 (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
608                                                 break;
609                                         }
610                                 }
611                         } else {
612                                 for (i = _processors.begin(); i != _processors.end(); ++i) {
613                                         switch ((*i)->placement()) {
614                                         case PreFader:
615                                                 break;
616                                         case PostFader:
617                                                 (*i)->silence (nframes, offset);
618                                                 break;
619                                         }
620                                 }
621                         }
622                 } 
623         }
624
625         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_control_outs) {
626                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
627                 mute_gain = dmg;
628                 mute_declick_applied = true;
629         }
630
631         /* ----------------------------------------------------------------------------------------------------
632            CONTROL OUTPUT STAGE
633            -------------------------------------------------------------------------------------------------- */
634
635         if ((_meter_point == MeterPostFader) && co) {
636                 
637                 solo_audible = solo_gain > 0;
638                 mute_audible = dmg > 0 || !_mute_affects_control_outs;
639
640                 if ( // silent anyway
641
642                         (_gain == 0 && !apply_gain_automation) || 
643                     
644                      // muted by solo of another track
645
646                         !solo_audible || 
647                     
648                      // muted by mute of this track 
649
650                         !mute_audible ||
651
652                     // recording but not s/w monitoring 
653                         
654                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
655
656                         ) {
657                         
658                         co->silence (nframes, offset);
659                         
660                 } else {
661
662                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
663                 } 
664         } 
665
666         /* ----------------------------------------------------------------------
667            GLOBAL MUTE 
668            ----------------------------------------------------------------------*/
669
670         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_main_outs) {
671                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
672                 mute_gain = dmg;
673                 mute_declick_applied = true;
674         }
675         
676         /* ----------------------------------------------------------------------------------------------------
677            MAIN OUTPUT STAGE
678            -------------------------------------------------------------------------------------------------- */
679
680         solo_audible = dsg > 0;
681         mute_audible = dmg > 0 || !_mute_affects_main_outs;
682         
683         if (n_outputs().get(_default_type) == 0) {
684             
685             /* relax */
686
687         } else if (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording())) {
688                 
689                 IO::silence (nframes, offset);
690                 
691         } else {
692
693                 if ( // silent anyway
694
695                     (_gain == 0 && !apply_gain_automation) ||
696                     
697                     // muted by solo of another track, but not using control outs for solo
698
699                     (!solo_audible && (Config->get_solo_model() != SoloBus)) ||
700                     
701                     // muted by mute of this track
702
703                     !mute_audible
704
705                         ) {
706
707                         /* don't use Route::silence() here, because that causes
708                            all outputs (sends, port processors, etc. to be silent).
709                         */
710                         
711                         if (_meter_point == MeterPostFader) {
712                                 peak_meter().reset();
713                         }
714
715                         IO::silence (nframes, offset);
716                         
717                 } else {
718                         
719                         deliver_output(bufs, start_frame, end_frame, nframes, offset);
720
721                 }
722
723         }
724
725         /* ----------------------------------------------------------------------------------------------------
726            POST-FADER METERING
727            -------------------------------------------------------------------------------------------------- */
728
729         if (meter && (_meter_point == MeterPostFader)) {
730                 if ((_gain == 0 && !apply_gain_automation) || dmg == 0) {
731                         _meter->reset();
732                 } else {
733                         _meter->run_in_place(output_buffers(), start_frame, end_frame, nframes, offset);
734                 }
735         }
736 }
737
738 #ifdef NEW_POB
739 /** Process this route for one (sub) cycle (process thread)
740  *
741  * @param bufs Scratch buffers to use for the signal path
742  * @param start_frame Initial transport frame 
743  * @param end_frame Final transport frame
744  * @param nframes Number of frames to output (to ports)
745  * @param offset Output offset (of port buffers, for split cycles)
746  *
747  * Note that (end_frame - start_frame) may not be equal to nframes when the
748  * transport speed isn't 1.0 (eg varispeed).
749  */
750 void
751 Route::process_output_buffers (BufferSet& bufs,
752                                nframes_t start_frame, nframes_t end_frame, 
753                                nframes_t nframes, nframes_t offset, bool with_processors, int declick,
754                                bool meter)
755 {
756         // This is definitely very audio-only for now
757         assert(_default_type == DataType::AUDIO);
758         
759         ProcessorList::iterator i;
760         bool post_fader_work = false;
761         bool mute_declick_applied = false;
762         gain_t dmg, dsg, dg;
763         IO *co;
764         bool mute_audible;
765         bool solo_audible;
766         bool no_monitor;
767         gain_t* gab = _session.gain_automation_buffer();
768
769         switch (Config->get_monitoring_model()) {
770         case HardwareMonitoring:
771         case ExternalMonitoring:
772                 no_monitor = true;
773                 break;
774         default:
775                 no_monitor = false;
776         }
777
778         declick = _pending_declick;
779
780         {
781                 Glib::Mutex::Lock cm (_control_outs_lock, Glib::TRY_LOCK);
782                 
783                 if (cm.locked()) {
784                         co = _control_outs;
785                 } else {
786                         co = 0;
787                 }
788         }
789         
790         { 
791                 Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
792                 
793                 if (dm.locked()) {
794                         dmg = desired_mute_gain;
795                         dsg = desired_solo_gain;
796                         dg = _desired_gain;
797                 } else {
798                         dmg = mute_gain;
799                         dsg = solo_gain;
800                         dg = _gain;
801                 }
802         }
803
804         /* ----------------------------------------------------------------------------------------------------
805            GLOBAL DECLICK (for transport changes etc.)
806            input metering & monitoring (control outs)
807            denormal control
808            pre-fader redirects
809            pre-fader metering & monitoring (control outs)
810            gain stage
811            post-fader redirects
812            global mute
813            main output
814            post-fader metering & monitoring (control outs)
815         */
816
817         {
818                 Glib::RWLock::ReaderLock rm (_processor_lock, Glib::TRY_LOCK);
819                 for (i = processors.begin(); i != processors.end(); ++i) {
820                         (*i)->run_in_place (bufs, start_frame, end_frame, nframes, offset);
821                 }
822         }
823
824         /* ----------------------------------------------------------------------------------------------------
825            INPUT METERING & MONITORING
826            -------------------------------------------------------------------------------------------------- */
827
828         if (meter && (_meter_point == MeterInput)) {
829                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
830         }
831
832         if (!_soloed && _mute_affects_pre_fader && (mute_gain != dmg)) {
833                 Amp::run_in_place (bufs, nframes, mute_gain, dmg, false);
834                 mute_gain = dmg;
835                 mute_declick_applied = true;
836         }
837
838         /* ----------------------------------------------------------------------------------------------------
839            PRE-FADER REDIRECTS
840            -------------------------------------------------------------------------------------------------- */
841
842         // This really should already be true...
843         bufs.set_count(pre_fader_streams());
844         
845
846         if ((_meter_point == MeterPreFader) && co) {
847                 
848                 solo_audible = dsg > 0;
849                 mute_audible = dmg > 0 || !_mute_affects_pre_fader;
850                 
851                 if ( // muted by solo of another track
852                         
853                         !solo_audible || 
854                         
855                         // muted by mute of this track 
856                         
857                         !mute_audible ||
858                         
859                         // rec-enabled but not s/w monitoring 
860                         
861                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
862
863                         ) {
864                         
865                         co->silence (nframes, offset);
866                         
867                 } else {
868
869                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
870                 } 
871         } 
872         
873         /* ----------------------------------------------------------------------------------------------------
874            GAIN STAGE
875            -------------------------------------------------------------------------------------------------- */
876
877         /* if not recording or recording and requiring any monitor signal, then apply gain */
878
879         if ( // not recording 
880
881                 !(record_enabled() && _session.actively_recording()) || 
882                 
883             // OR recording 
884                 
885                  // AND software monitoring required
886
887                 Config->get_monitoring_model() == SoftwareMonitoring) { 
888                 
889                 if (apply_gain_automation) {
890                         
891                         if (_phase_invert) {
892                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
893                                         Sample* const sp = i->data();
894                                         
895                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
896                                                 sp[nx] *= -gab[nx];
897                                         }
898                                 }
899                         } else {
900                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
901                                         Sample* const sp = i->data();
902                                         
903                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
904                                                 sp[nx] *= gab[nx];
905                                         }
906                                 }
907                         }
908                         
909                         if (apply_gain_automation && _session.transport_rolling() && nframes > 0) {
910                                 _effective_gain = gab[nframes-1];
911                         }
912                         
913                 } else {
914                         
915                         /* manual (scalar) gain */
916                         
917                         if (_gain != dg) {
918                                 
919                                 Amp::run_in_place (bufs, nframes, _gain, dg, _phase_invert);
920                                 _gain = dg;
921                                 
922                         } else if (_gain != 0 && (_phase_invert || _gain != 1.0)) {
923                                 
924                                 /* no need to interpolate current gain value,
925                                    but its non-unity, so apply it. if the gain
926                                    is zero, do nothing because we'll ship silence
927                                    below.
928                                 */
929
930                                 gain_t this_gain;
931                                 
932                                 if (_phase_invert) {
933                                         this_gain = -_gain;
934                                 } else {
935                                         this_gain = _gain;
936                                 }
937                                 
938                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
939                                         Sample* const sp = i->data();
940                                         apply_gain_to_buffer(sp,nframes,this_gain);
941                                 }
942
943                         } else if (_gain == 0) {
944                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
945                                         i->clear();
946                                 }
947                         }
948                 }
949
950         } else {
951
952                 /* actively recording, no monitoring required; leave buffers as-is to save CPU cycles */
953
954         }
955
956
957         /* ----------------------------------------------------------------------------------------------------
958            CONTROL OUTPUT STAGE
959            -------------------------------------------------------------------------------------------------- */
960
961         if ((_meter_point == MeterPostFader) && co) {
962                 
963                 solo_audible = solo_gain > 0;
964                 mute_audible = dmg > 0 || !_mute_affects_control_outs;
965
966                 if ( // silent anyway
967
968                         (_gain == 0 && !apply_gain_automation) || 
969                     
970                      // muted by solo of another track
971
972                         !solo_audible || 
973                     
974                      // muted by mute of this track 
975
976                         !mute_audible ||
977
978                     // recording but not s/w monitoring 
979                         
980                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
981
982                         ) {
983                         
984                         co->silence (nframes, offset);
985                         
986                 } else {
987
988                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
989                 } 
990         } 
991
992         /* ----------------------------------------------------------------------------------------------------
993            MAIN OUTPUT STAGE
994            -------------------------------------------------------------------------------------------------- */
995
996         solo_audible = dsg > 0;
997         mute_audible = dmg > 0 || !_mute_affects_main_outs;
998         
999         if (n_outputs().get(_default_type) == 0) {
1000             
1001             /* relax */
1002
1003         } else if (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording())) {
1004                 
1005                 IO::silence (nframes, offset);
1006                 
1007         } else {
1008
1009                 if ( // silent anyway
1010
1011                     (_gain == 0 && !apply_gain_automation) ||
1012                     
1013                     // muted by solo of another track, but not using control outs for solo
1014
1015                     (!solo_audible && (Config->get_solo_model() != SoloBus)) ||
1016                     
1017                     // muted by mute of this track
1018
1019                     !mute_audible
1020
1021                         ) {
1022
1023                         /* don't use Route::silence() here, because that causes
1024                            all outputs (sends, port processors, etc. to be silent).
1025                         */
1026                         
1027                         if (_meter_point == MeterPostFader) {
1028                                 peak_meter().reset();
1029                         }
1030
1031                         IO::silence (nframes, offset);
1032                         
1033                 } else {
1034                         
1035                         deliver_output(bufs, start_frame, end_frame, nframes, offset);
1036
1037                 }
1038
1039         }
1040 }
1041
1042 #endif /* NEW_POB */
1043
1044 ChanCount
1045 Route::n_process_buffers ()
1046 {
1047         return max (n_inputs(), processor_max_outs);
1048 }
1049
1050 void
1051 Route::passthru (nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset, int declick, bool meter_first)
1052 {
1053         BufferSet& bufs = _session.get_scratch_buffers(n_process_buffers());
1054
1055         _silent = false;
1056
1057         collect_input (bufs, nframes, offset);
1058
1059         if (meter_first) {
1060                 _meter->run_in_place(bufs, start_frame, end_frame, nframes, offset);
1061                 meter_first = false;
1062          } else {
1063                 meter_first = true;
1064          }
1065                 
1066         process_output_buffers (bufs, start_frame, end_frame, nframes, offset, true, declick, meter_first);
1067 }
1068
1069 void
1070 Route::passthru_silence (nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset, int declick, bool meter)
1071 {
1072         process_output_buffers (_session.get_silent_buffers (n_process_buffers()), start_frame, end_frame, nframes, offset, true, declick, meter);
1073 }
1074
1075 void
1076 Route::set_solo (bool yn, void *src)
1077 {
1078         if (_solo_safe) {
1079                 return;
1080         }
1081
1082         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
1083                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
1084                 return;
1085         }
1086
1087         if (_soloed != yn) {
1088                 _soloed = yn;
1089                 solo_changed (src); /* EMIT SIGNAL */
1090                 _solo_control->Changed (); /* EMIT SIGNAL */
1091         }       
1092         
1093         catch_up_on_solo_mute_override ();
1094 }
1095
1096 void
1097 Route::catch_up_on_solo_mute_override ()
1098 {
1099         if (Config->get_solo_model() != InverseMute) {
1100                 return;
1101         }
1102         
1103         {
1104
1105                 Glib::Mutex::Lock lm (declick_lock);
1106                 
1107                 if (_muted) {
1108                         if (Config->get_solo_mute_override()) {
1109                                 desired_mute_gain = (_soloed?1.0:0.0);
1110                         } else {
1111                                 desired_mute_gain = 0.0;
1112                         }
1113                 } else {
1114                         desired_mute_gain = 1.0;
1115                 }
1116         }
1117 }
1118
1119 void
1120 Route::set_solo_mute (bool yn)
1121 {
1122         Glib::Mutex::Lock lm (declick_lock);
1123
1124         /* Called by Session in response to another Route being soloed.
1125          */
1126            
1127         desired_solo_gain = (yn?0.0:1.0);
1128 }
1129
1130 void
1131 Route::set_solo_safe (bool yn, void *src)
1132 {
1133         if (_solo_safe != yn) {
1134                 _solo_safe = yn;
1135                  solo_safe_changed (src); /* EMIT SIGNAL */
1136         }
1137 }
1138
1139 void
1140 Route::set_mute (bool yn, void *src)
1141
1142 {
1143         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
1144                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
1145                 return;
1146         }
1147
1148         if (_muted != yn) {
1149                 _muted = yn;
1150                 mute_changed (src); /* EMIT SIGNAL */
1151                 
1152                 _mute_control->Changed (); /* EMIT SIGNAL */
1153                 
1154                 Glib::Mutex::Lock lm (declick_lock);
1155                 
1156                 if (_soloed && Config->get_solo_mute_override()){
1157                         desired_mute_gain = 1.0f;
1158                 } else {
1159                         desired_mute_gain = (yn?0.0f:1.0f);
1160                 }
1161         }
1162 }
1163
1164 int
1165 Route::add_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1166 {
1167         ChanCount old_pmo = processor_max_outs;
1168
1169         if (!_session.engine().connected()) {
1170                 return 1;
1171         }
1172
1173         {
1174                 Glib::RWLock::WriterLock lm (_processor_lock);
1175
1176                 boost::shared_ptr<PluginInsert> pi;
1177                 boost::shared_ptr<PortInsert> porti;
1178
1179                 //processor->set_default_type(_default_type);
1180
1181                 _processors.push_back (processor);
1182
1183                 // Set up processor list channels.  This will set processor->[input|output]_streams(),
1184                 // configure redirect ports properly, etc.
1185                 if (_reset_processor_counts (err)) {
1186                         _processors.pop_back ();
1187                         _reset_processor_counts (0); // it worked before we tried to add it ...
1188                         return -1;
1189                 }
1190
1191                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(processor)) != 0) {
1192                         
1193                         if (pi->natural_input_streams() == ChanCount::ZERO) {
1194                                 /* generator plugin */
1195                                 _have_internal_generator = true;
1196                         }
1197                         
1198                 }
1199                 
1200                 // Ensure peak vector sizes before the plugin is activated
1201
1202                 ChanCount potential_max_streams;
1203
1204                 potential_max_streams.set (DataType::AUDIO, max (processor->input_streams().n_audio(), 
1205                                                                  processor->output_streams().n_audio()));
1206                 potential_max_streams.set (DataType::MIDI, max (processor->input_streams().n_midi(), 
1207                                                                 processor->output_streams().n_midi()));
1208
1209                 _meter->configure_io (potential_max_streams, potential_max_streams);
1210
1211                 // XXX: do we want to emit the signal here ? change call order.
1212                 processor->activate ();
1213                 processor->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
1214
1215                 _user_latency = 0;
1216         }
1217         
1218         if (processor_max_outs != old_pmo || old_pmo == ChanCount::ZERO) {
1219                 reset_panner ();
1220         }
1221
1222         processors_changed (); /* EMIT SIGNAL */
1223         
1224         return 0;
1225 }
1226
1227 int
1228 Route::add_processors (const ProcessorList& others, ProcessorStreams* err)
1229 {
1230         ChanCount old_pmo = processor_max_outs;
1231
1232         if (!_session.engine().connected()) {
1233                 return 1;
1234         }
1235
1236         {
1237                 Glib::RWLock::WriterLock lm (_processor_lock);
1238
1239                 ProcessorList::iterator existing_end = _processors.end();
1240                 --existing_end;
1241
1242                 ChanCount potential_max_streams;
1243
1244                 for (ProcessorList::const_iterator i = others.begin(); i != others.end(); ++i) {
1245                         
1246                         boost::shared_ptr<PluginInsert> pi;
1247                         
1248                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1249                                 pi->set_count (1);
1250                                 
1251                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
1252                                 if (m > potential_max_streams)
1253                                         potential_max_streams = m;
1254                         }
1255
1256                         // Ensure peak vector sizes before the plugin is activated
1257                         _meter->configure_io (potential_max_streams, potential_max_streams);
1258
1259                         _processors.push_back (*i);
1260                         
1261                         if (_reset_processor_counts (err)) {
1262                                 ++existing_end;
1263                                 _processors.erase (existing_end, _processors.end());
1264                                 _reset_processor_counts (0); // it worked before we tried to add it ...
1265                                 return -1;
1266                         }
1267                         
1268                         (*i)->ActiveChanged.connect (bind (mem_fun (_session, &Session::update_latency_compensation), false, false));
1269                 }
1270
1271                 _user_latency = 0;
1272         }
1273         
1274         if (processor_max_outs != old_pmo || old_pmo == ChanCount::ZERO) {
1275                 reset_panner ();
1276         }
1277
1278         processors_changed (); /* EMIT SIGNAL */
1279         return 0;
1280 }
1281
1282 /** Turn off all processors with a given placement
1283  * @param p Placement of processors to disable
1284  */
1285
1286 void
1287 Route::disable_processors (Placement p)
1288 {
1289         Glib::RWLock::ReaderLock lm (_processor_lock);
1290         
1291         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1292                 if ((*i)->placement() == p) {
1293                         (*i)->set_active (false);
1294                 }
1295         }
1296
1297         _session.set_dirty ();
1298 }
1299
1300 /** Turn off all redirects 
1301  */
1302
1303 void
1304 Route::disable_processors ()
1305 {
1306         Glib::RWLock::ReaderLock lm (_processor_lock);
1307         
1308         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1309                 (*i)->set_active (false);
1310         }
1311         
1312         _session.set_dirty ();
1313 }
1314
1315 /** Turn off all redirects with a given placement
1316  * @param p Placement of redirects to disable
1317  */
1318
1319 void
1320 Route::disable_plugins (Placement p)
1321 {
1322         Glib::RWLock::ReaderLock lm (_processor_lock);
1323         
1324         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1325                 if (boost::dynamic_pointer_cast<PluginInsert> (*i) && (*i)->placement() == p) {
1326                         (*i)->set_active (false);
1327                 }
1328         }
1329         
1330         _session.set_dirty ();
1331 }
1332
1333 /** Turn off all plugins
1334  */
1335
1336 void
1337 Route::disable_plugins ()
1338 {
1339         Glib::RWLock::ReaderLock lm (_processor_lock);
1340         
1341         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1342                 if (boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1343                         (*i)->set_active (false);
1344                 }
1345         }
1346         
1347         _session.set_dirty ();
1348 }
1349
1350
1351 void
1352 Route::ab_plugins (bool forward)
1353 {
1354         Glib::RWLock::ReaderLock lm (_processor_lock);
1355                         
1356         if (forward) {
1357
1358                 /* forward = turn off all active redirects, and mark them so that the next time
1359                    we go the other way, we will revert them
1360                 */
1361
1362                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1363                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1364                                 continue;
1365                         }
1366
1367                         if ((*i)->active()) {
1368                                 (*i)->set_active (false);
1369                                 (*i)->set_next_ab_is_active (true);
1370                         } else {
1371                                 (*i)->set_next_ab_is_active (false);
1372                         }
1373                 }
1374
1375         } else {
1376
1377                 /* backward = if the redirect was marked to go active on the next ab, do so */
1378
1379                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1380
1381                         if (!boost::dynamic_pointer_cast<PluginInsert> (*i)) {
1382                                 continue;
1383                         }
1384
1385                         if ((*i)->get_next_ab_is_active()) {
1386                                 (*i)->set_active (true);
1387                         } else {
1388                                 (*i)->set_active (false);
1389                         }
1390                 }
1391         }
1392         
1393         _session.set_dirty ();
1394 }
1395         
1396         
1397 /* Figure out the streams that will feed into PreFader */
1398 ChanCount
1399 Route::pre_fader_streams() const
1400 {
1401         boost::shared_ptr<Processor> processor;
1402
1403         // Find the last pre-fader redirect
1404         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
1405                 if ((*i)->placement() == PreFader) {
1406                         processor = *i;
1407                 }
1408         }
1409         
1410         if (processor) {
1411                 return processor->output_streams();
1412         } else {
1413                 return n_inputs ();
1414         }
1415 }
1416
1417
1418 /** Remove processors with a given placement.
1419  * @param p Placement of processors to remove.
1420  */
1421 void
1422 Route::clear_processors (Placement p)
1423 {
1424         const ChanCount old_pmo = processor_max_outs;
1425
1426         if (!_session.engine().connected()) {
1427                 return;
1428         }
1429
1430         {
1431                 Glib::RWLock::WriterLock lm (_processor_lock);
1432                 ProcessorList new_list;
1433                 
1434                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1435                         if ((*i)->placement() == p) {
1436                                 /* it's the placement we want to get rid of */
1437                                 (*i)->drop_references ();
1438                         } else {
1439                                 /* it's a different placement, so keep it */
1440                                 new_list.push_back (*i);
1441                         }
1442                 }
1443                 
1444                 _processors = new_list;
1445         }
1446
1447         /* FIXME: can't see how this test can ever fire */
1448         if (processor_max_outs != old_pmo) {
1449                 reset_panner ();
1450         }
1451         
1452         processor_max_outs.reset();
1453         _have_internal_generator = false;
1454         processors_changed (); /* EMIT SIGNAL */
1455 }
1456
1457 int
1458 Route::remove_processor (boost::shared_ptr<Processor> processor, ProcessorStreams* err)
1459 {
1460         ChanCount old_pmo = processor_max_outs;
1461
1462         if (!_session.engine().connected()) {
1463                 return 1;
1464         }
1465
1466         processor_max_outs.reset();
1467
1468         {
1469                 Glib::RWLock::WriterLock lm (_processor_lock);
1470                 ProcessorList::iterator i;
1471                 bool removed = false;
1472
1473                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1474                         if (*i == processor) {
1475
1476                                 ProcessorList::iterator tmp;
1477
1478                                 /* move along, see failure case for reset_processor_counts()
1479                                    where we may need to reprocessor the processor.
1480                                 */
1481
1482                                 tmp = i;
1483                                 ++tmp;
1484
1485                                 /* stop redirects that send signals to JACK ports
1486                                    from causing noise as a result of no longer being
1487                                    run.
1488                                 */
1489
1490                                 boost::shared_ptr<IOProcessor> redirect;
1491                                 
1492                                 if ((redirect = boost::dynamic_pointer_cast<IOProcessor> (*i)) != 0) {
1493                                         redirect->io()->disconnect_inputs (this);
1494                                         redirect->io()->disconnect_outputs (this);
1495                                 }
1496
1497                                 _processors.erase (i);
1498
1499                                 i = tmp;
1500                                 removed = true;
1501                                 break;
1502                         }
1503
1504                         _user_latency = 0;
1505                 }
1506
1507                 if (!removed) {
1508                         /* what? */
1509                         return 1;
1510                 }
1511
1512                 if (_reset_processor_counts (err)) {
1513                         /* get back to where we where */
1514                         _processors.insert (i, processor);
1515                         /* we know this will work, because it worked before :) */
1516                         _reset_processor_counts (0);
1517                         return -1;
1518                 }
1519
1520                 _have_internal_generator = false;
1521
1522                 for (i = _processors.begin(); i != _processors.end(); ++i) {
1523                         boost::shared_ptr<PluginInsert> pi;
1524                         
1525                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
1526                                 if (pi->is_generator()) {
1527                                         _have_internal_generator = true;
1528                                         break;
1529                                 }
1530                         }
1531                 }
1532         }
1533
1534         if (old_pmo != processor_max_outs) {
1535                 reset_panner ();
1536         }
1537
1538         processor->drop_references ();
1539
1540         processors_changed (); /* EMIT SIGNAL */
1541         return 0;
1542 }
1543
1544 int
1545 Route::reset_processor_counts (ProcessorStreams* err)
1546 {
1547         Glib::RWLock::WriterLock lm (_processor_lock);
1548         return _reset_processor_counts (err);
1549 }
1550
1551
1552 int
1553 Route::_reset_processor_counts (ProcessorStreams* err)
1554 {
1555         ProcessorList::iterator r;
1556         uint32_t insert_cnt = 0;
1557         uint32_t send_cnt = 0;
1558         map<Placement,list<ProcessorCount> > proc_map;
1559         ProcessorList::iterator prev;
1560         ChanCount initial_streams = n_inputs ();
1561         ChanCount previous_initial_streams = n_inputs ();
1562         int ret = -1;
1563         uint32_t max_audio = 0;
1564         uint32_t max_midi = 0;
1565
1566         processor_max_outs.reset ();
1567         
1568         /* Step 1: build a map that links each insert to an in/out channel count 
1569
1570            Divide inserts up by placement so we get the signal flow
1571            properly modelled. we need to do this because the _processors
1572            list is not sorted by placement, and because other reasons may 
1573            exist now or in the future for this separate treatment.
1574         */
1575
1576         /* ... but it should/will be... */
1577         
1578         for (r = _processors.begin(); r != _processors.end(); ++r) {
1579
1580                 boost::shared_ptr<PluginInsert> plugin_insert;
1581                 boost::shared_ptr<PortInsert> port_insert;
1582
1583                 if ((plugin_insert = boost::dynamic_pointer_cast<PluginInsert>(*r)) != 0) {
1584
1585                         ++insert_cnt;
1586                         proc_map[(*r)->placement()].push_back (ProcessorCount (*r));
1587
1588                         /* reset plugin counts back to one for now so
1589                            that we have a predictable, controlled
1590                            state to try to configure.
1591                         */
1592
1593                         plugin_insert->set_count (1);
1594
1595                 } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert>(*r)) != 0) {
1596                         
1597                         ++insert_cnt;
1598                         proc_map[(*r)->placement()].push_back (ProcessorCount (*r));
1599
1600                 } else if (boost::dynamic_pointer_cast<Send> (*r) != 0) {
1601                         ++send_cnt;
1602                 }
1603         }
1604         
1605         if (insert_cnt == 0) {
1606                 if (send_cnt) {
1607                         goto recompute;
1608                 } else {
1609                         ret = 0;
1610                         goto streamcount;
1611                 }
1612         }
1613
1614         /* Now process each placement in order, checking to see if we 
1615            can really do what has been requested.
1616         */
1617
1618         /* A: PreFader */
1619         
1620         if (check_some_processor_counts (proc_map[PreFader], n_inputs (), err)) {
1621                 goto streamcount;
1622         }
1623
1624         if (!proc_map[PreFader].empty()) {
1625                 previous_initial_streams = n_inputs ();
1626                 for (list<ProcessorCount>::iterator i = proc_map[PreFader].begin(); i != proc_map[PreFader].end(); i++) {
1627                         if (i->processor->can_support_io_configuration (previous_initial_streams, initial_streams) < 0) {
1628                                 goto streamcount;
1629                         }
1630                         previous_initial_streams = initial_streams;
1631                 }
1632         }
1633
1634         /* B: PostFader */
1635
1636         if (check_some_processor_counts (proc_map[PostFader], initial_streams, err)) {
1637                 goto streamcount;
1638         }
1639
1640         if (!proc_map[PostFader].empty()) {
1641                 for (list<ProcessorCount>::iterator i = proc_map[PostFader].begin(); i != proc_map[PostFader].end(); i++) {
1642                         if (i->processor->can_support_io_configuration (previous_initial_streams, initial_streams) < 0) {
1643                                 goto streamcount;
1644                         }
1645                         previous_initial_streams = initial_streams;
1646                 }
1647         }
1648
1649         /* OK, everything can be set up correctly, so lets do it */
1650
1651         apply_some_processor_counts (proc_map[PreFader]);
1652         apply_some_processor_counts (proc_map[PostFader]);
1653
1654         /* recompute max outs of any processor */
1655
1656         ret = 0;
1657
1658   recompute:
1659
1660         processor_max_outs.reset ();
1661         prev = _processors.end();
1662
1663         for (r = _processors.begin(); r != _processors.end(); prev = r, ++r) {
1664                 boost::shared_ptr<Send> s;
1665
1666                 if ((s = boost::dynamic_pointer_cast<Send> (*r)) != 0) {
1667                         if (r == _processors.begin()) {
1668                                 s->expect_inputs (n_inputs());
1669                         } else {
1670                                 s->expect_inputs ((*prev)->output_streams());
1671                         }
1672
1673                 } else {
1674                         
1675                         /* don't pay any attention to send output configuration, since it doesn't
1676                            affect the route.
1677                          */
1678                         
1679                         max_audio = max ((*r)->output_streams ().n_audio(), max_audio);
1680                         max_midi = max ((*r)->output_streams ().n_midi(), max_midi);
1681                 }
1682         }
1683
1684         processor_max_outs.set (DataType::AUDIO, max_audio);
1685         processor_max_outs.set (DataType::MIDI, max_midi);
1686                         
1687         /* we're done */
1688         return 0;
1689
1690   streamcount:
1691         for (r = _processors.begin(); r != _processors.end(); ++r) {
1692                 max_audio = max ((*r)->output_streams ().n_audio(), max_audio);
1693                 max_midi = max ((*r)->output_streams ().n_midi(), max_midi);
1694         }
1695
1696         processor_max_outs.set (DataType::AUDIO, max_audio);
1697         processor_max_outs.set (DataType::MIDI, max_midi);
1698
1699         return ret;
1700 }                                  
1701
1702 int32_t
1703 Route::apply_some_processor_counts (list<ProcessorCount>& iclist)
1704 {
1705         list<ProcessorCount>::iterator i;
1706         
1707         for (i = iclist.begin(); i != iclist.end(); ++i) {
1708
1709                 ProcessorCount& pc (*i);
1710
1711                 cerr << "now applying for " << (*i).processor->name() << " in = " << pc.in.n_audio() << " out = " << pc.out.n_audio() << endl;
1712
1713                 if (pc.processor->configure_io (pc.in, pc.out)) {
1714                         return -1;
1715                 }
1716
1717                 /* make sure that however many we have, they are all active */
1718
1719                 pc.processor->activate ();
1720         }
1721
1722         return 0;
1723 }
1724
1725 /** Returns whether \a iclist can be configured and run starting with
1726  * \a required_inputs at the first processor's inputs.
1727  * If false is returned, \a iclist can not be run with \a required_inputs, and \a err is set.
1728  * Otherwise, \a err is set to the output of the list.
1729  */
1730 bool
1731 Route::check_some_processor_counts (list<ProcessorCount>& iclist, ChanCount required_inputs, ProcessorStreams* err)
1732 {
1733         list<ProcessorCount>::iterator i;
1734         size_t index = 0;
1735                         
1736         if (err) {
1737                 err->index = 0;
1738                 err->count = required_inputs;
1739         }
1740
1741         for (i = iclist.begin(); i != iclist.end(); ++i, ++index) {
1742
1743                 cerr << "Checking whether " << (*i).processor->name() << " can support " << required_inputs.n_audio() << " inputs\n";
1744
1745                 if (!(*i).processor->can_support_io_configuration (required_inputs, (*i).out)) {
1746                         if (err) {
1747                                 err->index = index;
1748                                 err->count = required_inputs;
1749                         }
1750                         return true;
1751                 }
1752                 
1753                 (*i).in = required_inputs;
1754                 required_inputs = (*i).out;
1755         }
1756
1757         return false;
1758 }
1759
1760 int
1761 Route::copy_processors (const Route& other, Placement placement, ProcessorStreams* err)
1762 {
1763         ChanCount old_pmo = processor_max_outs;
1764
1765         ProcessorList to_be_deleted;
1766
1767         {
1768                 Glib::RWLock::WriterLock lm (_processor_lock);
1769                 ProcessorList::iterator tmp;
1770                 ProcessorList the_copy;
1771
1772                 the_copy = _processors;
1773                 
1774                 /* remove all relevant processors */
1775
1776                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ) {
1777                         tmp = i;
1778                         ++tmp;
1779
1780                         if ((*i)->placement() == placement) {
1781                                 to_be_deleted.push_back (*i);
1782                                 _processors.erase (i);
1783                         }
1784
1785                         i = tmp;
1786                 }
1787
1788                 /* now copy the relevant ones from "other" */
1789                 
1790                 for (ProcessorList::const_iterator i = other._processors.begin(); i != other._processors.end(); ++i) {
1791                         if ((*i)->placement() == placement) {
1792                                 _processors.push_back (IOProcessor::clone (*i));
1793                         }
1794                 }
1795
1796                 /* reset plugin stream handling */
1797
1798                 if (_reset_processor_counts (err)) {
1799
1800                         /* FAILED COPY ATTEMPT: we have to restore order */
1801
1802                         /* delete all cloned processors */
1803
1804                         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ) {
1805
1806                                 tmp = i;
1807                                 ++tmp;
1808
1809                                 if ((*i)->placement() == placement) {
1810                                         _processors.erase (i);
1811                                 }
1812                                 
1813                                 i = tmp;
1814                         }
1815
1816                         /* restore the natural order */
1817
1818                         _processors = the_copy;
1819                         processor_max_outs = old_pmo;
1820
1821                         /* we failed, even though things are OK again */
1822
1823                         return -1;
1824
1825                 } else {
1826                         
1827                         /* SUCCESSFUL COPY ATTEMPT: delete the processors we removed pre-copy */
1828                         to_be_deleted.clear ();
1829                         _user_latency = 0;
1830                 }
1831         }
1832
1833         if (processor_max_outs != old_pmo || old_pmo == ChanCount::ZERO) {
1834                 reset_panner ();
1835         }
1836
1837         processors_changed (); /* EMIT SIGNAL */
1838         return 0;
1839 }
1840
1841 void
1842 Route::all_processors_flip ()
1843 {
1844         Glib::RWLock::ReaderLock lm (_processor_lock);
1845
1846         if (_processors.empty()) {
1847                 return;
1848         }
1849
1850         bool first_is_on = _processors.front()->active();
1851         
1852         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1853                 (*i)->set_active (!first_is_on);
1854         }
1855         
1856         _session.set_dirty ();
1857 }
1858
1859 /** Set all processors with a given placement to a given active state.
1860  * @param p Placement of processors to change.
1861  * @param state New active state for those processors.
1862  */
1863 void
1864 Route::all_processors_active (Placement p, bool state)
1865 {
1866         Glib::RWLock::ReaderLock lm (_processor_lock);
1867
1868         if (_processors.empty()) {
1869                 return;
1870         }
1871
1872         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
1873                 if ((*i)->placement() == p) {
1874                         (*i)->set_active (state);
1875                 }
1876         }
1877         
1878         _session.set_dirty ();
1879 }
1880
1881 struct ProcessorSorter {
1882     bool operator() (boost::shared_ptr<const Processor> a, boost::shared_ptr<const Processor> b) {
1883             return a->sort_key() < b->sort_key();
1884     }
1885 };
1886
1887 int
1888 Route::sort_processors (ProcessorStreams* err)
1889 {
1890         {
1891                 ProcessorSorter comparator;
1892                 Glib::RWLock::WriterLock lm (_processor_lock);
1893                 ChanCount old_pmo = processor_max_outs;
1894
1895                 /* the sweet power of C++ ... */
1896
1897                 ProcessorList as_it_was_before = _processors;
1898
1899                 _processors.sort (comparator);
1900         
1901                 if (_reset_processor_counts (err)) {
1902                         _processors = as_it_was_before;
1903                         processor_max_outs = old_pmo;
1904                         return -1;
1905                 } 
1906         } 
1907
1908         reset_panner ();
1909         processors_changed (); /* EMIT SIGNAL */
1910
1911         return 0;
1912 }
1913
1914 XMLNode&
1915 Route::get_state()
1916 {
1917         return state(true);
1918 }
1919
1920 XMLNode&
1921 Route::get_template()
1922 {
1923         return state(false);
1924 }
1925
1926 XMLNode&
1927 Route::state(bool full_state)
1928 {
1929         XMLNode *node = new XMLNode("Route");
1930         ProcessorList::iterator i;
1931         char buf[32];
1932
1933         if (_flags) {
1934                 node->add_property("flags", enum_2_string (_flags));
1935         }
1936         
1937         node->add_property("default-type", _default_type.to_string());
1938
1939         node->add_property("active", _active?"yes":"no");
1940         node->add_property("muted", _muted?"yes":"no");
1941         node->add_property("soloed", _soloed?"yes":"no");
1942         node->add_property("phase-invert", _phase_invert?"yes":"no");
1943         node->add_property("denormal-protection", _denormal_protection?"yes":"no");
1944         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1945         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1946         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1947         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1948
1949         if (_edit_group) {
1950                 node->add_property("edit-group", _edit_group->name());
1951         }
1952         if (_mix_group) {
1953                 node->add_property("mix-group", _mix_group->name());
1954         }
1955
1956         string order_string;
1957         OrderKeys::iterator x = order_keys.begin(); 
1958
1959         while (x != order_keys.end()) {
1960                 order_string += string ((*x).first);
1961                 order_string += '=';
1962                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1963                 order_string += buf;
1964                 
1965                 ++x;
1966
1967                 if (x == order_keys.end()) {
1968                         break;
1969                 }
1970
1971                 order_string += ':';
1972         }
1973         node->add_property ("order-keys", order_string);
1974
1975         node->add_child_nocopy (IO::state (full_state));
1976         node->add_child_nocopy (_solo_control->get_state ());
1977         node->add_child_nocopy (_mute_control->get_state ());
1978
1979         XMLNode* remote_control_node = new XMLNode (X_("remote_control"));
1980         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1981         remote_control_node->add_property (X_("id"), buf);
1982         node->add_child_nocopy (*remote_control_node);
1983
1984         if (_control_outs) {
1985                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1986                 cnode->add_child_nocopy (_control_outs->state (full_state));
1987                 node->add_child_nocopy (*cnode);
1988         }
1989
1990         if (_comment.length()) {
1991                 XMLNode *cmt = node->add_child ("Comment");
1992                 cmt->add_content (_comment);
1993         }
1994
1995         for (i = _processors.begin(); i != _processors.end(); ++i) {
1996                 node->add_child_nocopy((*i)->state (full_state));
1997         }
1998
1999         if (_extra_xml){
2000                 node->add_child_copy (*_extra_xml);
2001         }
2002         
2003         return *node;
2004 }
2005
2006 XMLNode&
2007 Route::get_processor_state ()
2008 {
2009         XMLNode* root = new XMLNode (X_("redirects"));
2010         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2011                 root->add_child_nocopy ((*i)->state (true));
2012         }
2013
2014         return *root;
2015 }
2016
2017 int
2018 Route::set_processor_state (const XMLNode& root)
2019 {
2020         if (root.name() != X_("redirects")) {
2021                 return -1;
2022         }
2023
2024         XMLNodeList nlist;
2025         XMLNodeList nnlist;
2026         XMLNodeConstIterator iter;
2027         XMLNodeConstIterator niter;
2028         Glib::RWLock::ReaderLock lm (_processor_lock);
2029
2030         nlist = root.children();
2031         
2032         for (iter = nlist.begin(); iter != nlist.end(); ++iter){
2033
2034                 /* iter now points to a IOProcessor state node */
2035                 
2036                 nnlist = (*iter)->children ();
2037
2038                 for (niter = nnlist.begin(); niter != nnlist.end(); ++niter) {
2039
2040                         /* find the IO child node, since it contains the ID we need */
2041
2042                         /* XXX OOP encapsulation violation, ugh */
2043
2044                         if ((*niter)->name() == IO::state_node_name) {
2045
2046                                 XMLProperty* prop = (*niter)->property (X_("id"));
2047                                 
2048                                 if (!prop) {
2049                                         warning << _("IOProcessor node has no ID, ignored") << endmsg;
2050                                         break;
2051                                 }
2052
2053                                 ID id = prop->value ();
2054
2055                                 /* now look for a processor with that ID */
2056         
2057                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2058                                         if ((*i)->id() == id) {
2059                                                 (*i)->set_state (**iter);
2060                                                 break;
2061                                         }
2062                                 }
2063                                 
2064                                 break;
2065                                 
2066                         }
2067                 }
2068
2069         }
2070
2071         return 0;
2072 }
2073
2074 void
2075 Route::set_deferred_state ()
2076 {
2077         XMLNodeList nlist;
2078         XMLNodeConstIterator niter;
2079
2080         if (!deferred_state) {
2081                 return;
2082         }
2083
2084         nlist = deferred_state->children();
2085
2086         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2087                 add_processor_from_xml (**niter);
2088         }
2089
2090         delete deferred_state;
2091         deferred_state = 0;
2092 }
2093
2094 void
2095 Route::add_processor_from_xml (const XMLNode& node)
2096 {
2097         const XMLProperty *prop;
2098
2099         // legacy sessions use a different node name for sends
2100         if (node.name() == "Send") {
2101         
2102                 try {
2103                         boost::shared_ptr<Send> send (new Send (_session, node));
2104                         add_processor (send);
2105                 } 
2106                 
2107                 catch (failed_constructor &err) {
2108                         error << _("Send construction failed") << endmsg;
2109                         return;
2110                 }
2111                 
2112         // use "Processor" in XML?
2113         } else if (node.name() == "Processor") {
2114                 
2115                 try {
2116                         if ((prop = node.property ("type")) != 0) {
2117
2118                                 boost::shared_ptr<Processor> processor;
2119                                 bool have_insert = false;
2120
2121                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || 
2122                                     prop->value() == "lv2" ||
2123                                     prop->value() == "vst" ||
2124                                     prop->value() == "audiounit") {
2125                                         
2126                                         processor.reset (new PluginInsert(_session, node));
2127                                         have_insert = true;
2128                                         
2129                                 } else if (prop->value() == "port") {
2130
2131                                         processor.reset (new PortInsert (_session, node));
2132                                 
2133                                 } else if (prop->value() == "send") {
2134
2135                                         processor.reset (new Send (_session, node));
2136                                         have_insert = true;
2137
2138                                 } else {
2139
2140                                         error << string_compose(_("unknown Processor type \"%1\"; ignored"), prop->value()) << endmsg;
2141                                 }
2142                                 
2143                                 add_processor (processor);
2144                                 
2145                         } else {
2146                                 error << _("Processor XML node has no type property") << endmsg;
2147                         }
2148                 }
2149
2150                 catch (failed_constructor &err) {
2151                         warning << _("processor could not be created. Ignored.") << endmsg;
2152                         return;
2153                 }
2154         }
2155 }
2156
2157 int
2158 Route::set_state (const XMLNode& node)
2159 {
2160         return _set_state (node, true);
2161 }
2162
2163 int
2164 Route::_set_state (const XMLNode& node, bool call_base)
2165 {
2166         XMLNodeList nlist;
2167         XMLNodeConstIterator niter;
2168         XMLNode *child;
2169         XMLPropertyList plist;
2170         const XMLProperty *prop;
2171
2172         if (node.name() != "Route"){
2173                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
2174                 return -1;
2175         }
2176
2177         if ((prop = node.property (X_("flags"))) != 0) {
2178                 _flags = Flag (string_2_enum (prop->value(), _flags));
2179         } else {
2180                 _flags = Flag (0);
2181         }
2182         
2183         if ((prop = node.property (X_("default-type"))) != 0) {
2184                 _default_type = DataType(prop->value());
2185                 assert(_default_type != DataType::NIL);
2186         }
2187
2188         if ((prop = node.property (X_("phase-invert"))) != 0) {
2189                 set_phase_invert (prop->value()=="yes"?true:false, this);
2190         }
2191
2192         if ((prop = node.property (X_("denormal-protection"))) != 0) {
2193                 set_denormal_protection (prop->value()=="yes"?true:false, this);
2194         }
2195         
2196         _active = true;
2197         if ((prop = node.property (X_("active"))) != 0) {
2198                 set_active (prop->value() == "yes");
2199         }
2200
2201         if ((prop = node.property (X_("muted"))) != 0) {
2202                 bool yn = prop->value()=="yes"?true:false; 
2203
2204                 /* force reset of mute status */
2205
2206                 _muted = !yn;
2207                 set_mute(yn, this);
2208                 mute_gain = desired_mute_gain;
2209         }
2210
2211         if ((prop = node.property (X_("soloed"))) != 0) {
2212                 bool yn = prop->value()=="yes"?true:false; 
2213
2214                 /* force reset of solo status */
2215
2216                 _soloed = !yn;
2217                 set_solo (yn, this);
2218                 solo_gain = desired_solo_gain;
2219         }
2220
2221         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
2222                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
2223         }
2224
2225         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
2226                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
2227         }
2228
2229         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
2230                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
2231         }
2232
2233         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
2234                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
2235         }
2236
2237         if ((prop = node.property (X_("edit-group"))) != 0) {
2238                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
2239                 if(edit_group == 0) {
2240                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
2241                 } else {
2242                         set_edit_group(edit_group, this);
2243                 }
2244         }
2245
2246         if ((prop = node.property (X_("order-keys"))) != 0) {
2247
2248                 long n;
2249
2250                 string::size_type colon, equal;
2251                 string remaining = prop->value();
2252
2253                 while (remaining.length()) {
2254
2255                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
2256                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2257                                       << endmsg;
2258                         } else {
2259                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
2260                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
2261                                               << endmsg;
2262                                 } else {
2263                                         set_order_key (remaining.substr (0, equal).c_str(), n);
2264                                 }
2265                         }
2266
2267                         colon = remaining.find_first_of (':');
2268
2269                         if (colon != string::npos) {
2270                                 remaining = remaining.substr (colon+1);
2271                         } else {
2272                                 break;
2273                         }
2274                 }
2275         }
2276
2277         nlist = node.children();
2278
2279         if (deferred_state) {
2280                 delete deferred_state;
2281         }
2282
2283         deferred_state = new XMLNode(X_("deferred state"));
2284
2285         /* set parent class properties before anything else */
2286
2287         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2288
2289                 child = *niter;
2290
2291                 if (child->name() == IO::state_node_name && call_base) {
2292
2293                         IO::set_state (*child);
2294                         break;
2295                 }
2296         }
2297
2298         XMLNodeList processor_nodes;
2299                         
2300         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2301
2302                 child = *niter;
2303                         
2304                 if (child->name() == X_("Send") || child->name() == X_("Processor")) {
2305                         processor_nodes.push_back(child);
2306                 }
2307
2308         }
2309
2310         _set_processor_states(processor_nodes);
2311
2312
2313         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
2314                 child = *niter;
2315                 // All processors have been applied already
2316
2317                 if (child->name() == X_("Automation")) {
2318                         
2319                         if ((prop = child->property (X_("path"))) != 0)  {
2320                                 load_automation (prop->value());
2321                         }
2322
2323                 } else if (child->name() == X_("ControlOuts")) {
2324                         
2325                         string coutname = _name;
2326                         coutname += _("[control]");
2327
2328                         _control_outs = new IO (_session, coutname);
2329                         _control_outs->set_state (**(child->children().begin()));
2330
2331                 } else if (child->name() == X_("Comment")) {
2332
2333                         /* XXX this is a terrible API design in libxml++ */
2334
2335                         XMLNode *cmt = *(child->children().begin());
2336                         _comment = cmt->content();
2337
2338                 } else if (child->name() == X_("extra")) {
2339
2340                         _extra_xml = new XMLNode (*child);
2341
2342                 } else if (child->name() == X_("controllable") && (prop = child->property("name")) != 0) {
2343                         
2344                         if (prop->value() == "solo") {
2345                                 _solo_control->set_state (*child);
2346                                 _session.add_controllable (_solo_control);
2347                         }
2348                         else if (prop->value() == "mute") {
2349                                 _mute_control->set_state (*child);
2350                                 _session.add_controllable (_mute_control);
2351                         }
2352                 }
2353                 else if (child->name() == X_("remote_control")) {
2354                         if ((prop = child->property (X_("id"))) != 0) {
2355                                 int32_t x;
2356                                 sscanf (prop->value().c_str(), "%d", &x);
2357                                 set_remote_control_id (x);
2358                         }
2359                 }
2360         }
2361
2362         if ((prop = node.property (X_("mix-group"))) != 0) {
2363                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
2364                 if (mix_group == 0) {
2365                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
2366                 }  else {
2367                         set_mix_group(mix_group, this);
2368                 }
2369         }
2370
2371         return 0;
2372 }
2373
2374 void
2375 Route::_set_processor_states(const XMLNodeList &nlist)
2376 {
2377         XMLNodeConstIterator niter;
2378         char buf[64];
2379
2380         ProcessorList::iterator i, o;
2381
2382         // Iterate through existing processors, remove those which are not in the state list
2383         for (i = _processors.begin(); i != _processors.end(); ) {
2384                 ProcessorList::iterator tmp = i;
2385                 ++tmp;
2386
2387                 bool processorInStateList = false;
2388         
2389                 (*i)->id().print (buf, sizeof (buf));
2390
2391
2392                 for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2393
2394                         // legacy sessions (IOProcessor as a child of Processor, both is-a IO)
2395                         if (strncmp(buf,(*niter)->child(X_("IOProcessor"))->child(X_("IO"))->property(X_("id"))->value().c_str(), sizeof(buf)) == 0) {
2396                                 processorInStateList = true;
2397                                 break;
2398                         } else if (strncmp(buf,(*niter)->property(X_("id"))->value().c_str(), sizeof(buf)) == 0) {
2399                                 processorInStateList = true;
2400                                 break;
2401                         }
2402                 }
2403                 
2404                 if (!processorInStateList) {
2405                         remove_processor (*i);
2406                 }
2407
2408
2409                 i = tmp;
2410         }
2411
2412
2413         // Iterate through state list and make sure all processors are on the track and in the correct order,
2414         // set the state of existing processors according to the new state on the same go
2415         i = _processors.begin();
2416         for (niter = nlist.begin(); niter != nlist.end(); ++niter, ++i) {
2417
2418                 // Check whether the next processor in the list 
2419                 o = i;
2420
2421                 while (o != _processors.end()) {
2422                         (*o)->id().print (buf, sizeof (buf));
2423                         if ( strncmp(buf, (*niter)->child(X_("IOProcessor"))->child(X_("IO"))->property(X_("id"))->value().c_str(), sizeof(buf)) == 0)
2424                                 break;
2425                         else if (strncmp(buf,(*niter)->property(X_("id"))->value().c_str(), sizeof(buf)) == 0)
2426                                 break;
2427                         
2428                         ++o;
2429                 }
2430
2431                 if (o == _processors.end()) {
2432                         // If the processor (*niter) is not on the route, we need to create it
2433                         // and move it to the correct location
2434
2435                         ProcessorList::iterator prev_last = _processors.end();
2436                         --prev_last; // We need this to check whether adding succeeded
2437                         
2438                         add_processor_from_xml (**niter);
2439
2440                         ProcessorList::iterator last = _processors.end();
2441                         --last;
2442
2443                         if (prev_last == last) {
2444                                 cerr << "Could not fully restore state as some processors were not possible to create" << endl;
2445                                 continue;
2446
2447                         }
2448
2449                         boost::shared_ptr<Processor> tmp = (*last);
2450                         // remove the processor from the wrong location
2451                         _processors.erase(last);
2452                         // processor the new processor at the current location
2453                         _processors.insert(i, tmp);
2454
2455                         --i; // move pointer to the newly processored processor
2456                         continue;
2457                 }
2458
2459                 // We found the processor (*niter) on the route, first we must make sure the processor
2460                 // is at the location provided in the XML state
2461                 if (i != o) {
2462                         boost::shared_ptr<Processor> tmp = (*o);
2463                         // remove the old copy
2464                         _processors.erase(o);
2465                         // processor the processor at the correct location
2466                         _processors.insert(i, tmp);
2467
2468                         --i; // move pointer so it points to the right processor
2469                 }
2470
2471                 (*i)->set_state( (**niter) );
2472         }
2473         
2474         processors_changed ();
2475 }
2476
2477 void
2478 Route::curve_reallocate ()
2479 {
2480 //      _gain_automation_curve.finish_resize ();
2481 //      _pan_automation_curve.finish_resize ();
2482 }
2483
2484 void
2485 Route::silence (nframes_t nframes, nframes_t offset)
2486 {
2487         if (!_silent) {
2488
2489                 IO::silence (nframes, offset);
2490
2491                 if (_control_outs) {
2492                         _control_outs->silence (nframes, offset);
2493                 }
2494
2495                 { 
2496                         Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2497                         
2498                         if (lm.locked()) {
2499                                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2500                                         boost::shared_ptr<PluginInsert> pi;
2501                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2502                                                 // skip plugins, they don't need anything when we're not active
2503                                                 continue;
2504                                         }
2505
2506                                         (*i)->silence (nframes, offset);
2507                                 }
2508
2509                                 if (nframes == _session.get_block_size() && offset == 0) {
2510                                         // _silent = true;
2511                                 }
2512                         }
2513                 }
2514                 
2515         }
2516 }       
2517
2518 int
2519 Route::set_control_outs (const vector<string>& ports)
2520 {
2521         Glib::Mutex::Lock lm (_control_outs_lock);
2522         vector<string>::const_iterator i;
2523         size_t limit;
2524         
2525         if (_control_outs) {
2526                 delete _control_outs;
2527                 _control_outs = 0;
2528         }
2529
2530         if (is_control() || is_master()) {
2531                 /* no control outs for these two special busses */
2532                 return 0;
2533         }
2534         
2535         if (ports.empty()) {
2536                 return 0;
2537         }
2538  
2539         string coutname = _name;
2540         coutname += _("[control]");
2541         
2542         _control_outs = new IO (_session, coutname);
2543
2544         /* our control outs need as many outputs as we
2545            have audio outputs. we track the changes in ::output_change_handler().
2546         */
2547         
2548         // XXX its stupid that we have to get this value twice
2549
2550         limit = n_outputs().n_audio();
2551         
2552         if (_control_outs->ensure_io (ChanCount::ZERO, ChanCount (DataType::AUDIO, n_outputs().get (DataType::AUDIO)), true, this)) {
2553                 return -1;
2554         }
2555         
2556         /* now connect to the named ports */
2557         
2558         for (size_t n = 0; n < limit; ++n) {
2559                 if (_control_outs->connect_output (_control_outs->output (n), ports[n % ports.size()], this)) {
2560                         error << string_compose (_("could not connect %1 to %2"), _control_outs->output(n)->name(), ports[n]) << endmsg;
2561                         return -1;
2562                 }
2563         }
2564  
2565         return 0;
2566 }       
2567
2568 void
2569 Route::set_edit_group (RouteGroup *eg, void *src)
2570
2571 {
2572         if (eg == _edit_group) {
2573                 return;
2574         }
2575
2576         if (_edit_group) {
2577                 _edit_group->remove (this);
2578         }
2579
2580         if ((_edit_group = eg) != 0) {
2581                 _edit_group->add (this);
2582         }
2583
2584         _session.set_dirty ();
2585         edit_group_changed (src); /* EMIT SIGNAL */
2586 }
2587
2588 void
2589 Route::drop_edit_group (void *src)
2590 {
2591         _edit_group = 0;
2592         _session.set_dirty ();
2593         edit_group_changed (src); /* EMIT SIGNAL */
2594 }
2595
2596 void
2597 Route::set_mix_group (RouteGroup *mg, void *src)
2598
2599 {
2600         if (mg == _mix_group) {
2601                 return;
2602         }
2603
2604         if (_mix_group) {
2605                 _mix_group->remove (this);
2606         }
2607
2608         if ((_mix_group = mg) != 0) {
2609                 _mix_group->add (this);
2610         }
2611
2612         _session.set_dirty ();
2613         mix_group_changed (src); /* EMIT SIGNAL */
2614 }
2615
2616 void
2617 Route::drop_mix_group (void *src)
2618 {
2619         _mix_group = 0;
2620         _session.set_dirty ();
2621         mix_group_changed (src); /* EMIT SIGNAL */
2622 }
2623
2624 void
2625 Route::set_comment (string cmt, void *src)
2626 {
2627         _comment = cmt;
2628         comment_changed (src);
2629         _session.set_dirty ();
2630 }
2631
2632 bool
2633 Route::feeds (boost::shared_ptr<Route> other)
2634 {
2635         uint32_t i, j;
2636
2637         IO& self = *this;
2638         uint32_t no = self.n_outputs().n_total();
2639         uint32_t ni = other->n_inputs ().n_total();
2640
2641         for (i = 0; i < no; ++i) {
2642                 for (j = 0; j < ni; ++j) {
2643                         if (self.output(i)->connected_to (other->input(j)->name())) {
2644                                 return true;
2645                         }
2646                 }
2647         }
2648
2649         /* check IOProcessors which may also interconnect Routes */
2650
2651         for (ProcessorList::iterator r = _processors.begin(); r != _processors.end(); r++) {
2652
2653                 boost::shared_ptr<IOProcessor> redirect = boost::dynamic_pointer_cast<IOProcessor>(*r);
2654
2655                 if ( ! redirect)
2656                         continue;
2657
2658                 // TODO: support internal redirects here
2659
2660                 no = redirect->io()->n_outputs().n_total();
2661
2662                 for (i = 0; i < no; ++i) {
2663                         for (j = 0; j < ni; ++j) {
2664                                 if (redirect->io()->output(i)->connected_to (other->input (j)->name())) {
2665                                         return true;
2666                                 }
2667                         }
2668                 }
2669         }
2670
2671         /* check for control room outputs which may also interconnect Routes */
2672
2673         if (_control_outs) {
2674
2675                 no = _control_outs->n_outputs().n_total();
2676                 
2677                 for (i = 0; i < no; ++i) {
2678                         for (j = 0; j < ni; ++j) {
2679                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
2680                                         return true;
2681                                 }
2682                         }
2683                 }
2684         }
2685
2686         return false;
2687 }
2688
2689 void
2690 Route::set_mute_config (mute_type t, bool onoff, void *src)
2691 {
2692         switch (t) {
2693         case PRE_FADER:
2694                 _mute_affects_pre_fader = onoff;
2695                  pre_fader_changed(src); /* EMIT SIGNAL */
2696                 break;
2697
2698         case POST_FADER:
2699                 _mute_affects_post_fader = onoff;
2700                  post_fader_changed(src); /* EMIT SIGNAL */
2701                 break;
2702
2703         case CONTROL_OUTS:
2704                 _mute_affects_control_outs = onoff;
2705                  control_outs_changed(src); /* EMIT SIGNAL */
2706                 break;
2707
2708         case MAIN_OUTS:
2709                 _mute_affects_main_outs = onoff;
2710                  main_outs_changed(src); /* EMIT SIGNAL */
2711                 break;
2712         }
2713 }
2714
2715 bool
2716 Route::get_mute_config (mute_type t)
2717 {
2718         bool onoff = false;
2719         
2720         switch (t){
2721         case PRE_FADER:
2722                 onoff = _mute_affects_pre_fader; 
2723                 break;
2724         case POST_FADER:
2725                 onoff = _mute_affects_post_fader;
2726                 break;
2727         case CONTROL_OUTS:
2728                 onoff = _mute_affects_control_outs;
2729                 break;
2730         case MAIN_OUTS:
2731                 onoff = _mute_affects_main_outs;
2732                 break;
2733         }
2734         
2735         return onoff;
2736 }
2737
2738 void
2739 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_processors)
2740 {
2741         nframes_t now = _session.transport_frame();
2742
2743         {
2744                 Glib::RWLock::ReaderLock lm (_processor_lock);
2745
2746                 if (!did_locate) {
2747                         automation_snapshot (now, true);
2748                 }
2749
2750                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2751                         
2752                         if (Config->get_plugins_stop_with_transport() && can_flush_processors) {
2753                                 (*i)->deactivate ();
2754                                 (*i)->activate ();
2755                         }
2756                         
2757                         (*i)->transport_stopped (now);
2758                 }
2759         }
2760
2761         IO::transport_stopped (now);
2762  
2763         _roll_delay = _initial_delay;
2764 }
2765
2766 void
2767 Route::input_change_handler (IOChange change, void *ignored)
2768 {
2769         if (change & ConfigurationChanged) {
2770                 reset_processor_counts (0);
2771         }
2772 }
2773
2774 void
2775 Route::output_change_handler (IOChange change, void *ignored)
2776 {
2777         if (change & ConfigurationChanged) {
2778                 if (_control_outs) {
2779                         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().n_audio()), true, this);
2780                 }
2781                 
2782                 reset_processor_counts (0);
2783         }
2784 }
2785
2786 uint32_t
2787 Route::pans_required () const
2788 {
2789         if (n_outputs().n_audio() < 2) {
2790                 return 0;
2791         }
2792         
2793         return max (n_inputs ().n_audio(), processor_max_outs.n_audio());
2794 }
2795
2796 int 
2797 Route::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2798                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2799 {
2800         if (n_outputs().n_total() == 0) {
2801                 return 0;
2802         }
2803
2804         if (session_state_changing || !_active)  {
2805                 silence (nframes, offset);
2806                 return 0;
2807         }
2808
2809         apply_gain_automation = false;
2810         
2811         if (n_inputs().n_total()) {
2812                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2813         } else {
2814                 silence (nframes, offset);
2815         }
2816
2817         return 0;
2818 }
2819
2820 nframes_t
2821 Route::check_initial_delay (nframes_t nframes, nframes_t& offset, nframes_t& transport_frame)
2822 {
2823         if (_roll_delay > nframes) {
2824
2825                 _roll_delay -= nframes;
2826                 silence (nframes, offset);
2827                 /* transport frame is not legal for caller to use */
2828                 return 0;
2829
2830         } else if (_roll_delay > 0) {
2831
2832                 nframes -= _roll_delay;
2833
2834                 silence (_roll_delay, offset);
2835
2836                 offset += _roll_delay;
2837                 transport_frame += _roll_delay;
2838
2839                 _roll_delay = 0;
2840         }
2841
2842         return nframes;
2843 }
2844
2845 int
2846 Route::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
2847              bool can_record, bool rec_monitors_input)
2848 {
2849         {
2850                 Glib::RWLock::ReaderLock lm (_processor_lock, Glib::TRY_LOCK);
2851                 if (lm.locked()) {
2852                         // automation snapshot can also be called from the non-rt context
2853                         // and it uses the processor list, so we take the lock out here
2854                         automation_snapshot (_session.transport_frame(), false);
2855                 }
2856         }
2857
2858         if ((n_outputs().n_total() == 0 && _processors.empty()) || n_inputs().n_total() == 0 || !_active) {
2859                 silence (nframes, offset);
2860                 return 0;
2861         }
2862         
2863         nframes_t unused = 0;
2864
2865         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2866                 return 0;
2867         }
2868
2869         _silent = false;
2870
2871         apply_gain_automation = false;
2872
2873         { 
2874                 Glib::Mutex::Lock am (data().control_lock(), Glib::TRY_LOCK);
2875                 
2876                 if (am.locked() && _session.transport_rolling()) {
2877                         
2878                         if (_gain_control->automation_playback()) {
2879                                 apply_gain_automation = _gain_control->list()->curve().rt_safe_get_vector (
2880                                                 start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2881                         }
2882                 }
2883         }
2884
2885         passthru (start_frame, end_frame, nframes, offset, declick, false);
2886
2887         return 0;
2888 }
2889
2890 int
2891 Route::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2892                     bool can_record, bool rec_monitors_input)
2893 {
2894         silence (nframes, offset);
2895         return 0;
2896 }
2897
2898 void
2899 Route::toggle_monitor_input ()
2900 {
2901         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2902                 i->ensure_monitor_input( ! i->monitoring_input());
2903         }
2904 }
2905
2906 bool
2907 Route::has_external_redirects () const
2908 {
2909         // FIXME: what about sends?
2910
2911         boost::shared_ptr<const PortInsert> pi;
2912         
2913         for (ProcessorList::const_iterator i = _processors.begin(); i != _processors.end(); ++i) {
2914                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2915
2916                         for (PortSet::const_iterator port = pi->io()->outputs().begin();
2917                                         port != pi->io()->outputs().end(); ++port) {
2918                                 
2919                                 string port_name = port->name();
2920                                 string client_name = port_name.substr (0, port_name.find(':'));
2921
2922                                 /* only say "yes" if the redirect is actually in use */
2923                                 
2924                                 if (client_name != "ardour" && pi->active()) {
2925                                         return true;
2926                                 }
2927                         }
2928                 }
2929         }
2930
2931         return false;
2932 }
2933
2934 void
2935 Route::flush_processors ()
2936 {
2937         /* XXX shouldn't really try to take this lock, since
2938            this is called from the RT audio thread.
2939         */
2940
2941         Glib::RWLock::ReaderLock lm (_processor_lock);
2942
2943         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2944                 (*i)->deactivate ();
2945                 (*i)->activate ();
2946         }
2947 }
2948
2949 void
2950 Route::set_meter_point (MeterPoint p, void *src)
2951 {
2952         if (_meter_point != p) {
2953                 _meter_point = p;
2954                  meter_change (src); /* EMIT SIGNAL */
2955                 _session.set_dirty ();
2956         }
2957 }
2958
2959 nframes_t
2960 Route::update_total_latency ()
2961 {
2962         nframes_t old = _own_latency;
2963
2964         if (_user_latency) {
2965                 _own_latency = _user_latency;
2966         } else {
2967                 _own_latency = 0;
2968
2969                 for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
2970                         if ((*i)->active ()) {
2971                                 _own_latency += (*i)->signal_latency ();
2972                         }
2973                 }
2974         }
2975
2976 #undef DEBUG_LATENCY
2977 #ifdef DEBUG_LATENCY
2978         cerr << _name << ": internal redirect latency = " << _own_latency << endl;
2979 #endif
2980
2981         set_port_latency (_own_latency);
2982         
2983         if (!_user_latency) {
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
2992                 _own_latency += input_latency ();
2993         }
2994
2995         if (old != _own_latency) {
2996                 signal_latency_changed (); /* EMIT SIGNAL */
2997         }
2998         
2999 #ifdef DEBUG_LATENCY
3000         cerr << _name << ": input latency = " << input_latency() << " total = "
3001              << _own_latency << endl;
3002 #endif
3003
3004         return _own_latency;
3005 }
3006
3007 void
3008 Route::set_user_latency (nframes_t nframes)
3009 {
3010         Latent::set_user_latency (nframes);
3011         _session.update_latency_compensation (false, false);
3012 }
3013
3014 void
3015 Route::set_latency_delay (nframes_t longest_session_latency)
3016 {
3017         nframes_t old = _initial_delay;
3018
3019         if (_own_latency < longest_session_latency) {
3020                 _initial_delay = longest_session_latency - _own_latency;
3021         } else {
3022                 _initial_delay = 0;
3023         }
3024
3025         if (_initial_delay != old) {
3026                 initial_delay_changed (); /* EMIT SIGNAL */
3027         }
3028
3029         if (_session.transport_stopped()) {
3030                 _roll_delay = _initial_delay;
3031         }
3032 }
3033
3034 void
3035 Route::automation_snapshot (nframes_t now, bool force)
3036 {
3037         if (!force && !should_snapshot(now)) {
3038                 return;
3039         }
3040
3041         IO::automation_snapshot (now, force);
3042
3043         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3044                 (*i)->automation_snapshot (now, force);
3045         }
3046 }
3047
3048 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
3049         : Controllable (name), route (s), type(tp)
3050 {
3051         
3052 }
3053
3054 void
3055 Route::ToggleControllable::set_value (float val)
3056 {
3057         bool bval = ((val >= 0.5f) ? true: false);
3058         
3059         switch (type) {
3060         case MuteControl:
3061                 route.set_mute (bval, this);
3062                 break;
3063         case SoloControl:
3064                 route.set_solo (bval, this);
3065                 break;
3066         default:
3067                 break;
3068         }
3069 }
3070
3071 float
3072 Route::ToggleControllable::get_value (void) const
3073 {
3074         float val = 0.0f;
3075         
3076         switch (type) {
3077         case MuteControl:
3078                 val = route.muted() ? 1.0f : 0.0f;
3079                 break;
3080         case SoloControl:
3081                 val = route.soloed() ? 1.0f : 0.0f;
3082                 break;
3083         default:
3084                 break;
3085         }
3086
3087         return val;
3088 }
3089
3090 void 
3091 Route::set_block_size (nframes_t nframes)
3092 {
3093         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i) {
3094                 (*i)->set_block_size (nframes);
3095         }
3096 }
3097
3098 void
3099 Route::protect_automation ()
3100 {
3101         Automatable::protect_automation();
3102         
3103         for (ProcessorList::iterator i = _processors.begin(); i != _processors.end(); ++i)
3104                 (*i)->protect_automation();
3105 }
3106
3107 void
3108 Route::set_pending_declick (int declick)
3109 {
3110         if (_declickable) {
3111                 /* this call is not allowed to turn off a pending declick unless "force" is true */
3112                 if (declick) {
3113                         _pending_declick = declick;
3114                 }
3115                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
3116         } else {
3117                 _pending_declick = 0;
3118         }
3119
3120 }
3121
3122 /** Shift automation forwards from a particular place, thereby inserting time.
3123  *  Adds undo commands for any shifts that are performed.
3124  *
3125  * @param pos Position to start shifting from.
3126  * @param frames Amount to shift forwards by.
3127  */
3128
3129 void
3130 Route::shift (nframes64_t pos, nframes64_t frames)
3131 {
3132 #ifdef THIS_NEEDS_FIXING_FOR_V3
3133
3134         /* gain automation */
3135         XMLNode &before = _gain_control->get_state ();
3136         _gain_control->shift (pos, frames);
3137         XMLNode &after = _gain_control->get_state ();
3138         _session.add_command (new MementoCommand<AutomationList> (_gain_automation_curve, &before, &after));
3139
3140         /* pan automation */
3141         for (std::vector<StreamPanner*>::iterator i = _panner->begin (); i != _panner->end (); ++i) {
3142                 Curve & c = (*i)->automation ();
3143                 XMLNode &before = c.get_state ();
3144                 c.shift (pos, frames);
3145                 XMLNode &after = c.get_state ();
3146                 _session.add_command (new MementoCommand<AutomationList> (c, &before, &after));
3147         }
3148
3149         /* redirect automation */
3150         {
3151                 Glib::RWLock::ReaderLock lm (redirect_lock);
3152                 for (RedirectList::iterator i = _redirects.begin (); i != _redirects.end (); ++i) {
3153                         
3154                         set<uint32_t> a;
3155                         (*i)->what_has_automation (a);
3156                         
3157                         for (set<uint32_t>::const_iterator j = a.begin (); j != a.end (); ++j) {
3158                                 AutomationList & al = (*i)->automation_list (*j);
3159                                 XMLNode &before = al.get_state ();
3160                                 al.shift (pos, frames);
3161                                 XMLNode &after = al.get_state ();
3162                                 _session.add_command (new MementoCommand<AutomationList> (al, &before, &after));
3163                         }
3164                 }
3165         }
3166 #endif
3167
3168 }