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