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