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