Merged with trunk R1705.
[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
28 #include <ardour/timestamps.h>
29 #include <ardour/audioengine.h>
30 #include <ardour/route.h>
31 #include <ardour/buffer.h>
32 #include <ardour/insert.h>
33 #include <ardour/send.h>
34 #include <ardour/session.h>
35 #include <ardour/utils.h>
36 #include <ardour/configuration.h>
37 #include <ardour/cycle_timer.h>
38 #include <ardour/route_group.h>
39 #include <ardour/port.h>
40 #include <ardour/audio_port.h>
41 #include <ardour/ladspa_plugin.h>
42 #include <ardour/panner.h>
43 #include <ardour/dB.h>
44 #include <ardour/mix.h>
45 #include <ardour/amp.h>
46 #include <ardour/meter.h>
47 #include <ardour/buffer_set.h>
48 #include "i18n.h"
49
50 using namespace std;
51 using namespace ARDOUR;
52 using namespace PBD;
53
54 uint32_t Route::order_key_cnt = 0;
55
56
57 Route::Route (Session& sess, string name, int input_min, int input_max, int output_min, int output_max, Flag flg, DataType default_type)
58         : IO (sess, name, input_min, input_max, output_min, output_max, default_type),
59           _flags (flg),
60           _solo_control (X_("solo"), *this, ToggleControllable::SoloControl),
61           _mute_control (X_("mute"), *this, ToggleControllable::MuteControl)
62 {
63         init ();
64 }
65
66 Route::Route (Session& sess, const XMLNode& node, DataType default_type)
67         : IO (sess, *node.child ("IO"), default_type),
68           _solo_control (X_("solo"), *this, ToggleControllable::SoloControl),
69           _mute_control (X_("mute"), *this, ToggleControllable::MuteControl)
70 {
71         init ();
72         _set_state (node, false);
73 }
74
75 void
76 Route::init ()
77 {
78         redirect_max_outs.reset();
79         _muted = false;
80         _soloed = false;
81         _solo_safe = false;
82         _phase_invert = false;
83         order_keys[strdup (N_("signal"))] = order_key_cnt++;
84         _active = true;
85         _silent = false;
86         _meter_point = MeterPostFader;
87         _initial_delay = 0;
88         _roll_delay = 0;
89         _own_latency = 0;
90         _have_internal_generator = false;
91         _declickable = false;
92         _pending_declick = true;
93         _remote_control_id = 0;
94         
95         _edit_group = 0;
96         _mix_group = 0;
97
98         _mute_affects_pre_fader = Config->get_mute_affects_pre_fader();
99         _mute_affects_post_fader = Config->get_mute_affects_post_fader();
100         _mute_affects_control_outs = Config->get_mute_affects_control_outs();
101         _mute_affects_main_outs = Config->get_mute_affects_main_outs();
102         
103         solo_gain = 1.0;
104         desired_solo_gain = 1.0;
105         mute_gain = 1.0;
106         desired_mute_gain = 1.0;
107
108         _control_outs = 0;
109
110         input_changed.connect (mem_fun (this, &Route::input_change_handler));
111         output_changed.connect (mem_fun (this, &Route::output_change_handler));
112 }
113
114 Route::~Route ()
115 {
116         clear_redirects (PreFader, this);
117         clear_redirects (PostFader, this);
118
119         for (OrderKeys::iterator i = order_keys.begin(); i != order_keys.end(); ++i) {
120                 free ((void*)(i->first));
121         }
122
123         if (_control_outs) {
124                 delete _control_outs;
125         }
126 }
127
128 void
129 Route::set_remote_control_id (uint32_t id)
130 {
131         if (id != _remote_control_id) {
132                 _remote_control_id = id;
133                 RemoteControlIDChanged ();
134         }
135 }
136
137 uint32_t
138 Route::remote_control_id() const
139 {
140         return _remote_control_id;
141 }
142
143 long
144 Route::order_key (const char* name) const
145 {
146         OrderKeys::const_iterator i;
147         
148         for (i = order_keys.begin(); i != order_keys.end(); ++i) {
149                 if (!strcmp (name, i->first)) {
150                         return i->second;
151                 }
152         }
153
154         return -1;
155 }
156
157 void
158 Route::set_order_key (const char* name, long n)
159 {
160         order_keys[strdup(name)] = n;
161         _session.set_dirty ();
162 }
163
164 void
165 Route::inc_gain (gain_t fraction, void *src)
166 {
167         IO::inc_gain (fraction, src);
168 }
169
170 void
171 Route::set_gain (gain_t val, void *src)
172 {
173         if (src != 0 && _mix_group && src != _mix_group && _mix_group->is_active()) {
174                 
175                 if (_mix_group->is_relative()) {
176                         
177                         
178                         gain_t usable_gain  = gain();
179                         if (usable_gain < 0.000001f) {
180                                 usable_gain=0.000001f;
181                         }
182                                                 
183                         gain_t delta = val;
184                         if (delta < 0.000001f) {
185                                 delta=0.000001f;
186                         }
187
188                         delta -= usable_gain;
189
190                         if (delta == 0.0f) return;
191
192                         gain_t factor = delta / usable_gain;
193
194                         if (factor > 0.0f) {
195                                 factor = _mix_group->get_max_factor(factor);
196                                 if (factor == 0.0f) {
197                                         gain_changed (src);
198                                         return;
199                                 }
200                         } else {
201                                 factor = _mix_group->get_min_factor(factor);
202                                 if (factor == 0.0f) {
203                                         gain_changed (src);
204                                         return;
205                                 }
206                         }
207                                         
208                         _mix_group->apply (&Route::inc_gain, factor, _mix_group);
209
210                 } else {
211                         
212                         _mix_group->apply (&Route::set_gain, val, _mix_group);
213                 }
214
215                 return;
216         } 
217
218         if (val == gain()) {
219                 return;
220         }
221
222         IO::set_gain (val, src);
223 }
224
225 /** Process this route for one (sub) cycle (process thread)
226  *
227  * @param bufs Scratch buffers to use for the signal path
228  * @param start_frame Initial transport frame 
229  * @param end_frame Final transport frame
230  * @param nframes Number of frames to output (to ports)
231  * @param offset Output offset (of port buffers, for split cycles)
232  *
233  * Note that (end_frame - start_frame) may not be equal to nframes when the
234  * transport speed isn't 1.0 (eg varispeed).
235  */
236 void
237 Route::process_output_buffers (BufferSet& bufs,
238                 nframes_t start_frame, nframes_t end_frame, 
239         nframes_t nframes, nframes_t offset, bool with_redirects, int declick,
240                 bool meter)
241 {
242         // This is definitely very audio-only for now
243         assert(_default_type == DataType::AUDIO);
244         
245         RedirectList::iterator i;
246         bool post_fader_work = false;
247         bool mute_declick_applied = false;
248         gain_t dmg, dsg, dg;
249         IO *co;
250         bool mute_audible;
251         bool solo_audible;
252         bool no_monitor;
253         gain_t* gab = _session.gain_automation_buffer();
254
255         switch (Config->get_monitoring_model()) {
256         case HardwareMonitoring:
257         case ExternalMonitoring:
258                 no_monitor = true;
259                 break;
260         default:
261                 no_monitor = false;
262         }
263
264         declick = _pending_declick;
265
266         {
267                 Glib::Mutex::Lock cm (control_outs_lock, Glib::TRY_LOCK);
268                 
269                 if (cm.locked()) {
270                         co = _control_outs;
271                 } else {
272                         co = 0;
273                 }
274         }
275         
276         { 
277                 Glib::Mutex::Lock dm (declick_lock, Glib::TRY_LOCK);
278                 
279                 if (dm.locked()) {
280                         dmg = desired_mute_gain;
281                         dsg = desired_solo_gain;
282                         dg = _desired_gain;
283                 } else {
284                         dmg = mute_gain;
285                         dsg = solo_gain;
286                         dg = _gain;
287                 }
288         }
289
290         /* ----------------------------------------------------------------------------------------------------
291            GLOBAL DECLICK (for transport changes etc.)
292            -------------------------------------------------------------------------------------------------- */
293
294         if (declick > 0) {
295                 Amp::run (bufs, nframes, 0.0, 1.0, false);
296                 _pending_declick = 0;
297         } else if (declick < 0) {
298                 Amp::run (bufs, nframes, 1.0, 0.0, false);
299                 _pending_declick = 0;
300         } else {
301
302                 /* no global declick */
303
304                 if (solo_gain != dsg) {
305                         Amp::run (bufs, nframes, solo_gain, dsg, false);
306                         solo_gain = dsg;
307                 }
308         }
309
310
311         /* ----------------------------------------------------------------------------------------------------
312            INPUT METERING & MONITORING
313            -------------------------------------------------------------------------------------------------- */
314
315         if (meter && (_meter_point == MeterInput)) {
316                 _meter->run(bufs, nframes);
317         }
318
319         if (!_soloed && _mute_affects_pre_fader && (mute_gain != dmg)) {
320                 Amp::run (bufs, nframes, mute_gain, dmg, false);
321                 mute_gain = dmg;
322                 mute_declick_applied = true;
323         }
324
325         if ((_meter_point == MeterInput) && co) {
326                 
327                 solo_audible = dsg > 0;
328                 mute_audible = dmg > 0;// || !_mute_affects_pre_fader;
329                 
330                 if (    // muted by solo of another track
331                         
332                         !solo_audible || 
333                         
334                         // muted by mute of this track 
335                         
336                         !mute_audible ||
337                         
338                         // rec-enabled but not s/w monitoring 
339                         
340                         // TODO: this is probably wrong
341
342                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
343
344                         ) {
345                         
346                         co->silence (nframes, offset);
347                         
348                 } else {
349
350                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
351                         
352                 } 
353         } 
354
355         /* ---------------------------------------------------------------------------------------------------
356            PRE-FADER REDIRECTS
357            -------------------------------------------------------------------------------------------------- */
358
359         /* FIXME: Somewhere in these loops is where bufs.count() should go from n_inputs() to redirect_max_outs()
360          * (if they differ).  Something explicit needs to be done here to make sure the list of redirects will
361          * give us what we need (possibly by inserting transparent 'translators' into the list to make it work) */
362
363         if (with_redirects) {
364                 Glib::RWLock::ReaderLock rm (redirect_lock, Glib::TRY_LOCK);
365                 if (rm.locked()) {
366                         if (mute_gain > 0 || !_mute_affects_pre_fader) {
367                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
368                                         switch ((*i)->placement()) {
369                                         case PreFader:
370                                                 (*i)->run (bufs, start_frame, end_frame, nframes, offset);
371                                                 break;
372                                         case PostFader:
373                                                 post_fader_work = true;
374                                                 break;
375                                         }
376                                 }
377                         } else {
378                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
379                                         switch ((*i)->placement()) {
380                                         case PreFader:
381                                                 (*i)->silence (nframes, offset);
382                                                 break;
383                                         case PostFader:
384                                                 post_fader_work = true;
385                                                 break;
386                                         }
387                                 }
388                         }
389                 } 
390         }
391
392         // FIXME: for now, just hope the redirects list did what it was supposed to
393         bufs.set_count(n_process_buffers());
394
395         
396         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_post_fader) {
397                 Amp::run (bufs, nframes, mute_gain, dmg, false);
398                 mute_gain = dmg;
399                 mute_declick_applied = true;
400         }
401
402         /* ----------------------------------------------------------------------------------------------------
403            PRE-FADER METERING & MONITORING
404            -------------------------------------------------------------------------------------------------- */
405
406         if (meter && (_meter_point == MeterPreFader)) {
407                 _meter->run(bufs, nframes);
408         }
409
410         
411         if ((_meter_point == MeterPreFader) && co) {
412                 
413                 solo_audible = dsg > 0;
414                 mute_audible = dmg > 0 || !_mute_affects_pre_fader;
415                 
416                 if ( // muted by solo of another track
417                         
418                         !solo_audible || 
419                         
420                         // muted by mute of this track 
421                         
422                         !mute_audible ||
423                         
424                         // rec-enabled but not s/w monitoring 
425                         
426                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
427
428                         ) {
429                         
430                         co->silence (nframes, offset);
431                         
432                 } else {
433
434                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
435                         
436                 } 
437         } 
438         
439         /* ----------------------------------------------------------------------------------------------------
440            GAIN STAGE
441            -------------------------------------------------------------------------------------------------- */
442
443         /* if not recording or recording and requiring any monitor signal, then apply gain */
444
445         if ( // not recording 
446
447                 !(record_enabled() && _session.actively_recording()) || 
448                 
449             // OR recording 
450                 
451                 // h/w monitoring not in use 
452                 
453                 (!Config->get_monitoring_model() == HardwareMonitoring && 
454
455                  // AND software monitoring required
456
457                  Config->get_monitoring_model() == SoftwareMonitoring)) { 
458                 
459                 if (apply_gain_automation) {
460                         
461                         if (_phase_invert) {
462                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
463                                         Sample* const sp = i->data(nframes);
464                                         
465                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
466                                                 sp[nx] *= -gab[nx];
467                                         }
468                                 }
469                         } else {
470                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
471                                         Sample* const sp = i->data(nframes);
472                                         
473                                         for (nframes_t nx = 0; nx < nframes; ++nx) {
474                                                 sp[nx] *= gab[nx];
475                                         }
476                                 }
477                         }
478                         
479                         if (apply_gain_automation && _session.transport_rolling() && nframes > 0) {
480                                 _effective_gain = gab[nframes-1];
481                         }
482                         
483                 } else {
484                         
485                         /* manual (scalar) gain */
486                         
487                         if (_gain != dg) {
488                                 
489                                 Amp::run (bufs, nframes, _gain, dg, _phase_invert);
490                                 _gain = dg;
491                                 
492                         } else if (_gain != 0 && (_phase_invert || _gain != 1.0)) {
493                                 
494                                 /* no need to interpolate current gain value,
495                                    but its non-unity, so apply it. if the gain
496                                    is zero, do nothing because we'll ship silence
497                                    below.
498                                 */
499
500                                 gain_t this_gain;
501                                 
502                                 if (_phase_invert) {
503                                         this_gain = -_gain;
504                                 } else {
505                                         this_gain = _gain;
506                                 }
507                                 
508                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
509                                         Sample* const sp = i->data(nframes);
510                                         Session::apply_gain_to_buffer(sp,nframes,this_gain);
511                                 }
512
513                         } else if (_gain == 0) {
514                                 for (BufferSet::audio_iterator i = bufs.audio_begin(); i != bufs.audio_end(); ++i) {
515                                         i->clear();
516                                 }
517                         }
518                 }
519
520         } else {
521
522                 /* actively recording, no monitoring required; leave buffers as-is to save CPU cycles */
523
524         }
525
526         /* ----------------------------------------------------------------------------------------------------
527            POST-FADER REDIRECTS
528            -------------------------------------------------------------------------------------------------- */
529
530         /* note that post_fader_work cannot be true unless with_redirects was also true, so don't test both */
531
532         if (post_fader_work) {
533
534                 Glib::RWLock::ReaderLock rm (redirect_lock, Glib::TRY_LOCK);
535                 if (rm.locked()) {
536                         if (mute_gain > 0 || !_mute_affects_post_fader) {
537                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
538                                         switch ((*i)->placement()) {
539                                         case PreFader:
540                                                 break;
541                                         case PostFader:
542                                                 (*i)->run (bufs, start_frame, end_frame, nframes, offset);
543                                                 break;
544                                         }
545                                 }
546                         } else {
547                                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
548                                         switch ((*i)->placement()) {
549                                         case PreFader:
550                                                 break;
551                                         case PostFader:
552                                                 (*i)->silence (nframes, offset);
553                                                 break;
554                                         }
555                                 }
556                         }
557                 } 
558         }
559
560         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_control_outs) {
561                 Amp::run (bufs, nframes, mute_gain, dmg, false);
562                 mute_gain = dmg;
563                 mute_declick_applied = true;
564         }
565
566         /* ----------------------------------------------------------------------------------------------------
567            CONTROL OUTPUT STAGE
568            -------------------------------------------------------------------------------------------------- */
569
570         if ((_meter_point == MeterPostFader) && co) {
571                 
572                 solo_audible = solo_gain > 0;
573                 mute_audible = dmg > 0 || !_mute_affects_control_outs;
574
575                 if ( // silent anyway
576
577                         (_gain == 0 && !apply_gain_automation) || 
578                     
579                      // muted by solo of another track
580
581                         !solo_audible || 
582                     
583                      // muted by mute of this track 
584
585                         !mute_audible ||
586
587                     // recording but not s/w monitoring 
588                         
589                         (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording()))
590
591                         ) {
592
593                         co->silence (nframes, offset);
594                         
595                 } else {
596
597                         co->deliver_output (bufs, start_frame, end_frame, nframes, offset);
598                 } 
599         } 
600
601         /* ----------------------------------------------------------------------
602            GLOBAL MUTE 
603            ----------------------------------------------------------------------*/
604
605         if (!_soloed && (mute_gain != dmg) && !mute_declick_applied && _mute_affects_main_outs) {
606                 Amp::run (bufs, nframes, mute_gain, dmg, false);
607                 mute_gain = dmg;
608                 mute_declick_applied = true;
609         }
610         
611         /* ----------------------------------------------------------------------------------------------------
612            MAIN OUTPUT STAGE
613            -------------------------------------------------------------------------------------------------- */
614
615         solo_audible = dsg > 0;
616         mute_audible = dmg > 0 || !_mute_affects_main_outs;
617         
618         if (n_outputs().get(_default_type) == 0) {
619             
620             /* relax */
621
622         } else if (no_monitor && record_enabled() && (!Config->get_auto_input() || _session.actively_recording())) {
623                 
624                 IO::silence (nframes, offset);
625                 
626         } else {
627
628                 if ( // silent anyway
629
630                     (_gain == 0 && !apply_gain_automation) ||
631                     
632                     // muted by solo of another track, but not using control outs for solo
633
634                     (!solo_audible && (Config->get_solo_model() != SoloBus)) ||
635                     
636                     // muted by mute of this track
637
638                     !mute_audible
639
640                         ) {
641
642                         /* don't use Route::silence() here, because that causes
643                            all outputs (sends, port inserts, etc. to be silent).
644                         */
645                         
646                         if (_meter_point == MeterPostFader) {
647                                 peak_meter().reset();
648                         }
649                         
650                         IO::silence (nframes, offset);
651                         
652                 } else {
653                         
654                         deliver_output(bufs, start_frame, end_frame, nframes, offset);
655
656                 }
657
658         }
659
660         /* ----------------------------------------------------------------------------------------------------
661            POST-FADER METERING
662            -------------------------------------------------------------------------------------------------- */
663
664         if (meter && (_meter_point == MeterPostFader)) {
665                 if ((_gain == 0 && !apply_gain_automation) || dmg == 0) {
666                         _meter->reset();
667                 } else {
668                         _meter->run(output_buffers(), nframes, offset);
669                 }
670         }
671 }
672
673 ChanCount
674 Route::n_process_buffers ()
675 {
676         return max (n_inputs(), redirect_max_outs);
677 }
678
679 void
680 Route::passthru (nframes_t start_frame, nframes_t end_frame, nframes_t nframes, nframes_t offset, int declick, bool meter_first)
681 {
682         BufferSet& bufs = _session.get_scratch_buffers(n_process_buffers());
683
684         _silent = false;
685
686         collect_input (bufs, nframes, offset);
687
688 #define meter_stream meter_first
689
690         if (meter_first) {
691                 _meter->run(bufs, nframes);
692                 meter_stream = false;
693         } else {
694                 meter_stream = true;
695         }
696                 
697         process_output_buffers (bufs, start_frame, end_frame, nframes, offset, true, declick, meter_stream);
698
699 #undef meter_stream
700 }
701
702 void
703 Route::passthru_silence (jack_nframes_t start_frame, jack_nframes_t end_frame, jack_nframes_t nframes, jack_nframes_t offset, int declick, bool meter)
704 {
705         process_output_buffers (_session.get_silent_buffers (n_process_buffers()), start_frame, end_frame, nframes, offset, true, declick, meter);
706 }
707
708 void
709 Route::set_solo (bool yn, void *src)
710 {
711         if (_solo_safe) {
712                 return;
713         }
714
715         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
716                 _mix_group->apply (&Route::set_solo, yn, _mix_group);
717                 return;
718         }
719
720         if (_soloed != yn) {
721                 _soloed = yn;
722                 solo_changed (src); /* EMIT SIGNAL */
723                 _solo_control.Changed (); /* EMIT SIGNAL */
724         }
725 }
726
727 void
728 Route::set_solo_mute (bool yn)
729 {
730         Glib::Mutex::Lock lm (declick_lock);
731
732         /* Called by Session in response to another Route being soloed.
733          */
734            
735         desired_solo_gain = (yn?0.0:1.0);
736 }
737
738 void
739 Route::set_solo_safe (bool yn, void *src)
740 {
741         if (_solo_safe != yn) {
742                 _solo_safe = yn;
743                  solo_safe_changed (src); /* EMIT SIGNAL */
744         }
745 }
746
747 void
748 Route::set_mute (bool yn, void *src)
749
750 {
751         if (_mix_group && src != _mix_group && _mix_group->is_active()) {
752                 _mix_group->apply (&Route::set_mute, yn, _mix_group);
753                 return;
754         }
755
756         if (_muted != yn) {
757                 _muted = yn;
758                 mute_changed (src); /* EMIT SIGNAL */
759                 
760                 _mute_control.Changed (); /* EMIT SIGNAL */
761                 
762                 Glib::Mutex::Lock lm (declick_lock);
763                 desired_mute_gain = (yn?0.0f:1.0f);
764         }
765 }
766
767 int
768 Route::add_redirect (boost::shared_ptr<Redirect> redirect, void *src, uint32_t* err_streams)
769 {
770         ChanCount old_rmo = redirect_max_outs;
771
772         if (!_session.engine().connected()) {
773                 return 1;
774         }
775
776         {
777                 Glib::RWLock::WriterLock lm (redirect_lock);
778
779                 boost::shared_ptr<PluginInsert> pi;
780                 boost::shared_ptr<PortInsert> porti;
781
782                 redirect->set_default_type(_default_type);
783
784                 if ((pi = boost::dynamic_pointer_cast<PluginInsert>(redirect)) != 0) {
785                         pi->set_count (1);
786
787                         if (pi->input_streams() == ChanCount::ZERO) {
788                                 /* generator plugin */
789                                 _have_internal_generator = true;
790                         }
791                         
792                 } else if ((porti = boost::dynamic_pointer_cast<PortInsert>(redirect)) != 0) {
793
794                         /* force new port inserts to start out with an i/o configuration
795                            that matches this route's i/o configuration.
796
797                            the "inputs" for the port are supposed to match the output
798                            of this route.
799
800                            the "outputs" of the route should match the inputs of this
801                            route. XXX shouldn't they match the number of active signal
802                            streams at the point of insertion?
803                         */
804                         // FIXME: (yes, they should)
805
806                         porti->ensure_io (n_outputs (), n_inputs(), false, this);
807                 }
808                 
809                 // Ensure peak vector sizes before the plugin is activated
810                 ChanCount potential_max_streams = max(redirect->input_streams(), redirect->output_streams());
811                 _meter->setup(potential_max_streams);
812
813                 _redirects.push_back (redirect);
814
815                 if (_reset_plugin_counts (err_streams)) {
816                         _redirects.pop_back ();
817                         _reset_plugin_counts (0); // it worked before we tried to add it ...
818                         return -1;
819                 }
820
821                 redirect->activate ();
822                 redirect->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
823         }
824         
825         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
826                 reset_panner ();
827         }
828
829
830         redirects_changed (src); /* EMIT SIGNAL */
831         return 0;
832 }
833
834 int
835 Route::add_redirects (const RedirectList& others, void *src, uint32_t* err_streams)
836 {
837         ChanCount old_rmo = redirect_max_outs;
838
839         if (!_session.engine().connected()) {
840                 return 1;
841         }
842
843         {
844                 Glib::RWLock::WriterLock lm (redirect_lock);
845
846                 RedirectList::iterator existing_end = _redirects.end();
847                 --existing_end;
848
849                 ChanCount potential_max_streams;
850
851                 for (RedirectList::const_iterator i = others.begin(); i != others.end(); ++i) {
852                         
853                         boost::shared_ptr<PluginInsert> pi;
854                         
855                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
856                                 pi->set_count (1);
857                                 
858                                 ChanCount m = max(pi->input_streams(), pi->output_streams());
859                                 if (m > potential_max_streams)
860                                         potential_max_streams = m;
861                         }
862
863                         // Ensure peak vector sizes before the plugin is activated
864                         _meter->setup(potential_max_streams);
865
866                         _redirects.push_back (*i);
867                         
868                         if (_reset_plugin_counts (err_streams)) {
869                                 ++existing_end;
870                                 _redirects.erase (existing_end, _redirects.end());
871                                 _reset_plugin_counts (0); // it worked before we tried to add it ...
872                                 return -1;
873                         }
874                         
875                         (*i)->activate ();
876                         (*i)->active_changed.connect (mem_fun (*this, &Route::redirect_active_proxy));
877                 }
878         }
879         
880         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
881                 reset_panner ();
882         }
883
884         redirects_changed (src); /* EMIT SIGNAL */
885         return 0;
886 }
887
888 /** Remove redirects with a given placement.
889  * @param p Placement of redirects to remove.
890  */
891 void
892 Route::clear_redirects (Placement p, void *src)
893 {
894         const ChanCount old_rmo = redirect_max_outs;
895
896         if (!_session.engine().connected()) {
897                 return;
898         }
899
900         {
901                 Glib::RWLock::WriterLock lm (redirect_lock);
902                 RedirectList new_list;
903                 
904                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
905                         if ((*i)->placement() == p) {
906                                 /* it's the placement we want to get rid of */
907                                 (*i)->drop_references ();
908                         } else {
909                                 /* it's a different placement, so keep it */
910                                 new_list.push_back (*i);
911                         }
912                 }
913                 
914                 _redirects = new_list;
915         }
916
917         /* FIXME: can't see how this test can ever fire */
918         if (redirect_max_outs != old_rmo) {
919                 reset_panner ();
920         }
921         
922         redirect_max_outs.reset();
923         _have_internal_generator = false;
924         redirects_changed (src); /* EMIT SIGNAL */
925 }
926
927 int
928 Route::remove_redirect (boost::shared_ptr<Redirect> redirect, void *src, uint32_t* err_streams)
929 {
930         ChanCount old_rmo = redirect_max_outs;
931
932         if (!_session.engine().connected()) {
933                 return 1;
934         }
935
936         redirect_max_outs.reset();
937
938         {
939                 Glib::RWLock::WriterLock lm (redirect_lock);
940                 RedirectList::iterator i;
941                 bool removed = false;
942
943                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
944                         if (*i == redirect) {
945
946                                 RedirectList::iterator tmp;
947
948                                 /* move along, see failure case for reset_plugin_counts()
949                                    where we may need to reinsert the redirect.
950                                 */
951
952                                 tmp = i;
953                                 ++tmp;
954
955                                 /* stop redirects that send signals to JACK ports
956                                    from causing noise as a result of no longer being
957                                    run.
958                                 */
959
960                                 boost::shared_ptr<Send> send;
961                                 boost::shared_ptr<PortInsert> port_insert;
962                                 
963                                 if ((send = boost::dynamic_pointer_cast<Send> (*i)) != 0) {
964                                         send->disconnect_inputs (this);
965                                         send->disconnect_outputs (this);
966                                 } else if ((port_insert = boost::dynamic_pointer_cast<PortInsert> (*i)) != 0) {
967                                         port_insert->disconnect_inputs (this);
968                                         port_insert->disconnect_outputs (this);
969                                 }
970
971                                 _redirects.erase (i);
972
973                                 i = tmp;
974                                 removed = true;
975                                 break;
976                         }
977                 }
978
979                 if (!removed) {
980                         /* what? */
981                         return 1;
982                 }
983
984                 if (_reset_plugin_counts (err_streams)) {
985                         /* get back to where we where */
986                         _redirects.insert (i, redirect);
987                         /* we know this will work, because it worked before :) */
988                         _reset_plugin_counts (0);
989                         return -1;
990                 }
991
992                 bool foo = false;
993
994                 for (i = _redirects.begin(); i != _redirects.end(); ++i) {
995                         boost::shared_ptr<PluginInsert> pi;
996                         
997                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(*i)) != 0) {
998                                 if (pi->is_generator()) {
999                                         foo = true;
1000                                 }
1001                         }
1002                 }
1003
1004                 _have_internal_generator = foo;
1005         }
1006
1007         if (old_rmo != redirect_max_outs) {
1008                 reset_panner ();
1009         }
1010
1011         redirect->drop_references ();
1012
1013         redirects_changed (src); /* EMIT SIGNAL */
1014         return 0;
1015 }
1016
1017 int
1018 Route::reset_plugin_counts (uint32_t* lpc)
1019 {
1020         Glib::RWLock::WriterLock lm (redirect_lock);
1021         return _reset_plugin_counts (lpc);
1022 }
1023
1024
1025 int
1026 Route::_reset_plugin_counts (uint32_t* err_streams)
1027 {
1028         RedirectList::iterator r;
1029         uint32_t i_cnt;
1030         uint32_t s_cnt;
1031         map<Placement,list<InsertCount> > insert_map;
1032         nframes_t initial_streams;
1033
1034         redirect_max_outs.reset();
1035         i_cnt = 0;
1036         s_cnt = 0;
1037
1038         /* divide inserts up by placement so we get the signal flow
1039            properly modelled. we need to do this because the _redirects
1040            list is not sorted by placement, and because other reasons may 
1041            exist now or in the future for this separate treatment.
1042         */
1043         
1044         for (r = _redirects.begin(); r != _redirects.end(); ++r) {
1045
1046                 boost::shared_ptr<Insert> insert;
1047
1048                 /* do this here in case we bomb out before we get to the end of
1049                    this function.
1050                 */
1051
1052                 redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1053
1054                 if ((insert = boost::dynamic_pointer_cast<Insert>(*r)) != 0) {
1055                         ++i_cnt;
1056                         insert_map[insert->placement()].push_back (InsertCount (insert));
1057
1058                         /* reset plugin counts back to one for now so
1059                            that we have a predictable, controlled
1060                            state to try to configure.
1061                         */
1062
1063                         boost::shared_ptr<PluginInsert> pi;
1064                 
1065                         if ((pi = boost::dynamic_pointer_cast<PluginInsert>(insert)) != 0) {
1066                                 pi->set_count (1);
1067                         }
1068
1069                 } else if (boost::dynamic_pointer_cast<Send> (*r) != 0) {
1070                         ++s_cnt;
1071                 }
1072         }
1073         
1074         if (i_cnt == 0) {
1075                 if (s_cnt) {
1076                         goto recompute;
1077                 } else {
1078                         return 0;
1079                 }
1080         }
1081
1082         /* Now process each placement in order, checking to see if we 
1083            can really do what has been requested.
1084         */
1085
1086         /* A: PreFader */
1087         
1088         if (check_some_plugin_counts (insert_map[PreFader], n_inputs ().get(_default_type), err_streams)) {
1089                 return -1;
1090         }
1091
1092         /* figure out the streams that will feed into PreFader */
1093
1094         if (!insert_map[PreFader].empty()) {
1095                 InsertCount& ic (insert_map[PreFader].back());
1096                 initial_streams = ic.insert->compute_output_streams (ic.cnt);
1097         } else {
1098                 initial_streams = n_inputs ().get(_default_type);
1099         }
1100
1101         /* B: PostFader */
1102
1103         if (check_some_plugin_counts (insert_map[PostFader], initial_streams, err_streams)) {
1104                 return -1;
1105         }
1106
1107         /* OK, everything can be set up correctly, so lets do it */
1108
1109         apply_some_plugin_counts (insert_map[PreFader]);
1110         apply_some_plugin_counts (insert_map[PostFader]);
1111
1112         /* recompute max outs of any redirect */
1113
1114   recompute:
1115
1116         redirect_max_outs.reset();
1117         RedirectList::iterator prev = _redirects.end();
1118
1119         for (r = _redirects.begin(); r != _redirects.end(); prev = r, ++r) {
1120                 boost::shared_ptr<Send> s;
1121
1122                 if ((s = boost::dynamic_pointer_cast<Send> (*r)) != 0) {
1123                         if (r == _redirects.begin()) {
1124                                 s->expect_inputs (n_inputs());
1125                         } else {
1126                                 s->expect_inputs ((*prev)->output_streams());
1127                         }
1128
1129                 } else {
1130                         
1131                         /* don't pay any attention to send output configuration, since it doesn't
1132                            affect the route.
1133                          */
1134
1135                         redirect_max_outs = max ((*r)->output_streams (), redirect_max_outs);
1136                         
1137                 }
1138         }
1139
1140         /* we're done */
1141
1142         return 0;
1143 }                                  
1144
1145 int32_t
1146 Route::apply_some_plugin_counts (list<InsertCount>& iclist)
1147 {
1148         list<InsertCount>::iterator i;
1149
1150         for (i = iclist.begin(); i != iclist.end(); ++i) {
1151                 
1152                 if ((*i).insert->configure_io ((*i).cnt, (*i).in, (*i).out)) {
1153                         return -1;
1154                 }
1155                 /* make sure that however many we have, they are all active */
1156                 (*i).insert->activate ();
1157         }
1158
1159         return 0;
1160 }
1161
1162 int32_t
1163 Route::check_some_plugin_counts (list<InsertCount>& iclist, int32_t required_inputs, uint32_t* err_streams)
1164 {
1165         list<InsertCount>::iterator i;
1166         
1167         for (i = iclist.begin(); i != iclist.end(); ++i) {
1168
1169                 if (((*i).cnt = (*i).insert->can_support_input_configuration (required_inputs)) < 0) {
1170                         if (err_streams) {
1171                                 *err_streams = required_inputs;
1172                         }
1173                         return -1;
1174                 }
1175                 
1176                 (*i).in = required_inputs;
1177                 (*i).out = (*i).insert->compute_output_streams ((*i).cnt);
1178
1179                 required_inputs = (*i).out;
1180         }
1181
1182         return 0;
1183 }
1184
1185 int
1186 Route::copy_redirects (const Route& other, Placement placement, uint32_t* err_streams)
1187 {
1188         ChanCount old_rmo = redirect_max_outs;
1189
1190         if (err_streams) {
1191                 *err_streams = 0;
1192         }
1193
1194         RedirectList to_be_deleted;
1195
1196         {
1197                 Glib::RWLock::WriterLock lm (redirect_lock);
1198                 RedirectList::iterator tmp;
1199                 RedirectList the_copy;
1200
1201                 the_copy = _redirects;
1202                 
1203                 /* remove all relevant redirects */
1204
1205                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1206                         tmp = i;
1207                         ++tmp;
1208
1209                         if ((*i)->placement() == placement) {
1210                                 to_be_deleted.push_back (*i);
1211                                 _redirects.erase (i);
1212                         }
1213
1214                         i = tmp;
1215                 }
1216
1217                 /* now copy the relevant ones from "other" */
1218                 
1219                 for (RedirectList::const_iterator i = other._redirects.begin(); i != other._redirects.end(); ++i) {
1220                         if ((*i)->placement() == placement) {
1221                                 _redirects.push_back (Redirect::clone (*i));
1222                         }
1223                 }
1224
1225                 /* reset plugin stream handling */
1226
1227                 if (_reset_plugin_counts (err_streams)) {
1228
1229                         /* FAILED COPY ATTEMPT: we have to restore order */
1230
1231                         /* delete all cloned redirects */
1232
1233                         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ) {
1234
1235                                 tmp = i;
1236                                 ++tmp;
1237
1238                                 if ((*i)->placement() == placement) {
1239                                         _redirects.erase (i);
1240                                 }
1241                                 
1242                                 i = tmp;
1243                         }
1244
1245                         /* restore the natural order */
1246
1247                         _redirects = the_copy;
1248                         redirect_max_outs = old_rmo;
1249
1250                         /* we failed, even though things are OK again */
1251
1252                         return -1;
1253
1254                 } else {
1255                         
1256                         /* SUCCESSFUL COPY ATTEMPT: delete the redirects we removed pre-copy */
1257                         to_be_deleted.clear ();
1258                 }
1259         }
1260
1261         if (redirect_max_outs != old_rmo || old_rmo == ChanCount::ZERO) {
1262                 reset_panner ();
1263         }
1264
1265         redirects_changed (this); /* EMIT SIGNAL */
1266         return 0;
1267 }
1268
1269 void
1270 Route::all_redirects_flip ()
1271 {
1272         Glib::RWLock::ReaderLock lm (redirect_lock);
1273
1274         if (_redirects.empty()) {
1275                 return;
1276         }
1277
1278         bool first_is_on = _redirects.front()->active();
1279         
1280         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1281                 (*i)->set_active (!first_is_on, this);
1282         }
1283 }
1284
1285 /** Set all redirects with a given placement to a given active state.
1286  * @param p Placement of redirects to change.
1287  * @param state New active state for those redirects.
1288  */
1289 void
1290 Route::all_redirects_active (Placement p, bool state)
1291 {
1292         Glib::RWLock::ReaderLock lm (redirect_lock);
1293
1294         if (_redirects.empty()) {
1295                 return;
1296         }
1297
1298         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1299                 if ((*i)->placement() == p) {
1300                         (*i)->set_active (state, this);
1301                 }
1302         }
1303 }
1304
1305 struct RedirectSorter {
1306     bool operator() (boost::shared_ptr<const Redirect> a, boost::shared_ptr<const Redirect> b) {
1307             return a->sort_key() < b->sort_key();
1308     }
1309 };
1310
1311 int
1312 Route::sort_redirects (uint32_t* err_streams)
1313 {
1314         {
1315                 RedirectSorter comparator;
1316                 Glib::RWLock::WriterLock lm (redirect_lock);
1317                 ChanCount old_rmo = redirect_max_outs;
1318
1319                 /* the sweet power of C++ ... */
1320
1321                 RedirectList as_it_was_before = _redirects;
1322
1323                 _redirects.sort (comparator);
1324         
1325                 if (_reset_plugin_counts (err_streams)) {
1326                         _redirects = as_it_was_before;
1327                         redirect_max_outs = old_rmo;
1328                         return -1;
1329                 } 
1330         } 
1331
1332         reset_panner ();
1333         redirects_changed (this); /* EMIT SIGNAL */
1334
1335         return 0;
1336 }
1337
1338 XMLNode&
1339 Route::get_state()
1340 {
1341         return state(true);
1342 }
1343
1344 XMLNode&
1345 Route::get_template()
1346 {
1347         return state(false);
1348 }
1349
1350 XMLNode&
1351 Route::state(bool full_state)
1352 {
1353         XMLNode *node = new XMLNode("Route");
1354         RedirectList:: iterator i;
1355         char buf[32];
1356
1357         if (_flags) {
1358                 node->add_property("flags", enum_2_string (_flags));
1359         }
1360         
1361         node->add_property("default-type", _default_type.to_string());
1362
1363         node->add_property("active", _active?"yes":"no");
1364         node->add_property("muted", _muted?"yes":"no");
1365         node->add_property("soloed", _soloed?"yes":"no");
1366         node->add_property("phase-invert", _phase_invert?"yes":"no");
1367         node->add_property("mute-affects-pre-fader", _mute_affects_pre_fader?"yes":"no"); 
1368         node->add_property("mute-affects-post-fader", _mute_affects_post_fader?"yes":"no"); 
1369         node->add_property("mute-affects-control-outs", _mute_affects_control_outs?"yes":"no"); 
1370         node->add_property("mute-affects-main-outs", _mute_affects_main_outs?"yes":"no"); 
1371
1372         if (_edit_group) {
1373                 node->add_property("edit-group", _edit_group->name());
1374         }
1375         if (_mix_group) {
1376                 node->add_property("mix-group", _mix_group->name());
1377         }
1378
1379         string order_string;
1380         OrderKeys::iterator x = order_keys.begin(); 
1381
1382         while (x != order_keys.end()) {
1383                 order_string += string ((*x).first);
1384                 order_string += '=';
1385                 snprintf (buf, sizeof(buf), "%ld", (*x).second);
1386                 order_string += buf;
1387                 
1388                 ++x;
1389
1390                 if (x == order_keys.end()) {
1391                         break;
1392                 }
1393
1394                 order_string += ':';
1395         }
1396         node->add_property ("order-keys", order_string);
1397
1398         node->add_child_nocopy (IO::state (full_state));
1399         node->add_child_nocopy (_solo_control.get_state ());
1400         node->add_child_nocopy (_mute_control.get_state ());
1401
1402         XMLNode* remote_control_node = new XMLNode (X_("remote_control"));
1403         snprintf (buf, sizeof (buf), "%d", _remote_control_id);
1404         remote_control_node->add_property (X_("id"), buf);
1405         node->add_child_nocopy (*remote_control_node);
1406
1407         if (_control_outs) {
1408                 XMLNode* cnode = new XMLNode (X_("ControlOuts"));
1409                 cnode->add_child_nocopy (_control_outs->state (full_state));
1410                 node->add_child_nocopy (*cnode);
1411         }
1412
1413         if (_comment.length()) {
1414                 XMLNode *cmt = node->add_child ("Comment");
1415                 cmt->add_content (_comment);
1416         }
1417
1418         for (i = _redirects.begin(); i != _redirects.end(); ++i) {
1419                 node->add_child_nocopy((*i)->state (full_state));
1420         }
1421
1422         if (_extra_xml){
1423                 node->add_child_copy (*_extra_xml);
1424         }
1425         
1426         return *node;
1427 }
1428
1429 void
1430 Route::set_deferred_state ()
1431 {
1432         XMLNodeList nlist;
1433         XMLNodeConstIterator niter;
1434
1435         if (!deferred_state) {
1436                 return;
1437         }
1438
1439         nlist = deferred_state->children();
1440
1441         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1442                 add_redirect_from_xml (**niter);
1443         }
1444
1445         delete deferred_state;
1446         deferred_state = 0;
1447 }
1448
1449 void
1450 Route::add_redirect_from_xml (const XMLNode& node)
1451 {
1452         const XMLProperty *prop;
1453
1454         if (node.name() == "Send") {
1455                 
1456
1457                 try {
1458                         boost::shared_ptr<Send> send (new Send (_session, node));
1459                         add_redirect (send, this);
1460                 } 
1461                 
1462                 catch (failed_constructor &err) {
1463                         error << _("Send construction failed") << endmsg;
1464                         return;
1465                 }
1466                 
1467         } else if (node.name() == "Insert") {
1468                 
1469                 try {
1470                         if ((prop = node.property ("type")) != 0) {
1471
1472                                 boost::shared_ptr<Insert> insert;
1473
1474                                 if (prop->value() == "ladspa" || prop->value() == "Ladspa" || prop->value() == "vst") {
1475
1476                                         insert.reset (new PluginInsert(_session, node));
1477                                         
1478                                 } else if (prop->value() == "port") {
1479
1480
1481                                         insert.reset (new PortInsert (_session, node));
1482
1483                                 } else {
1484
1485                                         error << string_compose(_("unknown Insert type \"%1\"; ignored"), prop->value()) << endmsg;
1486                                 }
1487
1488                                 add_redirect (insert, this);
1489                                 
1490                         } else {
1491                                 error << _("Insert XML node has no type property") << endmsg;
1492                         }
1493                 }
1494                 
1495                 catch (failed_constructor &err) {
1496                         warning << _("insert could not be created. Ignored.") << endmsg;
1497                         return;
1498                 }
1499         }
1500 }
1501
1502 int
1503 Route::set_state (const XMLNode& node)
1504 {
1505         return _set_state (node, true);
1506 }
1507
1508 int
1509 Route::_set_state (const XMLNode& node, bool call_base)
1510 {
1511         XMLNodeList nlist;
1512         XMLNodeConstIterator niter;
1513         XMLNode *child;
1514         XMLPropertyList plist;
1515         const XMLProperty *prop;
1516
1517         if (node.name() != "Route"){
1518                 error << string_compose(_("Bad node sent to Route::set_state() [%1]"), node.name()) << endmsg;
1519                 return -1;
1520         }
1521
1522         if ((prop = node.property (X_("flags"))) != 0) {
1523                 _flags = Flag (string_2_enum (prop->value(), _flags));
1524         } else {
1525                 _flags = Flag (0);
1526         }
1527         
1528         if ((prop = node.property (X_("default-type"))) != 0) {
1529                 _default_type = DataType(prop->value());
1530                 assert(_default_type != DataType::NIL);
1531         }
1532
1533         if ((prop = node.property (X_("phase-invert"))) != 0) {
1534                 set_phase_invert(prop->value()=="yes"?true:false, this);
1535         }
1536
1537         if ((prop = node.property (X_("active"))) != 0) {
1538                 set_active (prop->value() == "yes");
1539         }
1540
1541         if ((prop = node.property (X_("muted"))) != 0) {
1542                 bool yn = prop->value()=="yes"?true:false; 
1543
1544                 /* force reset of mute status */
1545
1546                 _muted = !yn;
1547                 set_mute(yn, this);
1548                 mute_gain = desired_mute_gain;
1549         }
1550
1551         if ((prop = node.property (X_("soloed"))) != 0) {
1552                 bool yn = prop->value()=="yes"?true:false; 
1553
1554                 /* force reset of solo status */
1555
1556                 _soloed = !yn;
1557                 set_solo (yn, this);
1558                 solo_gain = desired_solo_gain;
1559         }
1560
1561         if ((prop = node.property (X_("mute-affects-pre-fader"))) != 0) {
1562                 _mute_affects_pre_fader = (prop->value()=="yes")?true:false;
1563         }
1564
1565         if ((prop = node.property (X_("mute-affects-post-fader"))) != 0) {
1566                 _mute_affects_post_fader = (prop->value()=="yes")?true:false;
1567         }
1568
1569         if ((prop = node.property (X_("mute-affects-control-outs"))) != 0) {
1570                 _mute_affects_control_outs = (prop->value()=="yes")?true:false;
1571         }
1572
1573         if ((prop = node.property (X_("mute-affects-main-outs"))) != 0) {
1574                 _mute_affects_main_outs = (prop->value()=="yes")?true:false;
1575         }
1576
1577         if ((prop = node.property (X_("edit-group"))) != 0) {
1578                 RouteGroup* edit_group = _session.edit_group_by_name(prop->value());
1579                 if(edit_group == 0) {
1580                         error << string_compose(_("Route %1: unknown edit group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1581                 } else {
1582                         set_edit_group(edit_group, this);
1583                 }
1584         }
1585
1586         if ((prop = node.property (X_("order-keys"))) != 0) {
1587
1588                 long n;
1589
1590                 string::size_type colon, equal;
1591                 string remaining = prop->value();
1592
1593                 while (remaining.length()) {
1594
1595                         if ((equal = remaining.find_first_of ('=')) == string::npos || equal == remaining.length()) {
1596                                 error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1597                                       << endmsg;
1598                         } else {
1599                                 if (sscanf (remaining.substr (equal+1).c_str(), "%ld", &n) != 1) {
1600                                         error << string_compose (_("badly formed order key string in state file! [%1] ... ignored."), remaining)
1601                                               << endmsg;
1602                                 } else {
1603                                         set_order_key (remaining.substr (0, equal).c_str(), n);
1604                                 }
1605                         }
1606
1607                         colon = remaining.find_first_of (':');
1608
1609                         if (colon != string::npos) {
1610                                 remaining = remaining.substr (colon+1);
1611                         } else {
1612                                 break;
1613                         }
1614                 }
1615         }
1616
1617         nlist = node.children();
1618
1619         if (deferred_state) {
1620                 delete deferred_state;
1621         }
1622
1623         deferred_state = new XMLNode(X_("deferred state"));
1624
1625         /* set parent class properties before anything else */
1626
1627         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1628
1629                 child = *niter;
1630
1631                 if (child->name() == IO::state_node_name && call_base) {
1632
1633                         IO::set_state (*child);
1634                         break;
1635                 }
1636         }
1637                         
1638         for (niter = nlist.begin(); niter != nlist.end(); ++niter){
1639
1640                 child = *niter;
1641                         
1642                 if (child->name() == X_("Send")) {
1643
1644
1645                         if (!IO::ports_legal) {
1646
1647                                 deferred_state->add_child_copy (*child);
1648
1649                         } else {
1650                                 add_redirect_from_xml (*child);
1651                         }
1652
1653                 } else if (child->name() == X_("Insert")) {
1654                         
1655                         if (!IO::ports_legal) {
1656                                 
1657                                 deferred_state->add_child_copy (*child);
1658
1659                         } else {
1660                                 
1661                                 add_redirect_from_xml (*child);
1662                         }
1663
1664                 } else if (child->name() == X_("Automation")) {
1665                         
1666                         if ((prop = child->property (X_("path"))) != 0)  {
1667                                 load_automation (prop->value());
1668                         }
1669
1670                 } else if (child->name() == X_("ControlOuts")) {
1671                         
1672                         string coutname = _name;
1673                         coutname += _("[control]");
1674
1675                         _control_outs = new IO (_session, coutname);
1676                         _control_outs->set_state (**(child->children().begin()));
1677
1678                 } else if (child->name() == X_("Comment")) {
1679
1680                         /* XXX this is a terrible API design in libxml++ */
1681
1682                         XMLNode *cmt = *(child->children().begin());
1683                         _comment = cmt->content();
1684
1685                 } else if (child->name() == X_("extra")) {
1686
1687                         _extra_xml = new XMLNode (*child);
1688
1689                 } else if (child->name() == X_("controllable") && (prop = child->property("name")) != 0) {
1690                         
1691                         if (prop->value() == "solo") {
1692                                 _solo_control.set_state (*child);
1693                                 _session.add_controllable (&_solo_control);
1694                         }
1695                         else if (prop->value() == "mute") {
1696                                 _mute_control.set_state (*child);
1697                                 _session.add_controllable (&_mute_control);
1698                         }
1699                 }
1700                 else if (child->name() == X_("remote_control")) {
1701                         if ((prop = child->property (X_("id"))) != 0) {
1702                                 int32_t x;
1703                                 sscanf (prop->value().c_str(), "%d", &x);
1704                                 set_remote_control_id (x);
1705                         }
1706                 }
1707         }
1708
1709         if ((prop = node.property (X_("mix-group"))) != 0) {
1710                 RouteGroup* mix_group = _session.mix_group_by_name(prop->value());
1711                 if (mix_group == 0) {
1712                         error << string_compose(_("Route %1: unknown mix group \"%2 in saved state (ignored)"), _name, prop->value()) << endmsg;
1713                 }  else {
1714                         set_mix_group(mix_group, this);
1715                 }
1716         }
1717
1718         return 0;
1719 }
1720
1721 void
1722 Route::curve_reallocate ()
1723 {
1724 //      _gain_automation_curve.finish_resize ();
1725 //      _pan_automation_curve.finish_resize ();
1726 }
1727
1728 void
1729 Route::silence (nframes_t nframes, nframes_t offset)
1730 {
1731         if (!_silent) {
1732
1733                 IO::silence (nframes, offset);
1734
1735                 if (_control_outs) {
1736                         _control_outs->silence (nframes, offset);
1737                 }
1738
1739                 { 
1740                         Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
1741                         
1742                         if (lm.locked()) {
1743                                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1744                                         boost::shared_ptr<PluginInsert> pi;
1745                                         if (!_active && (pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
1746                                                 // skip plugins, they don't need anything when we're not active
1747                                                 continue;
1748                                         }
1749
1750                                         (*i)->silence (nframes, offset);
1751                                 }
1752
1753                                 if (nframes == _session.get_block_size() && offset == 0) {
1754                                         // _silent = true;
1755                                 }
1756                         }
1757                 }
1758                 
1759         }
1760 }       
1761
1762 int
1763 Route::set_control_outs (const vector<string>& ports)
1764 {
1765         Glib::Mutex::Lock lm (control_outs_lock);
1766         vector<string>::const_iterator i;
1767
1768         if (_control_outs) {
1769                 delete _control_outs;
1770                 _control_outs = 0;
1771         }
1772         
1773         if (ports.empty()) {
1774                 return 0;
1775         }
1776  
1777         string coutname = _name;
1778         coutname += _("[control]");
1779         
1780         _control_outs = new IO (_session, coutname);
1781
1782         /* our control outs need as many outputs as we
1783            have audio outputs. we track the changes in ::output_change_handler().
1784         */
1785
1786         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().get(DataType::AUDIO)), true, this);
1787  
1788         return 0;
1789 }       
1790
1791 void
1792 Route::set_edit_group (RouteGroup *eg, void *src)
1793
1794 {
1795         if (eg == _edit_group) {
1796                 return;
1797         }
1798
1799         if (_edit_group) {
1800                 _edit_group->remove (this);
1801         }
1802
1803         if ((_edit_group = eg) != 0) {
1804                 _edit_group->add (this);
1805         }
1806
1807         _session.set_dirty ();
1808         edit_group_changed (src); /* EMIT SIGNAL */
1809 }
1810
1811 void
1812 Route::drop_edit_group (void *src)
1813 {
1814         _edit_group = 0;
1815         _session.set_dirty ();
1816         edit_group_changed (src); /* EMIT SIGNAL */
1817 }
1818
1819 void
1820 Route::set_mix_group (RouteGroup *mg, void *src)
1821
1822 {
1823         if (mg == _mix_group) {
1824                 return;
1825         }
1826
1827         if (_mix_group) {
1828                 _mix_group->remove (this);
1829         }
1830
1831         if ((_mix_group = mg) != 0) {
1832                 _mix_group->add (this);
1833         }
1834
1835         _session.set_dirty ();
1836         mix_group_changed (src); /* EMIT SIGNAL */
1837 }
1838
1839 void
1840 Route::drop_mix_group (void *src)
1841 {
1842         _mix_group = 0;
1843         _session.set_dirty ();
1844         mix_group_changed (src); /* EMIT SIGNAL */
1845 }
1846
1847 void
1848 Route::set_comment (string cmt, void *src)
1849 {
1850         _comment = cmt;
1851         comment_changed (src);
1852         _session.set_dirty ();
1853 }
1854
1855 bool
1856 Route::feeds (boost::shared_ptr<Route> other)
1857 {
1858         uint32_t i, j;
1859
1860         IO& self = *this;
1861         uint32_t no = self.n_outputs().get_total();
1862         uint32_t ni = other->n_inputs ().get_total();
1863
1864         for (i = 0; i < no; ++i) {
1865                 for (j = 0; j < ni; ++j) {
1866                         if (self.output(i)->connected_to (other->input(j)->name())) {
1867                                 return true;
1868                         }
1869                 }
1870         }
1871
1872         /* check Redirects which may also interconnect Routes */
1873
1874         for (RedirectList::iterator r = _redirects.begin(); r != _redirects.end(); r++) {
1875
1876                 no = (*r)->n_outputs().get_total();
1877
1878                 for (i = 0; i < no; ++i) {
1879                         for (j = 0; j < ni; ++j) {
1880                                 if ((*r)->output(i)->connected_to (other->input (j)->name())) {
1881                                         return true;
1882                                 }
1883                         }
1884                 }
1885         }
1886
1887         /* check for control room outputs which may also interconnect Routes */
1888
1889         if (_control_outs) {
1890
1891                 no = _control_outs->n_outputs().get_total();
1892                 
1893                 for (i = 0; i < no; ++i) {
1894                         for (j = 0; j < ni; ++j) {
1895                                 if (_control_outs->output(i)->connected_to (other->input (j)->name())) {
1896                                         return true;
1897                                 }
1898                         }
1899                 }
1900         }
1901
1902         return false;
1903 }
1904
1905 void
1906 Route::set_mute_config (mute_type t, bool onoff, void *src)
1907 {
1908         switch (t) {
1909         case PRE_FADER:
1910                 _mute_affects_pre_fader = onoff;
1911                  pre_fader_changed(src); /* EMIT SIGNAL */
1912                 break;
1913
1914         case POST_FADER:
1915                 _mute_affects_post_fader = onoff;
1916                  post_fader_changed(src); /* EMIT SIGNAL */
1917                 break;
1918
1919         case CONTROL_OUTS:
1920                 _mute_affects_control_outs = onoff;
1921                  control_outs_changed(src); /* EMIT SIGNAL */
1922                 break;
1923
1924         case MAIN_OUTS:
1925                 _mute_affects_main_outs = onoff;
1926                  main_outs_changed(src); /* EMIT SIGNAL */
1927                 break;
1928         }
1929 }
1930
1931 bool
1932 Route::get_mute_config (mute_type t)
1933 {
1934         bool onoff = false;
1935         
1936         switch (t){
1937         case PRE_FADER:
1938                 onoff = _mute_affects_pre_fader; 
1939                 break;
1940         case POST_FADER:
1941                 onoff = _mute_affects_post_fader;
1942                 break;
1943         case CONTROL_OUTS:
1944                 onoff = _mute_affects_control_outs;
1945                 break;
1946         case MAIN_OUTS:
1947                 onoff = _mute_affects_main_outs;
1948                 break;
1949         }
1950         
1951         return onoff;
1952 }
1953
1954 void
1955 Route::set_active (bool yn)
1956 {
1957         _active = yn; 
1958          active_changed(); /* EMIT SIGNAL */
1959 }
1960
1961 void
1962 Route::handle_transport_stopped (bool abort_ignored, bool did_locate, bool can_flush_redirects)
1963 {
1964         nframes_t now = _session.transport_frame();
1965
1966         {
1967                 Glib::RWLock::ReaderLock lm (redirect_lock);
1968
1969                 if (!did_locate) {
1970                         automation_snapshot (now);
1971                 }
1972
1973                 for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
1974                         
1975                         if (Config->get_plugins_stop_with_transport() && can_flush_redirects) {
1976                                 (*i)->deactivate ();
1977                                 (*i)->activate ();
1978                         }
1979                         
1980                         (*i)->transport_stopped (now);
1981                 }
1982         }
1983
1984         IO::transport_stopped (now);
1985  
1986         _roll_delay = _initial_delay;
1987 }
1988
1989 void
1990 Route::input_change_handler (IOChange change, void *ignored)
1991 {
1992         if (change & ConfigurationChanged) {
1993                 reset_plugin_counts (0);
1994         }
1995 }
1996
1997 void
1998 Route::output_change_handler (IOChange change, void *ignored)
1999 {
2000         if (change & ConfigurationChanged) {
2001                 if (_control_outs) {
2002                         _control_outs->ensure_io (ChanCount::ZERO, ChanCount(DataType::AUDIO, n_outputs().get(DataType::AUDIO)), true, this);
2003                 }
2004                 
2005                 reset_plugin_counts (0);
2006         }
2007 }
2008
2009 uint32_t
2010 Route::pans_required () const
2011 {
2012         if (n_outputs().get(DataType::AUDIO) < 2) {
2013                 return 0;
2014         }
2015         
2016         return max (n_inputs ().get(DataType::AUDIO), static_cast<size_t>(redirect_max_outs.get(DataType::AUDIO)));
2017 }
2018
2019 int 
2020 Route::no_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2021                    bool session_state_changing, bool can_record, bool rec_monitors_input)
2022 {
2023         if (n_outputs().get_total() == 0) {
2024                 return 0;
2025         }
2026
2027         if (session_state_changing || !_active)  {
2028                 silence (nframes, offset);
2029                 return 0;
2030         }
2031
2032         apply_gain_automation = false;
2033         
2034         if (n_inputs().get_total()) {
2035                 passthru (start_frame, end_frame, nframes, offset, 0, false);
2036         } else {
2037                 silence (nframes, offset);
2038         }
2039
2040         return 0;
2041 }
2042
2043 nframes_t
2044 Route::check_initial_delay (nframes_t nframes, nframes_t& offset, nframes_t& transport_frame)
2045 {
2046         if (_roll_delay > nframes) {
2047
2048                 _roll_delay -= nframes;
2049                 silence (nframes, offset);
2050                 /* transport frame is not legal for caller to use */
2051                 return 0;
2052
2053         } else if (_roll_delay > 0) {
2054
2055                 nframes -= _roll_delay;
2056
2057                 silence (_roll_delay, offset);
2058
2059                 offset += _roll_delay;
2060                 transport_frame += _roll_delay;
2061
2062                 _roll_delay = 0;
2063         }
2064
2065         return nframes;
2066 }
2067
2068 int
2069 Route::roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, int declick,
2070              bool can_record, bool rec_monitors_input)
2071 {
2072         {
2073                 Glib::RWLock::ReaderLock lm (redirect_lock, Glib::TRY_LOCK);
2074                 if (lm.locked()) {
2075                         // automation snapshot can also be called from the non-rt context
2076                         // and it uses the redirect list, so we take the lock out here
2077                         automation_snapshot (_session.transport_frame());
2078                 }
2079         }
2080
2081         if ((n_outputs().get_total() == 0 && _redirects.empty()) || n_inputs().get_total() == 0 || !_active) {
2082                 silence (nframes, offset);
2083                 return 0;
2084         }
2085         
2086         nframes_t unused = 0;
2087
2088         if ((nframes = check_initial_delay (nframes, offset, unused)) == 0) {
2089                 return 0;
2090         }
2091
2092         _silent = false;
2093
2094         apply_gain_automation = false;
2095
2096         { 
2097                 Glib::Mutex::Lock am (automation_lock, Glib::TRY_LOCK);
2098                 
2099                 if (am.locked() && _session.transport_rolling()) {
2100                         
2101                         if (gain_automation_playback()) {
2102                                 apply_gain_automation = _gain_automation_curve.rt_safe_get_vector (start_frame, end_frame, _session.gain_automation_buffer(), nframes);
2103                         }
2104                 }
2105         }
2106
2107         passthru (start_frame, end_frame, nframes, offset, declick, false);
2108
2109         return 0;
2110 }
2111
2112 int
2113 Route::silent_roll (nframes_t nframes, nframes_t start_frame, nframes_t end_frame, nframes_t offset, 
2114                     bool can_record, bool rec_monitors_input)
2115 {
2116         silence (nframes, offset);
2117         return 0;
2118 }
2119
2120 void
2121 Route::toggle_monitor_input ()
2122 {
2123         for (PortSet::iterator i = _inputs.begin(); i != _inputs.end(); ++i) {
2124                 i->ensure_monitor_input( ! i->monitoring_input());
2125         }
2126 }
2127
2128 bool
2129 Route::has_external_redirects () const
2130 {
2131         boost::shared_ptr<const PortInsert> pi;
2132         
2133         for (RedirectList::const_iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2134                 if ((pi = boost::dynamic_pointer_cast<const PortInsert>(*i)) != 0) {
2135
2136                         for (PortSet::const_iterator port = pi->outputs().begin();
2137                                         port != pi->outputs().end(); ++port) {
2138                                 
2139                                 string port_name = port->name();
2140                                 string client_name = port_name.substr (0, port_name.find(':'));
2141
2142                                 /* only say "yes" if the redirect is actually in use */
2143                                 
2144                                 if (client_name != "ardour" && pi->active()) {
2145                                         return true;
2146                                 }
2147                         }
2148                 }
2149         }
2150
2151         return false;
2152 }
2153
2154 void
2155 Route::flush_redirects ()
2156 {
2157         /* XXX shouldn't really try to take this lock, since
2158            this is called from the RT audio thread.
2159         */
2160
2161         Glib::RWLock::ReaderLock lm (redirect_lock);
2162
2163         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2164                 (*i)->deactivate ();
2165                 (*i)->activate ();
2166         }
2167 }
2168
2169 void
2170 Route::set_meter_point (MeterPoint p, void *src)
2171 {
2172         if (_meter_point != p) {
2173                 _meter_point = p;
2174                  meter_change (src); /* EMIT SIGNAL */
2175                 _session.set_dirty ();
2176         }
2177 }
2178
2179 nframes_t
2180 Route::update_total_latency ()
2181 {
2182         _own_latency = 0;
2183
2184         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2185                 if ((*i)->active ()) {
2186                         _own_latency += (*i)->latency ();
2187                 }
2188         }
2189
2190         set_port_latency (_own_latency);
2191
2192         /* this (virtual) function is used for pure Routes,
2193            not derived classes like AudioTrack.  this means
2194            that the data processed here comes from an input
2195            port, not prerecorded material, and therefore we
2196            have to take into account any input latency.
2197         */
2198
2199         _own_latency += input_latency ();
2200
2201         return _own_latency;
2202 }
2203
2204 void
2205 Route::set_latency_delay (nframes_t longest_session_latency)
2206 {
2207         _initial_delay = longest_session_latency - _own_latency;
2208
2209         if (_session.transport_stopped()) {
2210                 _roll_delay = _initial_delay;
2211         }
2212 }
2213
2214 void
2215 Route::automation_snapshot (nframes_t now)
2216 {
2217         IO::automation_snapshot (now);
2218
2219         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2220                 (*i)->automation_snapshot (now);
2221         }
2222 }
2223
2224 Route::ToggleControllable::ToggleControllable (std::string name, Route& s, ToggleType tp)
2225         : Controllable (name), route (s), type(tp)
2226 {
2227         
2228 }
2229
2230 void
2231 Route::ToggleControllable::set_value (float val)
2232 {
2233         bool bval = ((val >= 0.5f) ? true: false);
2234         
2235         switch (type) {
2236         case MuteControl:
2237                 route.set_mute (bval, this);
2238                 break;
2239         case SoloControl:
2240                 route.set_solo (bval, this);
2241                 break;
2242         default:
2243                 break;
2244         }
2245 }
2246
2247 float
2248 Route::ToggleControllable::get_value (void) const
2249 {
2250         float val = 0.0f;
2251         
2252         switch (type) {
2253         case MuteControl:
2254                 val = route.muted() ? 1.0f : 0.0f;
2255                 break;
2256         case SoloControl:
2257                 val = route.soloed() ? 1.0f : 0.0f;
2258                 break;
2259         default:
2260                 break;
2261         }
2262
2263         return val;
2264 }
2265
2266 void 
2267 Route::set_block_size (nframes_t nframes)
2268 {
2269         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2270                 (*i)->set_block_size (nframes);
2271         }
2272 }
2273
2274 void
2275 Route::redirect_active_proxy (Redirect* ignored, void* ignored_src)
2276 {
2277         _session.update_latency_compensation (false, false);
2278 }
2279
2280 void
2281 Route::protect_automation ()
2282 {
2283         switch (gain_automation_state()) {
2284         case Write:
2285                 set_gain_automation_state (Off);
2286         case Touch:
2287                 set_gain_automation_state (Play);
2288                 break;
2289         default:
2290                 break;
2291         }
2292
2293         switch (panner().automation_state ()) {
2294         case Write:
2295                 panner().set_automation_state (Off);
2296                 break;
2297         case Touch:
2298                 panner().set_automation_state (Play);
2299                 break;
2300         default:
2301                 break;
2302         }
2303         
2304         for (RedirectList::iterator i = _redirects.begin(); i != _redirects.end(); ++i) {
2305                 boost::shared_ptr<PluginInsert> pi;
2306                 if ((pi = boost::dynamic_pointer_cast<PluginInsert> (*i)) != 0) {
2307                         pi->protect_automation ();
2308                 }
2309         }
2310 }
2311
2312 void
2313 Route::set_pending_declick (int declick)
2314 {
2315         if (_declickable) {
2316                 /* this call is not allowed to turn off a pending declick unless "force" is true */
2317                 if (declick) {
2318                         _pending_declick = declick;
2319                 }
2320                 // cerr << _name << ": after setting to " << declick << " pending declick = " << _pending_declick << endl;
2321         } else {
2322                 _pending_declick = 0;
2323         }
2324
2325 }