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