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