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