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