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