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