989b91606554adf7138538d71181733cbbc2f6fa
[ardour.git] / libs / ardour / session.cc
1 /*
2     Copyright (C) 1999-2010 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 <stdint.h>
21
22 #include <algorithm>
23 #include <string>
24 #include <vector>
25 #include <sstream>
26 #include <fstream>
27 #include <cstdio> /* sprintf(3) ... grrr */
28 #include <cmath>
29 #include <cerrno>
30 #include <unistd.h>
31 #include <limits.h>
32
33 #include <glibmm/threads.h>
34 #include <glibmm/miscutils.h>
35 #include <glibmm/fileutils.h>
36
37 #include <boost/algorithm/string/erase.hpp>
38
39 #include "pbd/convert.h"
40 #include "pbd/error.h"
41 #include "pbd/boost_debug.h"
42 #include "pbd/stl_delete.h"
43 #include "pbd/basename.h"
44 #include "pbd/stacktrace.h"
45 #include "pbd/file_utils.h"
46 #include "pbd/convert.h"
47 #include "pbd/unwind.h"
48 #include "pbd/search_path.h"
49
50 #include "ardour/amp.h"
51 #include "ardour/analyser.h"
52 #include "ardour/async_midi_port.h"
53 #include "ardour/audio_buffer.h"
54 #include "ardour/audio_diskstream.h"
55 #include "ardour/audio_port.h"
56 #include "ardour/audio_track.h"
57 #include "ardour/audioengine.h"
58 #include "ardour/audiofilesource.h"
59 #include "ardour/auditioner.h"
60 #include "ardour/buffer_manager.h"
61 #include "ardour/buffer_set.h"
62 #include "ardour/bundle.h"
63 #include "ardour/butler.h"
64 #include "ardour/click.h"
65 #include "ardour/control_protocol_manager.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/graph.h"
70 #include "ardour/midiport_manager.h"
71 #include "ardour/scene_changer.h"
72 #include "ardour/midi_track.h"
73 #include "ardour/midi_ui.h"
74 #include "ardour/operations.h"
75 #include "ardour/playlist.h"
76 #include "ardour/plugin.h"
77 #include "ardour/plugin_insert.h"
78 #include "ardour/process_thread.h"
79 #include "ardour/rc_configuration.h"
80 #include "ardour/recent_sessions.h"
81 #include "ardour/region.h"
82 #include "ardour/region_factory.h"
83 #include "ardour/route_graph.h"
84 #include "ardour/route_group.h"
85 #include "ardour/route_sorters.h"
86 #include "ardour/send.h"
87 #include "ardour/session.h"
88 #include "ardour/session_directory.h"
89 #include "ardour/session_playlists.h"
90 #include "ardour/smf_source.h"
91 #include "ardour/source_factory.h"
92 #include "ardour/speakers.h"
93 #include "ardour/track.h"
94 #include "ardour/utils.h"
95
96 #include "midi++/port.h"
97 #include "midi++/mmc.h"
98
99 #include "i18n.h"
100
101 namespace ARDOUR {
102 class MidiSource;
103 class Processor;
104 class Speakers;
105 }
106
107 using namespace std;
108 using namespace ARDOUR;
109 using namespace PBD;
110
111 bool Session::_disable_all_loaded_plugins = false;
112
113 PBD::Signal1<int,uint32_t> Session::AudioEngineSetupRequired;
114 PBD::Signal1<void,std::string> Session::Dialog;
115 PBD::Signal0<int> Session::AskAboutPendingState;
116 PBD::Signal2<int, framecnt_t, framecnt_t> Session::AskAboutSampleRateMismatch;
117 PBD::Signal0<void> Session::SendFeedback;
118 PBD::Signal3<int,Session*,std::string,DataType> Session::MissingFile;
119
120 PBD::Signal1<void, framepos_t> Session::StartTimeChanged;
121 PBD::Signal1<void, framepos_t> Session::EndTimeChanged;
122 PBD::Signal2<void,std::string, std::string> Session::Exported;
123 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
124 PBD::Signal0<void> Session::Quit;
125 PBD::Signal0<void> Session::FeedbackDetected;
126 PBD::Signal0<void> Session::SuccessfulGraphSort;
127 PBD::Signal2<void,std::string,std::string> Session::VersionMismatch;
128
129 const framecnt_t Session::bounce_chunk_size = 65536;
130 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
131 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
132
133 /** @param snapshot_name Snapshot name, without .ardour suffix */
134 Session::Session (AudioEngine &eng,
135                   const string& fullpath,
136                   const string& snapshot_name,
137                   BusProfile* bus_profile,
138                   string mix_template)
139         : playlists (new SessionPlaylists)
140         , _engine (eng)
141         , process_function (&Session::process_with_events)
142         , _bounce_processing_active (false)
143         , waiting_for_sync_offset (false)
144         , _base_frame_rate (0)
145         , _current_frame_rate (0)
146         , _nominal_frame_rate (0)
147         , transport_sub_state (0)
148         , _record_status (Disabled)
149         , _transport_frame (0)
150         , _session_range_location (0)
151         , _slave (0)
152         , _silent (false)
153         , _transport_speed (0)
154         , _default_transport_speed (1.0)
155         , _last_transport_speed (0)
156         , _target_transport_speed (0.0)
157         , auto_play_legal (false)
158         , _last_slave_transport_frame (0)
159         , maximum_output_latency (0)
160         , _requested_return_frame (-1)
161         , current_block_size (0)
162         , _worst_output_latency (0)
163         , _worst_input_latency (0)
164         , _worst_track_latency (0)
165         , _have_captured (false)
166         , _meter_hold (0)
167         , _meter_falloff (0)
168         , _non_soloed_outs_muted (false)
169         , _listen_cnt (0)
170         , _solo_isolated_cnt (0)
171         , _writable (false)
172         , _was_seamless (Config->get_seamless_loop ())
173         , _under_nsm_control (false)
174         , delta_accumulator_cnt (0)
175         , average_slave_delta (1800) // !!! why 1800 ???
176         , average_dir (0)
177         , have_first_delta_accumulator (false)
178         , _slave_state (Stopped)
179         , post_export_sync (false)
180         , post_export_position (0)
181         , _exporting (false)
182         , _export_started (false)
183         , _export_rolling (false)
184         , _pre_export_mmc_enabled (false)
185         , _name (snapshot_name)
186         , _is_new (true)
187         , _send_qf_mtc (false)
188         , _pframes_since_last_mtc (0)
189         , session_midi_feedback (0)
190         , play_loop (false)
191         , loop_changing (false)
192         , last_loopend (0)
193         , _session_dir (new SessionDirectory (fullpath))
194         , _current_snapshot_name (snapshot_name)          
195         , state_tree (0)
196         , state_was_pending (false)
197         , _state_of_the_state (StateOfTheState(CannotSave|InitialConnecting|Loading))
198         , _suspend_save (0)
199         , _save_queued (false)
200         , _last_roll_location (0)
201         , _last_roll_or_reversal_location (0)
202         , _last_record_location (0)
203         , pending_locate_roll (false)
204         , pending_locate_frame (0)
205         , pending_locate_flush (false)
206         , pending_abort (false)
207         , pending_auto_loop (false)
208         , _butler (new Butler (*this))
209         , _post_transport_work (0)
210         ,  cumulative_rf_motion (0)
211         , rf_scale (1.0)
212         , _locations (new Locations (*this))
213         , step_speed (0)
214         , outbound_mtc_timecode_frame (0)
215         , next_quarter_frame_to_send (-1)
216         , _frames_per_timecode_frame (0)
217         , _frames_per_hour (0)
218         , _timecode_frames_per_hour (0)
219         , last_timecode_valid (false)
220         , last_timecode_when (0)
221         , _send_timecode_update (false)
222         , ltc_encoder (0)
223         , ltc_enc_buf(0)
224         , ltc_buf_off (0)
225         , ltc_buf_len (0)
226         , ltc_speed (0)
227         , ltc_enc_byte (0)
228         , ltc_enc_pos (0)
229         , ltc_enc_cnt (0)
230         , ltc_enc_off (0)
231         , restarting (false)
232         , ltc_prev_cycle (0)
233         , ltc_timecode_offset (0)
234         , ltc_timecode_negative_offset (false)
235         , midi_control_ui (0)
236         , _tempo_map (0)
237         , _all_route_group (new RouteGroup (*this, "all"))
238         , routes (new RouteList)
239         , _adding_routes_in_progress (false)
240         , destructive_index (0)
241         , _track_number_decimals(1)
242         , solo_update_disabled (false)
243         , default_fade_steepness (0)
244         , default_fade_msecs (0)
245         , _total_free_4k_blocks (0)
246         , _total_free_4k_blocks_uncertain (false)
247         , no_questions_about_missing_files (false)
248         , _playback_load (0)
249         , _capture_load (0)
250         , _bundles (new BundleList)
251         , _bundle_xml_node (0)
252         , _current_trans (0)
253         , _clicking (false)
254         , click_data (0)
255         , click_emphasis_data (0)
256         , click_length (0)
257         , click_emphasis_length (0)
258         , _clicks_cleared (0)
259         , _play_range (false)
260         , main_outs (0)
261         , first_file_data_format_reset (true)
262         , first_file_header_format_reset (true)
263         , have_looped (false)
264         , _have_rec_enabled_track (false)
265         , _step_editors (0)
266         , _suspend_timecode_transmission (0)
267         ,  _speakers (new Speakers)
268         , _order_hint (0)
269         , ignore_route_processor_changes (false)
270         , _scene_changer (0)
271         , _midi_ports (0)
272         , _mmc (0)
273 {
274         uint32_t sr = 0;
275
276         pre_engine_init (fullpath);
277         
278         if (_is_new) {
279                 if (ensure_engine (sr)) {
280                         destroy ();
281                         throw failed_constructor ();
282                 }
283
284                 if (create (mix_template, bus_profile)) {
285                         destroy ();
286                         throw failed_constructor ();
287                 }
288
289                 /* if a mix template was provided, then ::create() will
290                  * have copied it into the session and we need to load it
291                  * so that we have the state ready for ::set_state()
292                  * after the engine is started.
293                  *
294                  * Note that we do NOT try to get the sample rate from
295                  * the template at this time, though doing so would
296                  * be easy if we decided this was an appropriate part
297                  * of a template.
298                  */
299
300                 if (!mix_template.empty() && load_state (_current_snapshot_name)) {
301                         throw failed_constructor ();
302                 }
303
304                 /* load default session properties - if any */
305                 config.load_state();
306
307         } else {
308
309                 if (load_state (_current_snapshot_name)) {
310                         throw failed_constructor ();
311                 }
312         
313                 /* try to get sample rate from XML state so that we
314                  * can influence the SR if we set up the audio
315                  * engine.
316                  */
317
318                 if (state_tree) {
319                         const XMLProperty* prop;
320                         if ((prop = state_tree->root()->property (X_("sample-rate"))) != 0) {           
321                                 sr = atoi (prop->value());
322                         }
323                 }
324
325                 if (ensure_engine (sr)) {
326                         destroy ();
327                         throw failed_constructor ();
328                 }
329         }
330
331         if (post_engine_init ()) {
332                 destroy ();
333                 throw failed_constructor ();
334         }
335
336         store_recent_sessions (_name, _path);
337
338         bool was_dirty = dirty();
339
340         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
341
342         Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
343         config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
344
345         if (was_dirty) {
346                 DirtyChanged (); /* EMIT SIGNAL */
347         }
348
349         StartTimeChanged.connect_same_thread (*this, boost::bind (&Session::start_time_changed, this, _1));
350         EndTimeChanged.connect_same_thread (*this, boost::bind (&Session::end_time_changed, this, _1));
351
352         _is_new = false;
353
354         /* hook us up to the engine since we are now completely constructed */
355
356         BootMessage (_("Connect to engine"));
357
358         _engine.set_session (this);
359         _engine.reset_timebase ();
360
361         BootMessage (_("Session loading complete"));
362
363 }
364
365 Session::~Session ()
366 {
367 #ifdef PT_TIMING        
368         ST.dump ("ST.dump");
369 #endif  
370         destroy ();
371 }
372
373 int
374 Session::ensure_engine (uint32_t desired_sample_rate)
375 {
376         if (_engine.current_backend() == 0) {
377                 /* backend is unknown ... */
378                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
379                 if (r.get_value_or (-1) != 0) {
380                         return -1;
381                 }
382         } else if (_engine.setup_required()) {
383                 /* backend is known, but setup is needed */
384                 boost::optional<int> r = AudioEngineSetupRequired (desired_sample_rate);
385                 if (r.get_value_or (-1) != 0) {
386                         return -1;
387                 }
388         } else if (!_engine.running()) {
389                 if (_engine.start()) {
390                         return -1;
391                 }
392         }
393
394         /* at this point the engine should be running
395         */
396
397         if (!_engine.running()) {
398                 return -1;
399         }
400
401         return immediately_post_engine ();
402
403 }
404
405 int
406 Session::immediately_post_engine ()
407 {
408         /* Do various initializations that should take place directly after we
409          * know that the engine is running, but before we either create a
410          * session or set state for an existing one.
411          */
412          
413         if (how_many_dsp_threads () > 1) {
414                 /* For now, only create the graph if we are using >1 DSP threads, as
415                    it is a bit slower than the old code with 1 thread.
416                 */
417                 _process_graph.reset (new Graph (*this));
418         }
419
420         /* every time we reconnect, recompute worst case output latencies */
421
422         _engine.Running.connect_same_thread (*this, boost::bind (&Session::initialize_latencies, this));
423
424         if (synced_to_engine()) {
425                 _engine.transport_stop ();
426         }
427
428         if (config.get_jack_time_master()) {
429                 _engine.transport_locate (_transport_frame);
430         }
431
432         try {
433                 BootMessage (_("Set up LTC"));
434                 setup_ltc ();
435                 BootMessage (_("Set up Click"));
436                 setup_click ();
437                 BootMessage (_("Set up standard connections"));
438                 setup_bundles ();
439         }
440
441         catch (failed_constructor& err) {
442                 return -1;
443         }
444
445         return 0;
446 }
447
448 void
449 Session::destroy ()
450 {
451         vector<void*> debug_pointers;
452
453         /* if we got to here, leaving pending capture state around
454            is a mistake.
455         */
456
457         remove_pending_capture_state ();
458
459         _state_of_the_state = StateOfTheState (CannotSave|Deletion);
460
461         /* disconnect from any and all signals that we are connected to */
462
463         drop_connections ();
464
465         _engine.remove_session ();
466
467         /* deregister all ports - there will be no process or any other
468          * callbacks from the engine any more.
469          */
470
471         Port::PortDrop (); /* EMIT SIGNAL */
472
473         ltc_tx_cleanup();
474
475         /* clear history so that no references to objects are held any more */
476
477         _history.clear ();
478
479         /* clear state tree so that no references to objects are held any more */
480
481         delete state_tree;
482
483         /* reset dynamic state version back to default */
484
485         Stateful::loading_state_version = 0;
486
487         _butler->drop_references ();
488         delete _butler;
489         _butler = 0;
490         
491         delete midi_control_ui;
492         delete _all_route_group;
493
494         if (click_data != default_click) {
495                 delete [] click_data;
496         }
497
498         if (click_emphasis_data != default_click_emphasis) {
499                 delete [] click_emphasis_data;
500         }
501
502         clear_clicks ();
503
504         /* need to remove auditioner before monitoring section
505          * otherwise it is re-connected */
506         auditioner.reset ();
507
508         /* drop references to routes held by the monitoring section
509          * specifically _monitor_out aux/listen references */
510         remove_monitor_section();
511
512         /* clear out any pending dead wood from RCU managed objects */
513
514         routes.flush ();
515         _bundles.flush ();
516
517         AudioDiskstream::free_working_buffers();
518
519         /* tell everyone who is still standing that we're about to die */
520         drop_references ();
521
522         /* tell everyone to drop references and delete objects as we go */
523
524         DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
525         RegionFactory::delete_all_regions ();
526
527         DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
528
529         /* reset these three references to special routes before we do the usual route delete thing */
530
531         _master_out.reset ();
532         _monitor_out.reset ();
533
534         {
535                 RCUWriter<RouteList> writer (routes);
536                 boost::shared_ptr<RouteList> r = writer.get_copy ();
537
538                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
539                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
540                         (*i)->drop_references ();
541                 }
542
543                 r->clear ();
544                 /* writer goes out of scope and updates master */
545         }
546         routes.flush ();
547
548         {
549                 DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
550                 Glib::Threads::Mutex::Lock lm (source_lock);
551                 for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
552                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->name(), i->second.use_count()));
553                         i->second->drop_references ();
554                 }
555
556                 sources.clear ();
557         }
558
559         DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
560         for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
561
562                 delete *i;
563         }
564
565         /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
566         playlists.reset ();
567
568         delete _scene_changer; _scene_changer = 0;
569
570         delete _mmc; _mmc = 0;
571         delete _midi_ports; _midi_ports = 0;
572         delete _locations; _locations = 0;
573
574         DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
575
576 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
577         boost_debug_list_ptrs ();
578 #endif
579 }
580
581 void
582 Session::setup_ltc ()
583 {
584         XMLNode* child = 0;
585         
586         _ltc_input.reset (new IO (*this, X_("LTC In"), IO::Input));
587         _ltc_output.reset (new IO (*this, X_("LTC Out"), IO::Output));
588         
589         if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC In"))) != 0) {
590                 _ltc_input->set_state (*(child->children().front()), Stateful::loading_state_version);
591         } else {
592                 {
593                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
594                         _ltc_input->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
595                 }
596                 reconnect_ltc_input ();
597         }
598         
599         if (state_tree && (child = find_named_node (*state_tree->root(), X_("LTC Out"))) != 0) {
600                 _ltc_output->set_state (*(child->children().front()), Stateful::loading_state_version);
601         } else {
602                 {
603                         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
604                         _ltc_output->ensure_io (ChanCount (DataType::AUDIO, 1), true, this);
605                 }
606                 reconnect_ltc_output ();
607         }
608         
609         /* fix up names of LTC ports because we don't want the normal
610          * IO style of NAME/TYPE-{in,out}N
611          */
612         
613         _ltc_input->nth (0)->set_name (X_("LTC-in"));
614         _ltc_output->nth (0)->set_name (X_("LTC-out"));
615 }
616
617 void
618 Session::setup_click ()
619 {
620         _clicking = false;
621         _click_io.reset (new ClickIO (*this, X_("Click")));
622         _click_gain.reset (new Amp (*this));
623         _click_gain->activate ();
624         if (state_tree) {
625                 setup_click_state (state_tree->root());
626         } else {
627                 setup_click_state (0);
628         }
629 }
630
631 void
632 Session::setup_click_state (const XMLNode* node)
633 {       
634         const XMLNode* child = 0;
635         
636         if (node && (child = find_named_node (*node, "Click")) != 0) {
637                 
638                 /* existing state for Click */
639                 int c = 0;
640
641                 if (Stateful::loading_state_version < 3000) {
642                         c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
643                 } else {
644                         const XMLNodeList& children (child->children());
645                         XMLNodeList::const_iterator i = children.begin();
646                         if ((c = _click_io->set_state (**i, Stateful::loading_state_version)) == 0) {
647                                 ++i;
648                                 if (i != children.end()) {
649                                         c = _click_gain->set_state (**i, Stateful::loading_state_version);
650                                 }
651                         }
652                 }
653                         
654                 if (c == 0) {
655                         _clicking = Config->get_clicking ();
656
657                 } else {
658
659                         error << _("could not setup Click I/O") << endmsg;
660                         _clicking = false;
661                 }
662
663
664         } else {
665
666                 /* default state for Click: dual-mono to first 2 physical outputs */
667
668                 vector<string> outs;
669                 _engine.get_physical_outputs (DataType::AUDIO, outs);
670
671                 for (uint32_t physport = 0; physport < 2; ++physport) {
672                         if (outs.size() > physport) {
673                                 if (_click_io->add_port (outs[physport], this)) {
674                                         // relax, even though its an error
675                                 }
676                         }
677                 }
678
679                 if (_click_io->n_ports () > ChanCount::ZERO) {
680                         _clicking = Config->get_clicking ();
681                 }
682         }
683 }
684
685 void
686 Session::setup_bundles ()
687 {
688         vector<string> inputs[DataType::num_types];
689         vector<string> outputs[DataType::num_types];
690         for (uint32_t i = 0; i < DataType::num_types; ++i) {
691                 _engine.get_physical_inputs (DataType (DataType::Symbol (i)), inputs[i]);
692                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
693         }
694
695         /* Create a set of Bundle objects that map
696            to the physical I/O currently available.  We create both
697            mono and stereo bundles, so that the common cases of mono
698            and stereo tracks get bundles to put in their mixer strip
699            in / out menus.  There may be a nicer way of achieving that;
700            it doesn't really scale that well to higher channel counts
701         */
702
703         /* mono output bundles */
704
705         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); ++np) {
706                 char buf[32];
707                 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
708
709                 boost::shared_ptr<Bundle> c (new Bundle (buf, true));
710                 c->add_channel (_("mono"), DataType::AUDIO);
711                 c->set_port (0, outputs[DataType::AUDIO][np]);
712
713                 add_bundle (c);
714         }
715
716         /* stereo output bundles */
717
718         for (uint32_t np = 0; np < outputs[DataType::AUDIO].size(); np += 2) {
719                 if (np + 1 < outputs[DataType::AUDIO].size()) {
720                         char buf[32];
721                         snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
722                         boost::shared_ptr<Bundle> c (new Bundle (buf, true));
723                         c->add_channel (_("L"), DataType::AUDIO);
724                         c->set_port (0, outputs[DataType::AUDIO][np]);
725                         c->add_channel (_("R"), DataType::AUDIO);
726                         c->set_port (1, outputs[DataType::AUDIO][np + 1]);
727
728                         add_bundle (c);
729                 }
730         }
731
732         /* mono input bundles */
733
734         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); ++np) {
735                 char buf[32];
736                 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
737
738                 boost::shared_ptr<Bundle> c (new Bundle (buf, false));
739                 c->add_channel (_("mono"), DataType::AUDIO);
740                 c->set_port (0, inputs[DataType::AUDIO][np]);
741
742                 add_bundle (c);
743         }
744
745         /* stereo input bundles */
746
747         for (uint32_t np = 0; np < inputs[DataType::AUDIO].size(); np += 2) {
748                 if (np + 1 < inputs[DataType::AUDIO].size()) {
749                         char buf[32];
750                         snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
751
752                         boost::shared_ptr<Bundle> c (new Bundle (buf, false));
753                         c->add_channel (_("L"), DataType::AUDIO);
754                         c->set_port (0, inputs[DataType::AUDIO][np]);
755                         c->add_channel (_("R"), DataType::AUDIO);
756                         c->set_port (1, inputs[DataType::AUDIO][np + 1]);
757
758                         add_bundle (c);
759                 }
760         }
761
762         /* MIDI input bundles */
763
764         for (uint32_t np = 0; np < inputs[DataType::MIDI].size(); ++np) {
765                 string n = inputs[DataType::MIDI][np];
766                 boost::erase_first (n, X_("alsa_pcm:"));
767
768                 boost::shared_ptr<Bundle> c (new Bundle (n, false));
769                 c->add_channel ("", DataType::MIDI);
770                 c->set_port (0, inputs[DataType::MIDI][np]);
771                 add_bundle (c);
772         }
773
774         /* MIDI output bundles */
775
776         for (uint32_t np = 0; np < outputs[DataType::MIDI].size(); ++np) {
777                 string n = outputs[DataType::MIDI][np];
778                 boost::erase_first (n, X_("alsa_pcm:"));
779
780                 boost::shared_ptr<Bundle> c (new Bundle (n, true));
781                 c->add_channel ("", DataType::MIDI);
782                 c->set_port (0, outputs[DataType::MIDI][np]);
783                 add_bundle (c);
784         }
785
786 }
787
788 void
789 Session::auto_connect_master_bus ()
790 {
791         if (!_master_out || !Config->get_auto_connect_standard_busses() || _monitor_out) {
792                 return;
793         }
794                 
795         /* if requested auto-connect the outputs to the first N physical ports.
796          */
797         
798         uint32_t limit = _master_out->n_outputs().n_total();
799         vector<string> outputs[DataType::num_types];
800         
801         for (uint32_t i = 0; i < DataType::num_types; ++i) {
802                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
803         }
804         
805         for (uint32_t n = 0; n < limit; ++n) {
806                 boost::shared_ptr<Port> p = _master_out->output()->nth (n);
807                 string connect_to;
808                 if (outputs[p->type()].size() > n) {
809                         connect_to = outputs[p->type()][n];
810                 }
811                 
812                 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
813                         if (_master_out->output()->connect (p, connect_to, this)) {
814                                 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
815                                       << endmsg;
816                                 break;
817                         }
818                 }
819         }
820 }
821
822 void
823 Session::remove_monitor_section ()
824 {
825         if (!_monitor_out) {
826                 return;
827         }
828
829         /* force reversion to Solo-In-Place */
830         Config->set_solo_control_is_listen_control (false);
831
832         /* if we are auditioning, cancel it ... this is a workaround
833            to a problem (auditioning does not execute the process graph,
834            which is needed to remove routes when using >1 core for processing)
835         */
836         cancel_audition ();
837
838         {
839                 /* Hold process lock while doing this so that we don't hear bits and
840                  * pieces of audio as we work on each route.
841                  */
842                 
843                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
844                 
845                 /* Connect tracks to monitor section. Note that in an
846                    existing session, the internal sends will already exist, but we want the
847                    routes to notice that they connect to the control out specifically.
848                 */
849                 
850                 
851                 boost::shared_ptr<RouteList> r = routes.reader ();
852                 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
853                 
854                 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
855                         
856                         if ((*x)->is_monitor()) {
857                                 /* relax */
858                         } else if ((*x)->is_master()) {
859                                 /* relax */
860                         } else {
861                                 (*x)->remove_aux_or_listen (_monitor_out);
862                         }
863                 }
864         }
865
866         remove_route (_monitor_out);
867         auto_connect_master_bus ();
868
869         if (auditioner) {
870                 auditioner->connect ();
871         }
872 }
873
874 void
875 Session::add_monitor_section ()
876 {
877         RouteList rl;
878
879         if (_monitor_out || !_master_out) {
880                 return;
881         }
882
883         boost::shared_ptr<Route> r (new Route (*this, _("monitor"), Route::MonitorOut, DataType::AUDIO));
884
885         if (r->init ()) {
886                 return;
887         }
888
889 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
890         // boost_debug_shared_ptr_mark_interesting (r.get(), "Route");
891 #endif
892         {
893                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
894                 r->input()->ensure_io (_master_out->output()->n_ports(), false, this);
895                 r->output()->ensure_io (_master_out->output()->n_ports(), false, this);
896         }
897
898         rl.push_back (r);
899         add_routes (rl, false, false, false);
900         
901         assert (_monitor_out);
902
903         /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
904            are undefined, at best.
905         */
906         
907         uint32_t limit = _monitor_out->n_inputs().n_audio();
908         
909         if (_master_out) {
910                 
911                 /* connect the inputs to the master bus outputs. this
912                  * represents a separate data feed from the internal sends from
913                  * each route. as of jan 2011, it allows the monitor section to
914                  * conditionally ignore either the internal sends or the normal
915                  * input feed, but we should really find a better way to do
916                  * this, i think.
917                  */
918
919                 _master_out->output()->disconnect (this);
920
921                 for (uint32_t n = 0; n < limit; ++n) {
922                         boost::shared_ptr<AudioPort> p = _monitor_out->input()->ports().nth_audio_port (n);
923                         boost::shared_ptr<AudioPort> o = _master_out->output()->ports().nth_audio_port (n);
924                         
925                         if (o) {
926                                 string connect_to = o->name();
927                                 if (_monitor_out->input()->connect (p, connect_to, this)) {
928                                         error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
929                                               << endmsg;
930                                         break;
931                                 }
932                         }
933                 }
934         }
935         
936         /* if monitor section is not connected, connect it to physical outs
937          */
938         
939         if (Config->get_auto_connect_standard_busses() && !_monitor_out->output()->connected ()) {
940                 
941                 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
942                         
943                         boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
944                         
945                         if (b) {
946                                 _monitor_out->output()->connect_ports_to_bundle (b, true, this);
947                         } else {
948                                 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
949                                                            Config->get_monitor_bus_preferred_bundle())
950                                         << endmsg;
951                         }
952                         
953                 } else {
954                         
955                         /* Monitor bus is audio only */
956
957                         vector<string> outputs[DataType::num_types];
958
959                         for (uint32_t i = 0; i < DataType::num_types; ++i) {
960                                 _engine.get_physical_outputs (DataType (DataType::Symbol (i)), outputs[i]);
961                         }
962
963                         uint32_t mod = outputs[DataType::AUDIO].size();
964                         uint32_t limit = _monitor_out->n_outputs().get (DataType::AUDIO);
965                         
966                         if (mod != 0) {
967                                 
968                                 for (uint32_t n = 0; n < limit; ++n) {
969                                         
970                                         boost::shared_ptr<Port> p = _monitor_out->output()->ports().port(DataType::AUDIO, n);
971                                         string connect_to;
972                                         if (outputs[DataType::AUDIO].size() > (n % mod)) {
973                                                 connect_to = outputs[DataType::AUDIO][n % mod];
974                                         }
975                                         
976                                         if (!connect_to.empty()) {
977                                                 if (_monitor_out->output()->connect (p, connect_to, this)) {
978                                                         error << string_compose (
979                                                                 _("cannot connect control output %1 to %2"),
980                                                                 n, connect_to)
981                                                               << endmsg;
982                                                         break;
983                                                 }
984                                         }
985                                 }
986                         }
987                 }
988         }
989
990         /* Hold process lock while doing this so that we don't hear bits and
991          * pieces of audio as we work on each route.
992          */
993          
994         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
995
996         /* Connect tracks to monitor section. Note that in an
997            existing session, the internal sends will already exist, but we want the
998            routes to notice that they connect to the control out specifically.
999         */
1000
1001
1002         boost::shared_ptr<RouteList> rls = routes.reader ();
1003
1004         PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
1005
1006         for (RouteList::iterator x = rls->begin(); x != rls->end(); ++x) {
1007                 
1008                 if ((*x)->is_monitor()) {
1009                         /* relax */
1010                 } else if ((*x)->is_master()) {
1011                         /* relax */
1012                 } else {
1013                         (*x)->enable_monitor_send ();
1014                 }
1015         }
1016
1017         if (auditioner) {
1018                 auditioner->connect ();
1019         }
1020 }
1021
1022 void
1023 Session::hookup_io ()
1024 {
1025         /* stop graph reordering notifications from
1026            causing resorts, etc.
1027         */
1028
1029         _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
1030
1031         if (!auditioner) {
1032
1033                 /* we delay creating the auditioner till now because
1034                    it makes its own connections to ports.
1035                 */
1036
1037                 try {
1038                         boost::shared_ptr<Auditioner> a (new Auditioner (*this));
1039                         if (a->init()) {
1040                                 throw failed_constructor ();
1041                         }
1042                         a->use_new_diskstream ();
1043                         auditioner = a;
1044                 }
1045
1046                 catch (failed_constructor& err) {
1047                         warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
1048                 }
1049         }
1050
1051         /* load bundles, which we may have postponed earlier on */
1052         if (_bundle_xml_node) {
1053                 load_bundles (*_bundle_xml_node);
1054                 delete _bundle_xml_node;
1055         }
1056
1057         /* Tell all IO objects to connect themselves together */
1058
1059         IO::enable_connecting ();
1060
1061         /* Now tell all "floating" ports to connect to whatever
1062            they should be connected to.
1063         */
1064
1065         AudioEngine::instance()->reconnect_ports ();
1066
1067         /* Anyone who cares about input state, wake up and do something */
1068
1069         IOConnectionsComplete (); /* EMIT SIGNAL */
1070
1071         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
1072
1073         /* now handle the whole enchilada as if it was one
1074            graph reorder event.
1075         */
1076
1077         graph_reordered ();
1078
1079         /* update the full solo state, which can't be
1080            correctly determined on a per-route basis, but
1081            needs the global overview that only the session
1082            has.
1083         */
1084
1085         update_route_solo_state ();
1086 }
1087
1088 void
1089 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
1090 {
1091         boost::shared_ptr<Track> track = wp.lock ();
1092         if (!track) {
1093                 return;
1094         }
1095
1096         boost::shared_ptr<Playlist> playlist;
1097
1098         if ((playlist = track->playlist()) != 0) {
1099                 playlist->RegionAdded.connect_same_thread (*this, boost::bind (&Session::playlist_region_added, this, _1));
1100                 playlist->RangesMoved.connect_same_thread (*this, boost::bind (&Session::playlist_ranges_moved, this, _1));
1101                 playlist->RegionsExtended.connect_same_thread (*this, boost::bind (&Session::playlist_regions_extended, this, _1));
1102         }
1103 }
1104
1105 bool
1106 Session::record_enabling_legal () const
1107 {
1108         /* this used to be in here, but survey says.... we don't need to restrict it */
1109         // if (record_status() == Recording) {
1110         //      return false;
1111         // }
1112
1113         if (Config->get_all_safe()) {
1114                 return false;
1115         }
1116         return true;
1117 }
1118
1119 void
1120 Session::set_track_monitor_input_status (bool yn)
1121 {
1122         boost::shared_ptr<RouteList> rl = routes.reader ();
1123         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1124                 boost::shared_ptr<AudioTrack> tr = boost::dynamic_pointer_cast<AudioTrack> (*i);
1125                 if (tr && tr->record_enabled ()) {
1126                         //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
1127                         tr->request_input_monitoring (yn);
1128                 }
1129         }
1130 }
1131
1132 void
1133 Session::auto_punch_start_changed (Location* location)
1134 {
1135         replace_event (SessionEvent::PunchIn, location->start());
1136
1137         if (get_record_enabled() && config.get_punch_in()) {
1138                 /* capture start has been changed, so save new pending state */
1139                 save_state ("", true);
1140         }
1141 }
1142
1143 void
1144 Session::auto_punch_end_changed (Location* location)
1145 {
1146         framepos_t when_to_stop = location->end();
1147         // when_to_stop += _worst_output_latency + _worst_input_latency;
1148         replace_event (SessionEvent::PunchOut, when_to_stop);
1149 }
1150
1151 void
1152 Session::auto_punch_changed (Location* location)
1153 {
1154         framepos_t when_to_stop = location->end();
1155
1156         replace_event (SessionEvent::PunchIn, location->start());
1157         //when_to_stop += _worst_output_latency + _worst_input_latency;
1158         replace_event (SessionEvent::PunchOut, when_to_stop);
1159 }
1160
1161 /** @param loc A loop location.
1162  *  @param pos Filled in with the start time of the required fade-out (in session frames).
1163  *  @param length Filled in with the length of the required fade-out.
1164  */
1165 void
1166 Session::auto_loop_declick_range (Location* loc, framepos_t & pos, framepos_t & length)
1167 {
1168         pos = max (loc->start(), loc->end() - 64);
1169         length = loc->end() - pos;
1170 }
1171
1172 void
1173 Session::auto_loop_changed (Location* location)
1174 {
1175         replace_event (SessionEvent::AutoLoop, location->end(), location->start());
1176         framepos_t dcp;
1177         framecnt_t dcl;
1178         auto_loop_declick_range (location, dcp, dcl);
1179         replace_event (SessionEvent::AutoLoopDeclick, dcp, dcl);
1180
1181         if (transport_rolling() && play_loop) {
1182
1183
1184                 // if (_transport_frame > location->end()) {
1185
1186                 if (_transport_frame < location->start() || _transport_frame > location->end()) {
1187                         // relocate to beginning of loop
1188                         clear_events (SessionEvent::LocateRoll);
1189
1190                         request_locate (location->start(), true);
1191
1192                 }
1193                 else if (Config->get_seamless_loop() && !loop_changing) {
1194
1195                         // schedule a locate-roll to refill the diskstreams at the
1196                         // previous loop end
1197                         loop_changing = true;
1198
1199                         if (location->end() > last_loopend) {
1200                                 clear_events (SessionEvent::LocateRoll);
1201                                 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
1202                                 queue_event (ev);
1203                         }
1204
1205                 }
1206         }
1207
1208         last_loopend = location->end();
1209 }
1210
1211 void
1212 Session::set_auto_punch_location (Location* location)
1213 {
1214         Location* existing;
1215
1216         if ((existing = _locations->auto_punch_location()) != 0 && existing != location) {
1217                 punch_connections.drop_connections();
1218                 existing->set_auto_punch (false, this);
1219                 remove_event (existing->start(), SessionEvent::PunchIn);
1220                 clear_events (SessionEvent::PunchOut);
1221                 auto_punch_location_changed (0);
1222         }
1223
1224         set_dirty();
1225
1226         if (location == 0) {
1227                 return;
1228         }
1229
1230         if (location->end() <= location->start()) {
1231                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1232                 return;
1233         }
1234
1235         punch_connections.drop_connections ();
1236
1237         location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
1238         location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
1239         location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
1240
1241         location->set_auto_punch (true, this);
1242
1243         auto_punch_changed (location);
1244
1245         auto_punch_location_changed (location);
1246 }
1247
1248 void
1249 Session::set_auto_loop_location (Location* location)
1250 {
1251         Location* existing;
1252
1253         if ((existing = _locations->auto_loop_location()) != 0 && existing != location) {
1254                 loop_connections.drop_connections ();
1255                 existing->set_auto_loop (false, this);
1256                 remove_event (existing->end(), SessionEvent::AutoLoop);
1257                 framepos_t dcp;
1258                 framecnt_t dcl;
1259                 auto_loop_declick_range (existing, dcp, dcl);
1260                 remove_event (dcp, SessionEvent::AutoLoopDeclick);
1261                 auto_loop_location_changed (0);
1262         }
1263
1264         set_dirty();
1265
1266         if (location == 0) {
1267                 return;
1268         }
1269
1270         if (location->end() <= location->start()) {
1271                 error << _("You cannot use this location for auto-loop because it has zero or negative length") << endmsg;
1272                 return;
1273         }
1274
1275         last_loopend = location->end();
1276
1277         loop_connections.drop_connections ();
1278
1279         location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1280         location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1281         location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
1282
1283         location->set_auto_loop (true, this);
1284
1285         /* take care of our stuff first */
1286
1287         auto_loop_changed (location);
1288
1289         /* now tell everyone else */
1290
1291         auto_loop_location_changed (location);
1292 }
1293
1294 void
1295 Session::locations_added (Location *)
1296 {
1297         set_dirty ();
1298 }
1299
1300 void
1301 Session::locations_changed ()
1302 {
1303         _locations->apply (*this, &Session::handle_locations_changed);
1304 }
1305
1306 void
1307 Session::handle_locations_changed (Locations::LocationList& locations)
1308 {
1309         Locations::LocationList::iterator i;
1310         Location* location;
1311         bool set_loop = false;
1312         bool set_punch = false;
1313
1314         for (i = locations.begin(); i != locations.end(); ++i) {
1315
1316                 location =* i;
1317
1318                 if (location->is_auto_punch()) {
1319                         set_auto_punch_location (location);
1320                         set_punch = true;
1321                 }
1322                 if (location->is_auto_loop()) {
1323                         set_auto_loop_location (location);
1324                         set_loop = true;
1325                 }
1326
1327                 if (location->is_session_range()) {
1328                         _session_range_location = location;
1329                 }
1330         }
1331
1332         if (!set_loop) {
1333                 set_auto_loop_location (0);
1334         }
1335         if (!set_punch) {
1336                 set_auto_punch_location (0);
1337         }
1338
1339         set_dirty();
1340 }
1341
1342 void
1343 Session::enable_record ()
1344 {
1345         if (_transport_speed != 0.0 && _transport_speed != 1.0) {
1346                 /* no recording at anything except normal speed */
1347                 return;
1348         }
1349
1350         while (1) {
1351                 RecordState rs = (RecordState) g_atomic_int_get (&_record_status);
1352
1353                 if (rs == Recording) {
1354                         break;
1355                 }
1356                 
1357                 if (g_atomic_int_compare_and_exchange (&_record_status, rs, Recording)) {
1358
1359                         _last_record_location = _transport_frame;
1360                         _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordStrobe));
1361
1362                         if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1363                                 set_track_monitor_input_status (true);
1364                         }
1365
1366                         RecordStateChanged ();
1367                         break;
1368                 }
1369         }
1370 }
1371
1372 void
1373 Session::disable_record (bool rt_context, bool force)
1374 {
1375         RecordState rs;
1376
1377         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1378
1379                 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1380                         g_atomic_int_set (&_record_status, Disabled);
1381                         _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordExit));
1382                 } else {
1383                         if (rs == Recording) {
1384                                 g_atomic_int_set (&_record_status, Enabled);
1385                         }
1386                 }
1387
1388                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1389                         set_track_monitor_input_status (false);
1390                 }
1391
1392                 RecordStateChanged (); /* emit signal */
1393
1394                 if (!rt_context) {
1395                         remove_pending_capture_state ();
1396                 }
1397         }
1398 }
1399
1400 void
1401 Session::step_back_from_record ()
1402 {
1403         if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1404
1405                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1406                         set_track_monitor_input_status (false);
1407                 }
1408
1409                 RecordStateChanged (); /* emit signal */
1410         }
1411 }
1412
1413 void
1414 Session::maybe_enable_record ()
1415 {
1416         if (_step_editors > 0) {
1417                 return;
1418         }
1419
1420         g_atomic_int_set (&_record_status, Enabled);
1421
1422         /* This function is currently called from somewhere other than an RT thread.
1423            This save_state() call therefore doesn't impact anything.  Doing it here
1424            means that we save pending state of which sources the next record will use,
1425            which gives us some chance of recovering from a crash during the record.
1426         */
1427
1428         save_state ("", true);
1429
1430         if (_transport_speed) {
1431                 if (!config.get_punch_in()) {
1432                         enable_record ();
1433                 }
1434         } else {
1435                 _mmc->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1436                 RecordStateChanged (); /* EMIT SIGNAL */
1437         }
1438
1439         set_dirty();
1440 }
1441
1442 framepos_t
1443 Session::audible_frame () const
1444 {
1445         framepos_t ret;
1446         framepos_t tf;
1447         framecnt_t offset;
1448
1449         /* the first of these two possible settings for "offset"
1450            mean that the audible frame is stationary until
1451            audio emerges from the latency compensation
1452            "pseudo-pipeline".
1453
1454            the second means that the audible frame is stationary
1455            until audio would emerge from a physical port
1456            in the absence of any plugin latency compensation
1457         */
1458
1459         offset = worst_playback_latency ();
1460
1461         if (offset > current_block_size) {
1462                 offset -= current_block_size;
1463         } else {
1464                 /* XXX is this correct? if we have no external
1465                    physical connections and everything is internal
1466                    then surely this is zero? still, how
1467                    likely is that anyway?
1468                 */
1469                 offset = current_block_size;
1470         }
1471
1472         if (synced_to_engine()) {
1473                 tf = _engine.transport_frame();
1474         } else {
1475                 tf = _transport_frame;
1476         }
1477
1478         ret = tf;
1479
1480         if (!non_realtime_work_pending()) {
1481
1482                 /* MOVING */
1483
1484                 /* Check to see if we have passed the first guaranteed
1485                    audible frame past our last start position. if not,
1486                    return that last start point because in terms
1487                    of audible frames, we have not moved yet.
1488
1489                    `Start position' in this context means the time we last
1490                    either started, located, or changed transport direction.
1491                 */
1492
1493                 if (_transport_speed > 0.0f) {
1494
1495                         if (!play_loop || !have_looped) {
1496                                 if (tf < _last_roll_or_reversal_location + offset) {
1497                                         return _last_roll_or_reversal_location;
1498                                 }
1499                         }
1500
1501
1502                         /* forwards */
1503                         ret -= offset;
1504
1505                 } else if (_transport_speed < 0.0f) {
1506
1507                         /* XXX wot? no backward looping? */
1508
1509                         if (tf > _last_roll_or_reversal_location - offset) {
1510                                 return _last_roll_or_reversal_location;
1511                         } else {
1512                                 /* backwards */
1513                                 ret += offset;
1514                         }
1515                 }
1516         }
1517
1518         return ret;
1519 }
1520
1521 void
1522 Session::set_frame_rate (framecnt_t frames_per_second)
1523 {
1524         /** \fn void Session::set_frame_size(framecnt_t)
1525                 the AudioEngine object that calls this guarantees
1526                 that it will not be called while we are also in
1527                 ::process(). Its fine to do things that block
1528                 here.
1529         */
1530
1531         _base_frame_rate = frames_per_second;
1532         _nominal_frame_rate = frames_per_second;
1533
1534         sync_time_vars();
1535
1536         clear_clicks ();
1537
1538         // XXX we need some equivalent to this, somehow
1539         // SndFileSource::setup_standard_crossfades (frames_per_second);
1540
1541         set_dirty();
1542
1543         /* XXX need to reset/reinstantiate all LADSPA plugins */
1544 }
1545
1546 void
1547 Session::set_block_size (pframes_t nframes)
1548 {
1549         /* the AudioEngine guarantees
1550            that it will not be called while we are also in
1551            ::process(). It is therefore fine to do things that block
1552            here.
1553         */
1554         
1555         {
1556                 current_block_size = nframes;
1557
1558                 ensure_buffers ();
1559
1560                 boost::shared_ptr<RouteList> r = routes.reader ();
1561
1562                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1563                         (*i)->set_block_size (nframes);
1564                 }
1565
1566                 boost::shared_ptr<RouteList> rl = routes.reader ();
1567                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1568                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1569                         if (tr) {
1570                                 tr->set_block_size (nframes);
1571                         }
1572                 }
1573
1574                 set_worst_io_latencies ();
1575         }
1576 }
1577
1578
1579 static void
1580 trace_terminal (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> rbase)
1581 {
1582         boost::shared_ptr<Route> r2;
1583
1584         if (r1->feeds (rbase) && rbase->feeds (r1)) {
1585                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1586                 return;
1587         }
1588
1589         /* make a copy of the existing list of routes that feed r1 */
1590
1591         Route::FedBy existing (r1->fed_by());
1592
1593         /* for each route that feeds r1, recurse, marking it as feeding
1594            rbase as well.
1595         */
1596
1597         for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1598                 if (!(r2 = i->r.lock ())) {
1599                         /* (*i) went away, ignore it */
1600                         continue;
1601                 }
1602
1603                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1604                    base as being fed by r2
1605                 */
1606
1607                 rbase->add_fed_by (r2, i->sends_only);
1608
1609                 if (r2 != rbase) {
1610
1611                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1612                            stop here.
1613                         */
1614
1615                         if (r1->feeds (r2) && r2->feeds (r1)) {
1616                                 continue;
1617                         }
1618
1619                         /* now recurse, so that we can mark base as being fed by
1620                            all routes that feed r2
1621                         */
1622
1623                         trace_terminal (r2, rbase);
1624                 }
1625
1626         }
1627 }
1628
1629 void
1630 Session::resort_routes ()
1631 {
1632         /* don't do anything here with signals emitted
1633            by Routes during initial setup or while we
1634            are being destroyed.
1635         */
1636
1637         if (_state_of_the_state & (InitialConnecting | Deletion)) {
1638                 return;
1639         }
1640
1641         {
1642                 RCUWriter<RouteList> writer (routes);
1643                 boost::shared_ptr<RouteList> r = writer.get_copy ();
1644                 resort_routes_using (r);
1645                 /* writer goes out of scope and forces update */
1646         }
1647
1648 #ifndef NDEBUG
1649         boost::shared_ptr<RouteList> rl = routes.reader ();
1650         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1651                 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1652
1653                 const Route::FedBy& fb ((*i)->fed_by());
1654
1655                 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1656                         boost::shared_ptr<Route> sf = f->r.lock();
1657                         if (sf) {
1658                                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1659                         }
1660                 }
1661         }
1662 #endif
1663
1664 }
1665
1666 /** This is called whenever we need to rebuild the graph of how we will process
1667  *  routes.
1668  *  @param r List of routes, in any order.
1669  */
1670
1671 void
1672 Session::resort_routes_using (boost::shared_ptr<RouteList> r)
1673 {
1674         /* We are going to build a directed graph of our routes;
1675            this is where the edges of that graph are put.
1676         */
1677         
1678         GraphEdges edges;
1679
1680         /* Go through all routes doing two things:
1681          *
1682          * 1. Collect the edges of the route graph.  Each of these edges
1683          *    is a pair of routes, one of which directly feeds the other
1684          *    either by a JACK connection or by an internal send.
1685          *
1686          * 2. Begin the process of making routes aware of which other
1687          *    routes directly or indirectly feed them.  This information
1688          *    is used by the solo code.
1689          */
1690            
1691         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1692
1693                 /* Clear out the route's list of direct or indirect feeds */
1694                 (*i)->clear_fed_by ();
1695
1696                 for (RouteList::iterator j = r->begin(); j != r->end(); ++j) {
1697
1698                         bool via_sends_only;
1699
1700                         /* See if this *j feeds *i according to the current state of the JACK
1701                            connections and internal sends.
1702                         */
1703                         if ((*j)->direct_feeds_according_to_reality (*i, &via_sends_only)) {
1704                                 /* add the edge to the graph (part #1) */
1705                                 edges.add (*j, *i, via_sends_only);
1706                                 /* tell the route (for part #2) */
1707                                 (*i)->add_fed_by (*j, via_sends_only);
1708                         }
1709                 }
1710         }
1711
1712         /* Attempt a topological sort of the route graph */
1713         boost::shared_ptr<RouteList> sorted_routes = topological_sort (r, edges);
1714         
1715         if (sorted_routes) {
1716                 /* We got a satisfactory topological sort, so there is no feedback;
1717                    use this new graph.
1718
1719                    Note: the process graph rechain does not require a
1720                    topologically-sorted list, but hey ho.
1721                 */
1722                 if (_process_graph) {
1723                         _process_graph->rechain (sorted_routes, edges);
1724                 }
1725                 
1726                 _current_route_graph = edges;
1727
1728                 /* Complete the building of the routes' lists of what directly
1729                    or indirectly feeds them.
1730                 */
1731                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1732                         trace_terminal (*i, *i);
1733                 }
1734
1735                 *r = *sorted_routes;
1736
1737 #ifndef NDEBUG
1738                 DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1739                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1740                         DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n",
1741                                                                    (*i)->name(), (*i)->order_key ()));
1742                 }
1743 #endif
1744
1745                 SuccessfulGraphSort (); /* EMIT SIGNAL */
1746
1747         } else {
1748                 /* The topological sort failed, so we have a problem.  Tell everyone
1749                    and stick to the old graph; this will continue to be processed, so
1750                    until the feedback is fixed, what is played back will not quite
1751                    reflect what is actually connected.  Note also that we do not
1752                    do trace_terminal here, as it would fail due to an endless recursion,
1753                    so the solo code will think that everything is still connected
1754                    as it was before.
1755                 */
1756                 
1757                 FeedbackDetected (); /* EMIT SIGNAL */
1758         }
1759
1760 }
1761
1762 /** Find a route name starting with \a base, maybe followed by the
1763  *  lowest \a id.  \a id will always be added if \a definitely_add_number
1764  *  is true on entry; otherwise it will only be added if required
1765  *  to make the name unique.
1766  *
1767  *  Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1768  *  The available route name with the lowest ID will be used, and \a id
1769  *  will be set to the ID.
1770  *
1771  *  \return false if a route name could not be found, and \a track_name
1772  *  and \a id do not reflect a free route name.
1773  */
1774 bool
1775 Session::find_route_name (string const & base, uint32_t& id, char* name, size_t name_len, bool definitely_add_number)
1776 {
1777         if (!definitely_add_number && route_by_name (base) == 0) {
1778                 /* juse use the base */
1779                 snprintf (name, name_len, "%s", base.c_str());
1780                 return true;
1781         }
1782
1783         do {
1784                 snprintf (name, name_len, "%s %" PRIu32, base.c_str(), id);
1785
1786                 if (route_by_name (name) == 0) {
1787                         return true;
1788                 }
1789
1790                 ++id;
1791                 
1792         } while (id < (UINT_MAX-1));
1793
1794         return false;
1795 }
1796
1797 /** Count the total ins and outs of all non-hidden tracks in the session and return them in in and out */
1798 void
1799 Session::count_existing_track_channels (ChanCount& in, ChanCount& out)
1800 {
1801         in  = ChanCount::ZERO;
1802         out = ChanCount::ZERO;
1803
1804         boost::shared_ptr<RouteList> r = routes.reader ();
1805
1806         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1807                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1808                 if (tr && !tr->is_auditioner()) {
1809                         in  += tr->n_inputs();
1810                         out += tr->n_outputs();
1811                 }
1812         }
1813 }
1814
1815 /** Caller must not hold process lock
1816  *  @param name_template string to use for the start of the name, or "" to use "MIDI".
1817  *  @param instrument plugin info for the instrument to insert pre-fader, if any
1818  */
1819 list<boost::shared_ptr<MidiTrack> >
1820 Session::new_midi_track (const ChanCount& input, const ChanCount& output, boost::shared_ptr<PluginInfo> instrument, 
1821                          TrackMode mode, RouteGroup* route_group, uint32_t how_many, string name_template)
1822 {
1823         char track_name[32];
1824         uint32_t track_id = 0;
1825         string port;
1826         RouteList new_routes;
1827         list<boost::shared_ptr<MidiTrack> > ret;
1828
1829         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("MIDI");
1830
1831         while (how_many) {
1832                 if (!find_route_name (name_template.empty() ? _("MIDI") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
1833                         error << "cannot find name for new midi track" << endmsg;
1834                         goto failed;
1835                 }
1836
1837                 boost::shared_ptr<MidiTrack> track;
1838
1839                 try {
1840                         track.reset (new MidiTrack (*this, track_name, Route::Flag (0), mode));
1841
1842                         if (track->init ()) {
1843                                 goto failed;
1844                         }
1845
1846                         track->use_new_diskstream();
1847
1848 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
1849                         // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
1850 #endif
1851                         {
1852                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
1853                                 if (track->input()->ensure_io (input, false, this)) {
1854                                         error << "cannot configure " << input << " out configuration for new midi track" << endmsg;     
1855                                         goto failed;
1856                                 }
1857
1858                                 if (track->output()->ensure_io (output, false, this)) {
1859                                         error << "cannot configure " << output << " out configuration for new midi track" << endmsg;
1860                                         goto failed;
1861                                 }
1862                         }
1863
1864                         track->non_realtime_input_change();
1865
1866                         if (route_group) {
1867                                 route_group->add (track);
1868                         }
1869
1870                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1871
1872                         if (Config->get_remote_model() == UserOrdered) {
1873                                 track->set_remote_control_id (next_control_id());
1874                         }
1875
1876                         new_routes.push_back (track);
1877                         ret.push_back (track);
1878                 }
1879
1880                 catch (failed_constructor &err) {
1881                         error << _("Session: could not create new midi track.") << endmsg;
1882                         goto failed;
1883                 }
1884
1885                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1886
1887                         error << string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with more ports if you need this many tracks."), PROGRAM_NAME) << endmsg;
1888                         goto failed;
1889                 }
1890
1891                 --how_many;
1892         }
1893
1894   failed:
1895         if (!new_routes.empty()) {
1896                 StateProtector sp (this);
1897                 add_routes (new_routes, true, true, true);
1898
1899                 if (instrument) {
1900                         for (RouteList::iterator r = new_routes.begin(); r != new_routes.end(); ++r) {
1901                                 PluginPtr plugin = instrument->load (*this);
1902                                 boost::shared_ptr<Processor> p (new PluginInsert (*this, plugin));
1903                                 (*r)->add_processor (p, PreFader);
1904                                 
1905                         }
1906                 }
1907         }
1908
1909         return ret;
1910 }
1911
1912 void
1913 Session::midi_output_change_handler (IOChange change, void * /*src*/, boost::weak_ptr<Route> wmt)
1914 {
1915         boost::shared_ptr<Route> midi_track (wmt.lock());
1916
1917         if (!midi_track) {
1918                 return;
1919         }
1920
1921         if ((change.type & IOChange::ConfigurationChanged) && Config->get_output_auto_connect() != ManualConnect) {
1922
1923                 if (change.after.n_audio() <= change.before.n_audio()) {
1924                         return;
1925                 }
1926
1927                 /* new audio ports: make sure the audio goes somewhere useful,
1928                    unless the user has no-auto-connect selected.
1929
1930                    The existing ChanCounts don't matter for this call as they are only
1931                    to do with matching input and output indices, and we are only changing
1932                    outputs here.
1933                 */
1934
1935                 ChanCount dummy;
1936
1937                 auto_connect_route (midi_track, dummy, dummy, false, false, ChanCount(), change.before);
1938         }
1939 }
1940
1941 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs.
1942  *  @param input_start Where to start from when auto-connecting inputs; e.g. if this is 0, auto-connect starting from input 0.
1943  *  @param output_start As \a input_start, but for outputs.
1944  */
1945 void
1946 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs,
1947                              bool with_lock, bool connect_inputs, ChanCount input_start, ChanCount output_start)
1948 {
1949         if (!IO::connecting_legal) {
1950                 return;
1951         }
1952
1953         Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock (), Glib::Threads::NOT_LOCK);
1954
1955         if (with_lock) {
1956                 lm.acquire ();
1957         }
1958
1959         /* If both inputs and outputs are auto-connected to physical ports,
1960            use the max of input and output offsets to ensure auto-connected
1961            port numbers always match up (e.g. the first audio input and the
1962            first audio output of the route will have the same physical
1963            port number).  Otherwise just use the lowest input or output
1964            offset possible.
1965         */
1966
1967         DEBUG_TRACE (DEBUG::Graph,
1968                      string_compose("Auto-connect: existing in = %1 out = %2\n",
1969                                     existing_inputs, existing_outputs));
1970
1971         const bool in_out_physical =
1972                 (Config->get_input_auto_connect() & AutoConnectPhysical)
1973                 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1974                 && connect_inputs;
1975
1976         const ChanCount in_offset = in_out_physical
1977                 ? ChanCount::max(existing_inputs, existing_outputs)
1978                 : existing_inputs;
1979
1980         const ChanCount out_offset = in_out_physical
1981                 ? ChanCount::max(existing_inputs, existing_outputs)
1982                 : existing_outputs;
1983
1984         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1985                 vector<string> physinputs;
1986                 vector<string> physoutputs;
1987
1988                 _engine.get_physical_outputs (*t, physoutputs);
1989                 _engine.get_physical_inputs (*t, physinputs);
1990
1991                 if (!physinputs.empty() && connect_inputs) {
1992                         uint32_t nphysical_in = physinputs.size();
1993
1994                         DEBUG_TRACE (DEBUG::Graph,
1995                                      string_compose("There are %1 physical inputs of type %2\n",
1996                                                     nphysical_in, *t));
1997
1998                         for (uint32_t i = input_start.get(*t); i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1999                                 string port;
2000
2001                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
2002                                         DEBUG_TRACE (DEBUG::Graph,
2003                                                      string_compose("Get index %1 + %2 % %3 = %4\n",
2004                                                                     in_offset.get(*t), i, nphysical_in,
2005                                                                     (in_offset.get(*t) + i) % nphysical_in));
2006                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
2007                                 }
2008
2009                                 DEBUG_TRACE (DEBUG::Graph,
2010                                              string_compose("Connect route %1 IN to %2\n",
2011                                                             route->name(), port));
2012
2013                                 if (!port.empty() && route->input()->connect (route->input()->ports().port(*t, i), port, this)) {
2014                                         break;
2015                                 }
2016
2017                                 ChanCount one_added (*t, 1);
2018                                 existing_inputs += one_added;
2019                         }
2020                 }
2021
2022                 if (!physoutputs.empty()) {
2023                         uint32_t nphysical_out = physoutputs.size();
2024                         for (uint32_t i = output_start.get(*t); i < route->n_outputs().get(*t); ++i) {
2025                                 string port;
2026
2027                                 if ((*t) == DataType::MIDI && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
2028                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
2029                                 } else if ((*t) == DataType::AUDIO && (Config->get_output_auto_connect() & AutoConnectMaster)) {
2030                                         /* master bus is audio only */
2031                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
2032                                                 port = _master_out->input()->ports().port(*t,
2033                                                                 i % _master_out->input()->n_ports().get(*t))->name();
2034                                         }
2035                                 }
2036
2037                                 DEBUG_TRACE (DEBUG::Graph,
2038                                              string_compose("Connect route %1 OUT to %2\n",
2039                                                             route->name(), port));
2040
2041                                 if (!port.empty() && route->output()->connect (route->output()->ports().port(*t, i), port, this)) {
2042                                         break;
2043                                 }
2044
2045                                 ChanCount one_added (*t, 1);
2046                                 existing_outputs += one_added;
2047                         }
2048                 }
2049         }
2050 }
2051
2052 /** Caller must not hold process lock
2053  *  @param name_template string to use for the start of the name, or "" to use "Audio".
2054  */
2055 list< boost::shared_ptr<AudioTrack> >
2056 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, 
2057                           uint32_t how_many, string name_template)
2058 {
2059         char track_name[32];
2060         uint32_t track_id = 0;
2061         string port;
2062         RouteList new_routes;
2063         list<boost::shared_ptr<AudioTrack> > ret;
2064
2065         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Audio");
2066
2067         while (how_many) {
2068                 if (!find_route_name (name_template.empty() ? _("Audio") : name_template, ++track_id, track_name, sizeof(track_name), use_number)) {
2069                         error << "cannot find name for new audio track" << endmsg;
2070                         goto failed;
2071                 }
2072
2073                 boost::shared_ptr<AudioTrack> track;
2074
2075                 try {
2076                         track.reset (new AudioTrack (*this, track_name, Route::Flag (0), mode));
2077
2078                         if (track->init ()) {
2079                                 goto failed;
2080                         }
2081
2082                         track->use_new_diskstream();
2083
2084 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2085                         // boost_debug_shared_ptr_mark_interesting (track.get(), "Track");
2086 #endif
2087                         {
2088                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2089
2090                                 if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2091                                         error << string_compose (
2092                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
2093                                                 input_channels, output_channels)
2094                                               << endmsg;
2095                                         goto failed;
2096                                 }
2097
2098                                 if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2099                                         error << string_compose (
2100                                                 _("cannot configure %1 in/%2 out configuration for new audio track"),
2101                                                 input_channels, output_channels)
2102                                               << endmsg;
2103                                         goto failed;
2104                                 }
2105                         }
2106
2107                         if (route_group) {
2108                                 route_group->add (track);
2109                         }
2110
2111                         track->non_realtime_input_change();
2112
2113                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
2114                         if (Config->get_remote_model() == UserOrdered) {
2115                                 track->set_remote_control_id (next_control_id());
2116                         }
2117
2118                         new_routes.push_back (track);
2119                         ret.push_back (track);
2120                 }
2121
2122                 catch (failed_constructor &err) {
2123                         error << _("Session: could not create new audio track.") << endmsg;
2124                         goto failed;
2125                 }
2126
2127                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2128
2129                         error << pfe.what() << endmsg;
2130                         goto failed;
2131                 }
2132
2133                 --how_many;
2134         }
2135
2136   failed:
2137         if (!new_routes.empty()) {
2138                 StateProtector sp (this);
2139                 add_routes (new_routes, true, true, true);
2140         }
2141
2142         return ret;
2143 }
2144
2145 /** Caller must not hold process lock.
2146  *  @param name_template string to use for the start of the name, or "" to use "Bus".
2147  */
2148 RouteList
2149 Session::new_audio_route (int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many, string name_template)
2150 {
2151         char bus_name[32];
2152         uint32_t bus_id = 0;
2153         string port;
2154         RouteList ret;
2155
2156         bool const use_number = (how_many != 1) || name_template.empty () || name_template == _("Bus");
2157         
2158         while (how_many) {
2159                 if (!find_route_name (name_template.empty () ? _("Bus") : name_template, ++bus_id, bus_name, sizeof(bus_name), use_number)) {
2160                         error << "cannot find name for new audio bus" << endmsg;
2161                         goto failure;
2162                 }
2163
2164                 try {
2165                         boost::shared_ptr<Route> bus (new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO));
2166
2167                         if (bus->init ()) {
2168                                 goto failure;
2169                         }
2170
2171 #ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
2172                         // boost_debug_shared_ptr_mark_interesting (bus.get(), "Route");
2173 #endif
2174                         {
2175                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2176
2177                                 if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
2178                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2179                                                                  input_channels, output_channels)
2180                                               << endmsg;
2181                                         goto failure;
2182                                 }
2183
2184
2185                                 if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
2186                                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
2187                                                                  input_channels, output_channels)
2188                                               << endmsg;
2189                                         goto failure;
2190                                 }
2191                         }
2192
2193                         if (route_group) {
2194                                 route_group->add (bus);
2195                         }
2196                         if (Config->get_remote_model() == UserOrdered) {
2197                                 bus->set_remote_control_id (next_control_id());
2198                         }
2199
2200                         bus->add_internal_return ();
2201
2202                         ret.push_back (bus);
2203                         
2204                         ARDOUR::GUIIdle ();
2205                 }
2206
2207
2208                 catch (failed_constructor &err) {
2209                         error << _("Session: could not create new audio route.") << endmsg;
2210                         goto failure;
2211                 }
2212
2213                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2214                         error << pfe.what() << endmsg;
2215                         goto failure;
2216                 }
2217
2218
2219                 --how_many;
2220         }
2221
2222   failure:
2223         if (!ret.empty()) {
2224                 StateProtector sp (this);
2225                 add_routes (ret, false, true, true); // autoconnect outputs only
2226         }
2227
2228         return ret;
2229
2230 }
2231
2232 RouteList
2233 Session::new_route_from_template (uint32_t how_many, const std::string& template_path, const std::string& name_base)
2234 {
2235         RouteList ret;
2236         uint32_t control_id;
2237         XMLTree tree;
2238         uint32_t number = 0;
2239         const uint32_t being_added = how_many;
2240
2241         if (!tree.read (template_path.c_str())) {
2242                 return ret;
2243         }
2244
2245         XMLNode* node = tree.root();
2246
2247         IO::disable_connecting ();
2248
2249         control_id = next_control_id ();
2250
2251         while (how_many) {
2252
2253                 XMLNode node_copy (*node);
2254
2255                 /* Remove IDs of everything so that new ones are used */
2256                 node_copy.remove_property_recursively (X_("id"));
2257
2258                 try {
2259                         char name[32];
2260
2261                         if (!name_base.empty()) {
2262
2263                                 /* if we're adding more than one routes, force
2264                                  * all the names of the new routes to be
2265                                  * numbered, via the final parameter.
2266                                  */
2267
2268                                 if (!find_route_name (name_base.c_str(), ++number, name, sizeof(name), (being_added > 1))) {
2269                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2270                                         /*NOTREACHDE*/
2271                                 }
2272
2273                         } else {
2274
2275                                 string const route_name  = node_copy.property(X_("name"))->value ();
2276                         
2277                                 /* generate a new name by adding a number to the end of the template name */
2278                                 if (!find_route_name (route_name.c_str(), ++number, name, sizeof(name), true)) {
2279                                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
2280                                         /*NOTREACHED*/
2281                                 }
2282                         }
2283
2284                         /* set this name in the XML description that we are about to use */
2285                         Route::set_name_in_state (node_copy, name);
2286
2287                         /* trim bitslots from listen sends so that new ones are used */
2288                         XMLNodeList children = node_copy.children ();
2289                         for (XMLNodeList::iterator i = children.begin(); i != children.end(); ++i) {
2290                                 if ((*i)->name() == X_("Processor")) {
2291                                         XMLProperty* role = (*i)->property (X_("role"));
2292                                         if (role && role->value() == X_("Listen")) {
2293                                                 (*i)->remove_property (X_("bitslot"));
2294                                         }
2295                                 }
2296                         }
2297                         
2298                         boost::shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
2299
2300                         if (route == 0) {
2301                                 error << _("Session: cannot create track/bus from template description") << endmsg;
2302                                 goto out;
2303                         }
2304
2305                         if (boost::dynamic_pointer_cast<Track>(route)) {
2306                                 /* force input/output change signals so that the new diskstream
2307                                    picks up the configuration of the route. During session
2308                                    loading this normally happens in a different way.
2309                                 */
2310
2311                                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2312
2313                                 IOChange change (IOChange::Type (IOChange::ConfigurationChanged | IOChange::ConnectionsChanged));
2314                                 change.after = route->input()->n_ports();
2315                                 route->input()->changed (change, this);
2316                                 change.after = route->output()->n_ports();
2317                                 route->output()->changed (change, this);
2318                         }
2319
2320                         route->set_remote_control_id (control_id);
2321                         ++control_id;
2322
2323                         ret.push_back (route);
2324                 }
2325
2326                 catch (failed_constructor &err) {
2327                         error << _("Session: could not create new route from template") << endmsg;
2328                         goto out;
2329                 }
2330
2331                 catch (AudioEngine::PortRegistrationFailure& pfe) {
2332                         error << pfe.what() << endmsg;
2333                         goto out;
2334                 }
2335
2336                 --how_many;
2337         }
2338
2339   out:
2340         if (!ret.empty()) {
2341                 StateProtector sp (this);
2342                 add_routes (ret, true, true, true);
2343                 IO::enable_connecting ();
2344         }
2345
2346         return ret;
2347 }
2348
2349 void
2350 Session::add_routes (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect, bool save)
2351 {
2352         try {
2353                 PBD::Unwinder<bool> aip (_adding_routes_in_progress, true);
2354                 add_routes_inner (new_routes, input_auto_connect, output_auto_connect);
2355
2356         } catch (...) {
2357                 error << _("Adding new tracks/busses failed") << endmsg;
2358         }
2359
2360         graph_reordered ();
2361
2362         update_latency (true);
2363         update_latency (false);
2364                 
2365         set_dirty();
2366         
2367         if (save) {
2368                 save_state (_current_snapshot_name);
2369         }
2370         
2371         reassign_track_numbers();
2372
2373         RouteAdded (new_routes); /* EMIT SIGNAL */
2374 }
2375
2376 void
2377 Session::add_routes_inner (RouteList& new_routes, bool input_auto_connect, bool output_auto_connect)
2378 {
2379         ChanCount existing_inputs;
2380         ChanCount existing_outputs;
2381         uint32_t order = next_control_id();
2382
2383         if (_order_hint != 0) {
2384                 order = _order_hint;
2385                 _order_hint = 0;
2386         }
2387
2388         count_existing_track_channels (existing_inputs, existing_outputs);
2389
2390         {
2391                 RCUWriter<RouteList> writer (routes);
2392                 boost::shared_ptr<RouteList> r = writer.get_copy ();
2393                 r->insert (r->end(), new_routes.begin(), new_routes.end());
2394
2395                 /* if there is no control out and we're not in the middle of loading,
2396                    resort the graph here. if there is a control out, we will resort
2397                    toward the end of this method. if we are in the middle of loading,
2398                    we will resort when done.
2399                 */
2400
2401                 if (!_monitor_out && IO::connecting_legal) {
2402                         resort_routes_using (r);
2403                 }
2404         }
2405
2406         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2407
2408                 boost::weak_ptr<Route> wpr (*x);
2409                 boost::shared_ptr<Route> r (*x);
2410
2411                 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
2412                 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
2413                 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
2414                 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
2415                 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
2416                 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2417
2418                 if (r->is_master()) {
2419                         _master_out = r;
2420                 }
2421
2422                 if (r->is_monitor()) {
2423                         _monitor_out = r;
2424                 }
2425
2426                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2427                 if (tr) {
2428                         tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2429                         track_playlist_changed (boost::weak_ptr<Track> (tr));
2430                         tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2431
2432                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
2433                         if (mt) {
2434                                 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
2435                                 mt->output()->changed.connect_same_thread (*this, boost::bind (&Session::midi_output_change_handler, this, _1, _2, boost::weak_ptr<Route>(mt)));
2436                         }
2437                 }
2438
2439
2440                 if (input_auto_connect || output_auto_connect) {
2441                         auto_connect_route (r, existing_inputs, existing_outputs, true, input_auto_connect);
2442                 }
2443
2444                 /* order keys are a GUI responsibility but we need to set up
2445                    reasonable defaults because they also affect the remote control
2446                    ID in most situations.
2447                 */
2448
2449                 if (!r->has_order_key ()) {
2450                         if (r->is_auditioner()) {
2451                                 /* use an arbitrarily high value */
2452                                 r->set_order_key (UINT_MAX);
2453                         } else {
2454                                 DEBUG_TRACE (DEBUG::OrderKeys, string_compose ("while adding, set %1 to order key %2\n", r->name(), order));
2455                                 r->set_order_key (order);
2456                                 order++;
2457                         }
2458                 }
2459
2460                 ARDOUR::GUIIdle ();
2461         }
2462
2463         if (_monitor_out && IO::connecting_legal) {
2464                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());         
2465                 
2466                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2467                         if ((*x)->is_monitor()) {
2468                                 /* relax */
2469                         } else if ((*x)->is_master()) {
2470                                         /* relax */
2471                         } else {
2472                                 (*x)->enable_monitor_send ();
2473                         }
2474                 }
2475         }
2476 }
2477
2478 void
2479 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2480 {
2481         boost::shared_ptr<RouteList> r = routes.reader ();
2482         boost::shared_ptr<Send> s;
2483
2484         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2485                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2486                         s->amp()->gain_control()->set_value (0.0);
2487                 }
2488         }
2489 }
2490
2491 void
2492 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2493 {
2494         boost::shared_ptr<RouteList> r = routes.reader ();
2495         boost::shared_ptr<Send> s;
2496
2497         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2498                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2499                         s->amp()->gain_control()->set_value (1.0);
2500                 }
2501         }
2502 }
2503
2504 void
2505 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2506 {
2507         boost::shared_ptr<RouteList> r = routes.reader ();
2508         boost::shared_ptr<Send> s;
2509
2510         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2511                 if ((s = (*i)->internal_send_for (dest)) != 0) {
2512                         s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2513                 }
2514         }
2515 }
2516
2517 /** @param include_buses true to add sends to buses and tracks, false for just tracks */
2518 void
2519 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p, bool include_buses)
2520 {
2521         boost::shared_ptr<RouteList> r = routes.reader ();
2522         boost::shared_ptr<RouteList> t (new RouteList);
2523
2524         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2525                 /* no MIDI sends because there are no MIDI busses yet */
2526                 if (include_buses || boost::dynamic_pointer_cast<AudioTrack>(*i)) {
2527                         t->push_back (*i);
2528                 }
2529         }
2530
2531         add_internal_sends (dest, p, t);
2532 }
2533
2534 void
2535 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2536 {
2537         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2538                 add_internal_send (dest, (*i)->before_processor_for_placement (p), *i);
2539         }
2540 }
2541
2542 void
2543 Session::add_internal_send (boost::shared_ptr<Route> dest, int index, boost::shared_ptr<Route> sender)
2544 {
2545         add_internal_send (dest, sender->before_processor_for_index (index), sender);
2546 }
2547
2548 void
2549 Session::add_internal_send (boost::shared_ptr<Route> dest, boost::shared_ptr<Processor> before, boost::shared_ptr<Route> sender)
2550 {
2551         if (sender->is_monitor() || sender->is_master() || sender == dest || dest->is_monitor() || dest->is_master()) {
2552                 return;
2553         }
2554
2555         if (!dest->internal_return()) {
2556                 dest->add_internal_return ();
2557         }
2558
2559         sender->add_aux_send (dest, before);
2560
2561         graph_reordered ();
2562 }
2563
2564 void
2565 Session::remove_route (boost::shared_ptr<Route> route)
2566 {
2567         if (route == _master_out) {
2568                 return;
2569         }
2570
2571         route->set_solo (false, this);
2572
2573         {
2574                 RCUWriter<RouteList> writer (routes);
2575                 boost::shared_ptr<RouteList> rs = writer.get_copy ();
2576
2577                 rs->remove (route);
2578
2579                 /* deleting the master out seems like a dumb
2580                    idea, but its more of a UI policy issue
2581                    than our concern.
2582                 */
2583
2584                 if (route == _master_out) {
2585                         _master_out = boost::shared_ptr<Route> ();
2586                 }
2587
2588                 if (route == _monitor_out) {
2589                         _monitor_out.reset ();
2590                 }
2591
2592                 /* writer goes out of scope, forces route list update */
2593         }
2594
2595         update_route_solo_state ();
2596
2597         // We need to disconnect the route's inputs and outputs
2598
2599         route->input()->disconnect (0);
2600         route->output()->disconnect (0);
2601
2602         /* if the route had internal sends sending to it, remove them */
2603         if (route->internal_return()) {
2604
2605                 boost::shared_ptr<RouteList> r = routes.reader ();
2606                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2607                         boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2608                         if (s) {
2609                                 (*i)->remove_processor (s);
2610                         }
2611                 }
2612         }
2613
2614         /* if the monitoring section had a pointer to this route, remove it */
2615         if (_monitor_out && !route->is_master() && !route->is_monitor()) {
2616                 Glib::Threads::Mutex::Lock lm (AudioEngine::instance()->process_lock ());
2617                 PBD::Unwinder<bool> uw (ignore_route_processor_changes, true);
2618                 route->remove_aux_or_listen (_monitor_out);
2619         }
2620
2621         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2622         if (mt && mt->step_editing()) {
2623                 if (_step_editors > 0) {
2624                         _step_editors--;
2625                 }
2626         }
2627
2628         update_latency_compensation ();
2629         set_dirty();
2630
2631         /* Re-sort routes to remove the graph's current references to the one that is
2632          * going away, then flush old references out of the graph.
2633          */
2634
2635         resort_routes ();
2636         if (_process_graph) {
2637                 _process_graph->clear_other_chain ();
2638         }
2639
2640         /* get rid of it from the dead wood collection in the route list manager */
2641
2642         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2643
2644         routes.flush ();
2645
2646         /* try to cause everyone to drop their references */
2647
2648         route->drop_references ();
2649
2650         Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2651
2652         /* save the new state of the world */
2653
2654         if (save_state (_current_snapshot_name)) {
2655                 save_history (_current_snapshot_name);
2656         }
2657         reassign_track_numbers();
2658 }
2659
2660 void
2661 Session::route_mute_changed (void* /*src*/)
2662 {
2663         set_dirty ();
2664 }
2665
2666 void
2667 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2668 {
2669         boost::shared_ptr<Route> route = wpr.lock();
2670         if (!route) {
2671                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2672                 return;
2673         }
2674
2675         if (route->listening_via_monitor ()) {
2676
2677                 if (Config->get_exclusive_solo()) {
2678                         /* new listen: disable all other listen */
2679                         boost::shared_ptr<RouteList> r = routes.reader ();
2680                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2681                                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner()) {
2682                                         continue;
2683                                 }
2684                                 (*i)->set_listen (false, this);
2685                         }
2686                 }
2687
2688                 _listen_cnt++;
2689
2690         } else if (_listen_cnt > 0) {
2691
2692                 _listen_cnt--;
2693         }
2694
2695         update_route_solo_state ();
2696 }
2697 void
2698 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2699 {
2700         boost::shared_ptr<Route> route = wpr.lock ();
2701
2702         if (!route) {
2703                 /* should not happen */
2704                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2705                 return;
2706         }
2707
2708         bool send_changed = false;
2709
2710         if (route->solo_isolated()) {
2711                 if (_solo_isolated_cnt == 0) {
2712                         send_changed = true;
2713                 }
2714                 _solo_isolated_cnt++;
2715         } else if (_solo_isolated_cnt > 0) {
2716                 _solo_isolated_cnt--;
2717                 if (_solo_isolated_cnt == 0) {
2718                         send_changed = true;
2719                 }
2720         }
2721
2722         if (send_changed) {
2723                 IsolatedChanged (); /* EMIT SIGNAL */
2724         }
2725 }
2726
2727 void
2728 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2729 {
2730         DEBUG_TRACE (DEBUG::Solo, string_compose ("route solo change, self = %1\n", self_solo_change));
2731
2732         if (!self_solo_change) {
2733                 // session doesn't care about changes to soloed-by-others
2734                 return;
2735         }
2736
2737         if (solo_update_disabled) {
2738                 // We know already
2739                 DEBUG_TRACE (DEBUG::Solo, "solo update disabled - changed ignored\n");
2740                 return;
2741         }
2742
2743         boost::shared_ptr<Route> route = wpr.lock ();
2744         assert (route);
2745
2746         boost::shared_ptr<RouteList> r = routes.reader ();
2747         int32_t delta;
2748
2749         if (route->self_soloed()) {
2750                 delta = 1;
2751         } else {
2752                 delta = -1;
2753         }
2754
2755         RouteGroup* rg = route->route_group ();
2756         bool leave_group_alone = (rg && rg->is_active() && rg->is_solo());
2757
2758         if (delta == 1 && Config->get_exclusive_solo()) {
2759                 
2760                 /* new solo: disable all other solos, but not the group if its solo-enabled */
2761
2762                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2763                         if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2764                             (leave_group_alone && ((*i)->route_group() == rg))) {
2765                                 continue;
2766                         }
2767                         (*i)->set_solo (false, this);
2768                 }
2769         }
2770
2771         DEBUG_TRACE (DEBUG::Solo, string_compose ("propagate solo change, delta = %1\n", delta));
2772
2773         solo_update_disabled = true;
2774
2775         RouteList uninvolved;
2776
2777         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1\n", route->name()));
2778
2779         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2780                 bool via_sends_only;
2781                 bool in_signal_flow;
2782
2783                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_auditioner() ||
2784                     (leave_group_alone && ((*i)->route_group() == rg))) {
2785                         continue;
2786                 }
2787
2788                 in_signal_flow = false;
2789
2790                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed from %1\n", (*i)->name()));
2791                 
2792                 if ((*i)->feeds (route, &via_sends_only)) {
2793                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a feed from %1\n", (*i)->name()));
2794                         if (!via_sends_only) {
2795                                 if (!route->soloed_by_others_upstream()) {
2796                                         (*i)->mod_solo_by_others_downstream (delta);
2797                                 }
2798                         } else {
2799                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tthere is a send-only feed from %1\n", (*i)->name()));
2800                         }
2801                         in_signal_flow = true;
2802                 } else {
2803                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tno feed from %1\n", (*i)->name()));
2804                 }
2805                 
2806                 DEBUG_TRACE (DEBUG::Solo, string_compose ("check feed to %1\n", (*i)->name()));
2807
2808                 if (route->feeds (*i, &via_sends_only)) {
2809                         /* propagate solo upstream only if routing other than
2810                            sends is involved, but do consider the other route
2811                            (*i) to be part of the signal flow even if only
2812                            sends are involved.
2813                         */
2814                         DEBUG_TRACE (DEBUG::Solo, string_compose ("%1 feeds %2 via sends only %3 sboD %4 sboU %5\n",
2815                                                                   route->name(),
2816                                                                   (*i)->name(),
2817                                                                   via_sends_only,
2818                                                                   route->soloed_by_others_downstream(),
2819                                                                   route->soloed_by_others_upstream()));
2820                         if (!via_sends_only) {
2821                                 if (!route->soloed_by_others_downstream()) {
2822                                         DEBUG_TRACE (DEBUG::Solo, string_compose ("\tmod %1 by %2\n", (*i)->name(), delta));
2823                                         (*i)->mod_solo_by_others_upstream (delta);
2824                                 } else {
2825                                         DEBUG_TRACE (DEBUG::Solo, "\talready soloed by others downstream\n");
2826                                 }
2827                         } else {
2828                                 DEBUG_TRACE (DEBUG::Solo, string_compose ("\tfeed to %1 ignored, sends-only\n", (*i)->name()));
2829                         }
2830                         in_signal_flow = true;
2831                 } else {
2832                         DEBUG_TRACE (DEBUG::Solo, "\tno feed to\n");
2833                 }
2834
2835                 if (!in_signal_flow) {
2836                         uninvolved.push_back (*i);
2837                 }
2838         }
2839
2840         solo_update_disabled = false;
2841         DEBUG_TRACE (DEBUG::Solo, "propagation complete\n");
2842
2843         update_route_solo_state (r);
2844
2845         /* now notify that the mute state of the routes not involved in the signal
2846            pathway of the just-solo-changed route may have altered.
2847         */
2848
2849         for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2850                 DEBUG_TRACE (DEBUG::Solo, string_compose ("mute change for %1, which neither feeds or is fed by %2\n", (*i)->name(), route->name()));
2851                 (*i)->mute_changed (this);
2852         }
2853
2854         SoloChanged (); /* EMIT SIGNAL */
2855         set_dirty();
2856 }
2857
2858 void
2859 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2860 {
2861         /* now figure out if anything that matters is soloed (or is "listening")*/
2862
2863         bool something_soloed = false;
2864         uint32_t listeners = 0;
2865         uint32_t isolated = 0;
2866
2867         if (!r) {
2868                 r = routes.reader();
2869         }
2870
2871         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2872                 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner() && (*i)->self_soloed()) {
2873                         something_soloed = true;
2874                 }
2875
2876                 if (!(*i)->is_auditioner() && (*i)->listening_via_monitor()) {
2877                         if (Config->get_solo_control_is_listen_control()) {
2878                                 listeners++;
2879                         } else {
2880                                 (*i)->set_listen (false, this);
2881                         }
2882                 }
2883
2884                 if ((*i)->solo_isolated()) {
2885                         isolated++;
2886                 }
2887         }
2888
2889         if (something_soloed != _non_soloed_outs_muted) {
2890                 _non_soloed_outs_muted = something_soloed;
2891                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2892         }
2893
2894         _listen_cnt = listeners;
2895
2896         if (isolated != _solo_isolated_cnt) {
2897                 _solo_isolated_cnt = isolated;
2898                 IsolatedChanged (); /* EMIT SIGNAL */
2899         }
2900
2901         DEBUG_TRACE (DEBUG::Solo, string_compose ("solo state updated by session, soloed? %1 listeners %2 isolated %3\n",
2902                                                   something_soloed, listeners, isolated));
2903 }
2904
2905 boost::shared_ptr<RouteList>
2906 Session::get_routes_with_internal_returns() const
2907 {
2908         boost::shared_ptr<RouteList> r = routes.reader ();
2909         boost::shared_ptr<RouteList> rl (new RouteList);
2910
2911         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2912                 if ((*i)->internal_return ()) {
2913                         rl->push_back (*i);
2914                 }
2915         }
2916         return rl;
2917 }
2918
2919 bool
2920 Session::io_name_is_legal (const std::string& name)
2921 {
2922         boost::shared_ptr<RouteList> r = routes.reader ();
2923
2924         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2925                 if ((*i)->name() == name) {
2926                         return false;
2927                 }
2928
2929                 if ((*i)->has_io_processor_named (name)) {
2930                         return false;
2931                 }
2932         }
2933
2934         return true;
2935 }
2936
2937 void
2938 Session::set_exclusive_input_active (boost::shared_ptr<RouteList> rl, bool onoff, bool flip_others)
2939 {
2940         RouteList rl2;
2941         vector<string> connections;
2942
2943         /* if we are passed only a single route and we're not told to turn
2944          * others off, then just do the simple thing.
2945          */
2946
2947         if (flip_others == false && rl->size() == 1) {
2948                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (rl->front());
2949                 if (mt) {
2950                         mt->set_input_active (onoff);
2951                         return;
2952                 }
2953         }
2954
2955         for (RouteList::iterator rt = rl->begin(); rt != rl->end(); ++rt) {
2956
2957                 PortSet& ps ((*rt)->input()->ports());
2958                 
2959                 for (PortSet::iterator p = ps.begin(); p != ps.end(); ++p) {
2960                         p->get_connections (connections);
2961                 }
2962                 
2963                 for (vector<string>::iterator s = connections.begin(); s != connections.end(); ++s) {
2964                         routes_using_input_from (*s, rl2);
2965                 }
2966                 
2967                 /* scan all relevant routes to see if others are on or off */
2968                 
2969                 bool others_are_already_on = false;
2970                 
2971                 for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2972
2973                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2974
2975                         if (!mt) {
2976                                 continue;
2977                         }
2978
2979                         if ((*r) != (*rt)) {
2980                                 if (mt->input_active()) {
2981                                         others_are_already_on = true;
2982                                 }
2983                         } else {
2984                                 /* this one needs changing */
2985                                 mt->set_input_active (onoff);
2986                         }
2987                 }
2988                 
2989                 if (flip_others) {
2990
2991                         /* globally reverse other routes */
2992                         
2993                         for (RouteList::iterator r = rl2.begin(); r != rl2.end(); ++r) {
2994                                 if ((*r) != (*rt)) {
2995                                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (*r);
2996                                         if (mt) {
2997                                                 mt->set_input_active (!others_are_already_on);
2998                                         }
2999                                 }
3000                         }
3001                 }
3002         }
3003 }
3004
3005 void
3006 Session::routes_using_input_from (const string& str, RouteList& rl)
3007 {
3008         boost::shared_ptr<RouteList> r = routes.reader();
3009
3010         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3011                 if ((*i)->input()->connected_to (str)) {
3012                         rl.push_back (*i);
3013                 }
3014         }
3015 }
3016
3017 boost::shared_ptr<Route>
3018 Session::route_by_name (string name)
3019 {
3020         boost::shared_ptr<RouteList> r = routes.reader ();
3021
3022         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3023                 if ((*i)->name() == name) {
3024                         return *i;
3025                 }
3026         }
3027
3028         return boost::shared_ptr<Route> ((Route*) 0);
3029 }
3030
3031 boost::shared_ptr<Route>
3032 Session::route_by_id (PBD::ID id)
3033 {
3034         boost::shared_ptr<RouteList> r = routes.reader ();
3035
3036         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3037                 if ((*i)->id() == id) {
3038                         return *i;
3039                 }
3040         }
3041
3042         return boost::shared_ptr<Route> ((Route*) 0);
3043 }
3044
3045 boost::shared_ptr<Track>
3046 Session::track_by_diskstream_id (PBD::ID id)
3047 {
3048         boost::shared_ptr<RouteList> r = routes.reader ();
3049
3050         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3051                 boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3052                 if (t && t->using_diskstream_id (id)) {
3053                         return t;
3054                 }
3055         }
3056
3057         return boost::shared_ptr<Track> ();
3058 }
3059
3060 boost::shared_ptr<Route>
3061 Session::route_by_remote_id (uint32_t id)
3062 {
3063         boost::shared_ptr<RouteList> r = routes.reader ();
3064
3065         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3066                 if ((*i)->remote_control_id() == id) {
3067                         return *i;
3068                 }
3069         }
3070
3071         return boost::shared_ptr<Route> ((Route*) 0);
3072 }
3073
3074
3075 void
3076 Session::reassign_track_numbers ()
3077 {
3078         int64_t tn = 0;
3079         int64_t bn = 0;
3080         RouteList r (*(routes.reader ()));
3081         SignalOrderRouteSorter sorter;
3082         r.sort (sorter);
3083
3084         StateProtector sp (this);
3085
3086         for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3087                 if (boost::dynamic_pointer_cast<Track> (*i)) {
3088                         (*i)->set_track_number(++tn);
3089                 }
3090                 else if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_auditioner()) {
3091                         (*i)->set_track_number(--bn);
3092                 }
3093         }
3094         const uint32_t decimals = ceilf (log10f (tn + 1));
3095         const bool decimals_changed = _track_number_decimals != decimals;
3096         _track_number_decimals = decimals;
3097
3098         if (decimals_changed && config.get_track_name_number ()) {
3099                 for (RouteList::iterator i = r.begin(); i != r.end(); ++i) {
3100                         boost::shared_ptr<Track> t = boost::dynamic_pointer_cast<Track> (*i);
3101                         if (t) {
3102                                 t->resync_track_name();
3103                         }
3104                 }
3105                 // trigger GUI re-layout
3106                 config.ParameterChanged("track-name-number");
3107         }
3108 }
3109
3110 void
3111 Session::playlist_region_added (boost::weak_ptr<Region> w)
3112 {
3113         boost::shared_ptr<Region> r = w.lock ();
3114         if (!r) {
3115                 return;
3116         }
3117
3118         /* These are the operations that are currently in progress... */
3119         list<GQuark> curr = _current_trans_quarks;
3120         curr.sort ();
3121
3122         /* ...and these are the operations during which we want to update
3123            the session range location markers.
3124         */
3125         list<GQuark> ops;
3126         ops.push_back (Operations::capture);
3127         ops.push_back (Operations::paste);
3128         ops.push_back (Operations::duplicate_region);
3129         ops.push_back (Operations::insert_file);
3130         ops.push_back (Operations::insert_region);
3131         ops.push_back (Operations::drag_region_brush);
3132         ops.push_back (Operations::region_drag);
3133         ops.push_back (Operations::selection_grab);
3134         ops.push_back (Operations::region_fill);
3135         ops.push_back (Operations::fill_selection);
3136         ops.push_back (Operations::create_region);
3137         ops.push_back (Operations::region_copy);
3138         ops.push_back (Operations::fixed_time_region_copy);
3139         ops.sort ();
3140
3141         /* See if any of the current operations match the ones that we want */
3142         list<GQuark> in;
3143         set_intersection (_current_trans_quarks.begin(), _current_trans_quarks.end(), ops.begin(), ops.end(), back_inserter (in));
3144
3145         /* If so, update the session range markers */
3146         if (!in.empty ()) {
3147                 maybe_update_session_range (r->position (), r->last_frame ());
3148         }
3149 }
3150
3151 /** Update the session range markers if a is before the current start or
3152  *  b is after the current end.
3153  */
3154 void
3155 Session::maybe_update_session_range (framepos_t a, framepos_t b)
3156 {
3157         if (_state_of_the_state & Loading) {
3158                 return;
3159         }
3160
3161         if (_session_range_location == 0) {
3162
3163                 add_session_range_location (a, b);
3164
3165         } else {
3166
3167                 if (a < _session_range_location->start()) {
3168                         _session_range_location->set_start (a);
3169                 }
3170
3171                 if (b > _session_range_location->end()) {
3172                         _session_range_location->set_end (b);
3173                 }
3174         }
3175 }
3176
3177 void
3178 Session::playlist_ranges_moved (list<Evoral::RangeMove<framepos_t> > const & ranges)
3179 {
3180         for (list<Evoral::RangeMove<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3181                 maybe_update_session_range (i->to, i->to + i->length);
3182         }
3183 }
3184
3185 void
3186 Session::playlist_regions_extended (list<Evoral::Range<framepos_t> > const & ranges)
3187 {
3188         for (list<Evoral::Range<framepos_t> >::const_iterator i = ranges.begin(); i != ranges.end(); ++i) {
3189                 maybe_update_session_range (i->from, i->to);
3190         }
3191 }
3192
3193 /* Region management */
3194
3195 boost::shared_ptr<Region>
3196 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
3197 {
3198         const RegionFactory::RegionMap& regions (RegionFactory::regions());
3199         RegionFactory::RegionMap::const_iterator i;
3200         boost::shared_ptr<Region> region;
3201
3202         Glib::Threads::Mutex::Lock lm (region_lock);
3203
3204         for (i = regions.begin(); i != regions.end(); ++i) {
3205
3206                 region = i->second;
3207
3208                 if (region->whole_file()) {
3209
3210                         if (child->source_equivalent (region)) {
3211                                 return region;
3212                         }
3213                 }
3214         }
3215
3216         return boost::shared_ptr<Region> ();
3217 }
3218
3219 int
3220 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
3221 {
3222         set<boost::shared_ptr<Region> > relevant_regions;
3223
3224         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
3225                 RegionFactory::get_regions_using_source (*s, relevant_regions);
3226         }
3227
3228         for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
3229                 set<boost::shared_ptr<Region> >::iterator tmp;
3230
3231                 tmp = r;
3232                 ++tmp;
3233
3234                 playlists->destroy_region (*r);
3235                 RegionFactory::map_remove (*r);
3236
3237                 (*r)->drop_sources ();
3238                 (*r)->drop_references ();
3239
3240                 relevant_regions.erase (r);
3241
3242                 r = tmp;
3243         }
3244
3245         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
3246
3247                 {
3248                         Glib::Threads::Mutex::Lock ls (source_lock);
3249                         /* remove from the main source list */
3250                         sources.erase ((*s)->id());
3251                 }
3252
3253                 (*s)->mark_for_remove ();
3254                 (*s)->drop_references ();
3255
3256                 s = srcs.erase (s);
3257         }
3258
3259         return 0;
3260 }
3261
3262 int
3263 Session::remove_last_capture ()
3264 {
3265         list<boost::shared_ptr<Source> > srcs;
3266
3267         boost::shared_ptr<RouteList> rl = routes.reader ();
3268         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3269                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3270                 if (!tr) {
3271                         continue;
3272                 }
3273
3274                 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
3275
3276                 if (!l.empty()) {
3277                         srcs.insert (srcs.end(), l.begin(), l.end());
3278                         l.clear ();
3279                 }
3280         }
3281
3282         destroy_sources (srcs);
3283
3284         save_state (_current_snapshot_name);
3285
3286         return 0;
3287 }
3288
3289 /* Source Management */
3290
3291 void
3292 Session::add_source (boost::shared_ptr<Source> source)
3293 {
3294         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3295         pair<SourceMap::iterator,bool> result;
3296
3297         entry.first = source->id();
3298         entry.second = source;
3299
3300         {
3301                 Glib::Threads::Mutex::Lock lm (source_lock);
3302                 result = sources.insert (entry);
3303         }
3304
3305         if (result.second) {
3306
3307                 /* yay, new source */
3308
3309                 boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (source);
3310                 
3311                 if (fs) {
3312                         if (!fs->within_session()) {
3313                                 ensure_search_path_includes (Glib::path_get_dirname (fs->path()), fs->type());
3314                         }
3315                 }
3316                 
3317                 set_dirty();
3318
3319                 boost::shared_ptr<AudioFileSource> afs;
3320
3321                 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3322                         if (Config->get_auto_analyse_audio()) {
3323                                 Analyser::queue_source_for_analysis (source, false);
3324                         }
3325                 }
3326
3327                 source->DropReferences.connect_same_thread (*this, boost::bind (&Session::remove_source, this, boost::weak_ptr<Source> (source)));
3328         }
3329 }
3330
3331 void
3332 Session::remove_source (boost::weak_ptr<Source> src)
3333 {
3334         if (_state_of_the_state & Deletion) {
3335                 return;
3336         }
3337
3338         SourceMap::iterator i;
3339         boost::shared_ptr<Source> source = src.lock();
3340
3341         if (!source) {
3342                 return;
3343         }
3344
3345         {
3346                 Glib::Threads::Mutex::Lock lm (source_lock);
3347
3348                 if ((i = sources.find (source->id())) != sources.end()) {
3349                         sources.erase (i);
3350                 }
3351         }
3352
3353         if (!(_state_of_the_state & InCleanup)) {
3354
3355                 /* save state so we don't end up with a session file
3356                    referring to non-existent sources.
3357                 */
3358
3359                 save_state (_current_snapshot_name);
3360         }
3361 }
3362
3363 boost::shared_ptr<Source>
3364 Session::source_by_id (const PBD::ID& id)
3365 {
3366         Glib::Threads::Mutex::Lock lm (source_lock);
3367         SourceMap::iterator i;
3368         boost::shared_ptr<Source> source;
3369
3370         if ((i = sources.find (id)) != sources.end()) {
3371                 source = i->second;
3372         }
3373
3374         return source;
3375 }
3376
3377 boost::shared_ptr<AudioFileSource>
3378 Session::audio_source_by_path_and_channel (const string& path, uint16_t chn) const
3379 {
3380         /* Restricted to audio files because only audio sources have channel
3381            as a property.
3382         */
3383
3384         Glib::Threads::Mutex::Lock lm (source_lock);
3385
3386         for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i) {
3387                 boost::shared_ptr<AudioFileSource> afs
3388                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3389
3390                 if (afs && afs->path() == path && chn == afs->channel()) {
3391                         return afs;
3392                 }
3393         }
3394
3395         return boost::shared_ptr<AudioFileSource>();
3396 }
3397
3398 boost::shared_ptr<MidiSource>
3399 Session::midi_source_by_path (const std::string& path) const
3400 {
3401         /* Restricted to MIDI files because audio sources require a channel
3402            for unique identification, in addition to a path.
3403         */
3404
3405         Glib::Threads::Mutex::Lock lm (source_lock);
3406
3407         for (SourceMap::const_iterator s = sources.begin(); s != sources.end(); ++s) {
3408                 boost::shared_ptr<MidiSource> ms
3409                         = boost::dynamic_pointer_cast<MidiSource>(s->second);
3410                 boost::shared_ptr<FileSource> fs
3411                         = boost::dynamic_pointer_cast<FileSource>(s->second);
3412                 
3413                 if (ms && fs && fs->path() == path) {
3414                         return ms;
3415                 }
3416         }
3417
3418         return boost::shared_ptr<MidiSource>();
3419 }
3420
3421 uint32_t
3422 Session::count_sources_by_origin (const string& path)
3423 {
3424         uint32_t cnt = 0;
3425         Glib::Threads::Mutex::Lock lm (source_lock);
3426
3427         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3428                 boost::shared_ptr<FileSource> fs
3429                         = boost::dynamic_pointer_cast<FileSource>(i->second);
3430
3431                 if (fs && fs->origin() == path) {
3432                         ++cnt;
3433                 }
3434         }
3435
3436         return cnt;
3437 }
3438
3439 string
3440 Session::peak_path (string base) const
3441 {
3442         return Glib::build_filename (_session_dir->peak_path(), base + peakfile_suffix);
3443 }
3444
3445 /** Return a unique name based on \a base for a new internal audio source */
3446 string
3447 Session::new_audio_source_path (const string& base, uint32_t nchan, uint32_t chan, bool destructive, bool take_required)
3448 {
3449         uint32_t cnt;
3450         string possible_name;
3451         const uint32_t limit = 9999; // arbitrary limit on number of files with the same basic name
3452         string legalized;
3453         string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3454         bool some_related_source_name_exists = false;
3455
3456         possible_name[0] = '\0';
3457         legalized = legalize_for_path (base);
3458
3459         std::vector<string> sdirs = source_search_path(DataType::AUDIO);
3460
3461         // Find a "version" of the base name that doesn't exist in any of the possible directories.
3462
3463         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3464
3465                 vector<space_and_path>::iterator i;
3466                 uint32_t existing = 0;
3467
3468                 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
3469
3470                         ostringstream sstr;
3471
3472                         if (destructive) {
3473                                 sstr << 'T';
3474                                 sstr << setfill ('0') << setw (4) << cnt;
3475                                 sstr << legalized;
3476                         } else {
3477                                 sstr << legalized;
3478                                 
3479                                 if (take_required || some_related_source_name_exists) {
3480                                         sstr << '-';
3481                                         sstr << cnt;
3482                                 }
3483                         }
3484                         
3485                         if (nchan == 2) {
3486                                 if (chan == 0) {
3487                                         sstr << "%L";
3488                                 } else {
3489                                         sstr << "%R";
3490                                 }
3491                         } else if (nchan > 2 && nchan < 26) {
3492                                 sstr << '%';
3493                                 sstr << 'a' + chan;
3494                         } 
3495
3496                         sstr << ext;
3497
3498                         possible_name = sstr.str();
3499                         const string spath = (*i);
3500
3501                         /* note that we search *without* the extension so that
3502                            we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf"
3503                            in the event that this new name is required for
3504                            a file format change.
3505                         */
3506
3507                         if (matching_unsuffixed_filename_exists_in (spath, possible_name)) {
3508                                 existing++;
3509                                 break;
3510                         }
3511
3512                         /* it is possible that we have the path already
3513                          * assigned to a source that has not yet been written
3514                          * (ie. the write source for a diskstream). we have to
3515                          * check this in order to make sure that our candidate
3516                          * path isn't used again, because that can lead to
3517                          * two Sources point to the same file with different
3518                          * notions of their removability.
3519                          */
3520
3521                         string possible_path = Glib::build_filename (spath, possible_name);
3522
3523                         if (audio_source_by_path_and_channel (possible_path, chan)) {
3524                                 existing++;
3525                                 break;
3526                         }
3527                 }
3528
3529                 if (existing == 0) {
3530                         break;
3531                 }
3532
3533                 some_related_source_name_exists = true;
3534
3535                 if (cnt > limit) {
3536                         error << string_compose(
3537                                         _("There are already %1 recordings for %2, which I consider too many."),
3538                                         limit, base) << endmsg;
3539                         destroy ();
3540                         throw failed_constructor();
3541                 }
3542         }
3543
3544         /* We've established that the new name does not exist in any session
3545          * directory, so now find out which one we should use for this new
3546          * audio source.
3547          */
3548
3549         SessionDirectory sdir (get_best_session_directory_for_new_audio());
3550
3551         std::string s = Glib::build_filename (sdir.sound_path(), possible_name);
3552
3553         return s;
3554 }
3555
3556 /** Return a unique name based on \a owner_name for a new internal MIDI source */
3557 string
3558 Session::new_midi_source_path (const string& base)
3559 {
3560         uint32_t cnt;
3561         char buf[PATH_MAX+1];
3562         const uint32_t limit = 10000;
3563         string legalized;
3564         string possible_path;
3565         string possible_name;
3566
3567         buf[0] = '\0';
3568         legalized = legalize_for_path (base);
3569
3570         // Find a "version" of the file name that doesn't exist in any of the possible directories.
3571         std::vector<string> sdirs = source_search_path(DataType::MIDI);
3572
3573         /* - the main session folder is the first in the vector.
3574          * - after checking all locations for file-name uniqueness,
3575          *   we keep the one from the last iteration as new file name
3576          * - midi files are small and should just be kept in the main session-folder
3577          *
3578          * -> reverse the array, check main session folder last and use that as location
3579          *    for MIDI files.
3580          */
3581         std::reverse(sdirs.begin(), sdirs.end());
3582
3583         for (cnt = 1; cnt <= limit; ++cnt) {
3584
3585                 vector<space_and_path>::iterator i;
3586                 uint32_t existing = 0;
3587                 
3588                 for (vector<string>::const_iterator i = sdirs.begin(); i != sdirs.end(); ++i) {
3589
3590                         snprintf (buf, sizeof(buf), "%s-%u.mid", legalized.c_str(), cnt);
3591                         possible_name = buf;
3592
3593                         possible_path = Glib::build_filename (*i, possible_name);
3594                         
3595                         if (Glib::file_test (possible_path, Glib::FILE_TEST_EXISTS)) {
3596                                 existing++;
3597                         }
3598
3599                         if (midi_source_by_path (possible_path)) {
3600                                 existing++;
3601                         }
3602                 }
3603
3604                 if (existing == 0) {
3605                         break;
3606                 }
3607
3608                 if (cnt > limit) {
3609                         error << string_compose(
3610                                         _("There are already %1 recordings for %2, which I consider too many."),
3611                                         limit, base) << endmsg;
3612                         destroy ();
3613                         return 0;
3614                 }
3615         }
3616
3617         /* No need to "find best location" for software/app-based RAID, because
3618            MIDI is so small that we always put it in the same place.
3619         */
3620
3621         return possible_path;
3622 }
3623
3624
3625 /** Create a new within-session audio source */
3626 boost::shared_ptr<AudioFileSource>
3627 Session::create_audio_source_for_session (size_t n_chans, string const & base, uint32_t chan, bool destructive)
3628 {
3629         const string path = new_audio_source_path (base, n_chans, chan, destructive, true);
3630
3631         if (!path.empty()) {
3632                 return boost::dynamic_pointer_cast<AudioFileSource> (
3633                         SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3634         } else {
3635                 throw failed_constructor ();
3636         }
3637 }
3638
3639 /** Create a new within-session MIDI source */
3640 boost::shared_ptr<MidiSource>
3641 Session::create_midi_source_for_session (string const & basic_name)
3642 {
3643         const string path = new_midi_source_path (basic_name);
3644         
3645         if (!path.empty()) {
3646                 return boost::dynamic_pointer_cast<SMFSource> (
3647                         SourceFactory::createWritable (
3648                                 DataType::MIDI, *this, path, false, frame_rate()));
3649         } else {
3650                 throw failed_constructor ();
3651         }
3652 }
3653
3654 /** Create a new within-session MIDI source */
3655 boost::shared_ptr<MidiSource>
3656 Session::create_midi_source_by_stealing_name (boost::shared_ptr<Track> track)
3657 {
3658         /* the caller passes in the track the source will be used in,
3659            so that we can keep the numbering sane. 
3660            
3661            Rationale: a track with the name "Foo" that has had N
3662            captures carried out so far will ALREADY have a write source
3663            named "Foo-N+1.mid" waiting to be used for the next capture.
3664            
3665            If we call new_midi_source_name() we will get "Foo-N+2". But
3666            there is no region corresponding to "Foo-N+1", so when
3667            "Foo-N+2" appears in the track, the gap presents the user
3668            with odd behaviour - why did it skip past Foo-N+1?
3669            
3670            We could explain this to the user in some odd way, but
3671            instead we rename "Foo-N+1.mid" as "Foo-N+2.mid", and then
3672            use "Foo-N+1" here.
3673            
3674            If that attempted rename fails, we get "Foo-N+2.mid" anyway.
3675         */
3676         
3677         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (track);
3678         assert (mt);
3679         std::string name = track->steal_write_source_name ();
3680
3681         if (name.empty()) {
3682                 return boost::shared_ptr<MidiSource>();
3683         }
3684
3685         const string path = new_midi_source_path (name);
3686
3687         return boost::dynamic_pointer_cast<SMFSource> (
3688                 SourceFactory::createWritable (
3689                         DataType::MIDI, *this, path, false, frame_rate()));
3690 }
3691
3692
3693 void
3694 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3695 {
3696         if (playlist->hidden()) {
3697                 return;
3698         }
3699
3700         playlists->add (playlist);
3701
3702         if (unused) {
3703                 playlist->release();
3704         }
3705
3706         set_dirty();
3707 }
3708
3709 void
3710 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3711 {
3712         if (_state_of_the_state & Deletion) {
3713                 return;
3714         }
3715
3716         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3717
3718         if (!playlist) {
3719                 return;
3720         }
3721
3722         playlists->remove (playlist);
3723
3724         set_dirty();
3725 }
3726
3727 void
3728 Session::set_audition (boost::shared_ptr<Region> r)
3729 {
3730         pending_audition_region = r;
3731         add_post_transport_work (PostTransportAudition);
3732         _butler->schedule_transport_work ();
3733 }
3734
3735 void
3736 Session::audition_playlist ()
3737 {
3738         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3739         ev->region.reset ();
3740         queue_event (ev);
3741 }
3742
3743 void
3744 Session::non_realtime_set_audition ()
3745 {
3746         assert (pending_audition_region);
3747         auditioner->audition_region (pending_audition_region);
3748         pending_audition_region.reset ();
3749         AuditionActive (true); /* EMIT SIGNAL */
3750 }
3751
3752 void
3753 Session::audition_region (boost::shared_ptr<Region> r)
3754 {
3755         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3756         ev->region = r;
3757         queue_event (ev);
3758 }
3759
3760 void
3761 Session::cancel_audition ()
3762 {
3763         if (!auditioner) {
3764                 return;
3765         }
3766         if (auditioner->auditioning()) {
3767                 auditioner->cancel_audition ();
3768                 AuditionActive (false); /* EMIT SIGNAL */
3769         }
3770 }
3771
3772 bool
3773 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3774 {
3775         if (a->is_monitor()) {
3776                 return true;
3777         }
3778         if (b->is_monitor()) {
3779                 return false;
3780         }
3781         return a->order_key () < b->order_key ();
3782 }
3783
3784 bool
3785 Session::is_auditioning () const
3786 {
3787         /* can be called before we have an auditioner object */
3788         if (auditioner) {
3789                 return auditioner->auditioning();
3790         } else {
3791                 return false;
3792         }
3793 }
3794
3795 void
3796 Session::graph_reordered ()
3797 {
3798         /* don't do this stuff if we are setting up connections
3799            from a set_state() call or creating new tracks. Ditto for deletion.
3800         */
3801
3802         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
3803                 return;
3804         }
3805
3806         /* every track/bus asked for this to be handled but it was deferred because
3807            we were connecting. do it now.
3808         */
3809
3810         request_input_change_handling ();
3811
3812         resort_routes ();
3813
3814         /* force all diskstreams to update their capture offset values to
3815            reflect any changes in latencies within the graph.
3816         */
3817
3818         boost::shared_ptr<RouteList> rl = routes.reader ();
3819         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3820                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3821                 if (tr) {
3822                         tr->set_capture_offset ();
3823                 }
3824         }
3825 }
3826
3827 /** @return Number of frames that there is disk space available to write,
3828  *  if known.
3829  */
3830 boost::optional<framecnt_t>
3831 Session::available_capture_duration ()
3832 {
3833         Glib::Threads::Mutex::Lock lm (space_lock);
3834
3835         if (_total_free_4k_blocks_uncertain) {
3836                 return boost::optional<framecnt_t> ();
3837         }
3838         
3839         float sample_bytes_on_disk = 4.0; // keep gcc happy
3840
3841         switch (config.get_native_file_data_format()) {
3842         case FormatFloat:
3843                 sample_bytes_on_disk = 4.0;
3844                 break;
3845
3846         case FormatInt24:
3847                 sample_bytes_on_disk = 3.0;
3848                 break;
3849
3850         case FormatInt16:
3851                 sample_bytes_on_disk = 2.0;
3852                 break;
3853
3854         default:
3855                 /* impossible, but keep some gcc versions happy */
3856                 fatal << string_compose (_("programming error: %1"),
3857                                          X_("illegal native file data format"))
3858                       << endmsg;
3859                 /*NOTREACHED*/
3860         }
3861
3862         double scale = 4096.0 / sample_bytes_on_disk;
3863
3864         if (_total_free_4k_blocks * scale > (double) max_framecnt) {
3865                 return max_framecnt;
3866         }
3867
3868         return (framecnt_t) floor (_total_free_4k_blocks * scale);
3869 }
3870
3871 void
3872 Session::add_bundle (boost::shared_ptr<Bundle> bundle)
3873 {
3874         {
3875                 RCUWriter<BundleList> writer (_bundles);
3876                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3877                 b->push_back (bundle);
3878         }
3879
3880         BundleAdded (bundle); /* EMIT SIGNAL */
3881
3882         set_dirty();
3883 }
3884
3885 void
3886 Session::remove_bundle (boost::shared_ptr<Bundle> bundle)
3887 {
3888         bool removed = false;
3889
3890         {
3891                 RCUWriter<BundleList> writer (_bundles);
3892                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3893                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3894
3895                 if (i != b->end()) {
3896                         b->erase (i);
3897                         removed = true;
3898                 }
3899         }
3900
3901         if (removed) {
3902                  BundleRemoved (bundle); /* EMIT SIGNAL */
3903         }
3904
3905         set_dirty();
3906 }
3907
3908 boost::shared_ptr<Bundle>
3909 Session::bundle_by_name (string name) const
3910 {
3911         boost::shared_ptr<BundleList> b = _bundles.reader ();
3912
3913         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3914                 if ((*i)->name() == name) {
3915                         return* i;
3916                 }
3917         }
3918
3919         return boost::shared_ptr<Bundle> ();
3920 }
3921
3922 void
3923 Session::tempo_map_changed (const PropertyChange&)
3924 {
3925         clear_clicks ();
3926
3927         playlists->update_after_tempo_map_change ();
3928
3929         _locations->apply (*this, &Session::update_locations_after_tempo_map_change);
3930
3931         set_dirty ();
3932 }
3933
3934 void
3935 Session::update_locations_after_tempo_map_change (Locations::LocationList& loc)
3936 {
3937         for (Locations::LocationList::iterator i = loc.begin(); i != loc.end(); ++i) {
3938                 (*i)->recompute_frames_from_bbt ();
3939         }
3940 }
3941
3942 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3943  * the given count with the current block size.
3944  */
3945 void
3946 Session::ensure_buffers (ChanCount howmany)
3947 {
3948         BufferManager::ensure_buffers (howmany, bounce_processing() ? bounce_chunk_size : 0);
3949 }
3950
3951 void
3952 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3953 {
3954         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3955                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3956         }
3957 }
3958
3959 uint32_t
3960 Session::next_insert_id ()
3961 {
3962         /* this doesn't really loop forever. just think about it */
3963
3964         while (true) {
3965                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3966                         if (!insert_bitset[n]) {
3967                                 insert_bitset[n] = true;
3968                                 return n;
3969
3970                         }
3971                 }
3972
3973                 /* none available, so resize and try again */
3974
3975                 insert_bitset.resize (insert_bitset.size() + 16, false);
3976         }
3977 }
3978
3979 uint32_t
3980 Session::next_send_id ()
3981 {
3982         /* this doesn't really loop forever. just think about it */
3983
3984         while (true) {
3985                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3986                         if (!send_bitset[n]) {
3987                                 send_bitset[n] = true;
3988                                 return n;
3989
3990                         }
3991                 }
3992
3993                 /* none available, so resize and try again */
3994
3995                 send_bitset.resize (send_bitset.size() + 16, false);
3996         }
3997 }
3998
3999 uint32_t
4000 Session::next_aux_send_id ()
4001 {
4002         /* this doesn't really loop forever. just think about it */
4003
4004         while (true) {
4005                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < aux_send_bitset.size(); ++n) {
4006                         if (!aux_send_bitset[n]) {
4007                                 aux_send_bitset[n] = true;
4008                                 return n;
4009
4010                         }
4011                 }
4012
4013                 /* none available, so resize and try again */
4014
4015                 aux_send_bitset.resize (aux_send_bitset.size() + 16, false);
4016         }
4017 }
4018
4019 uint32_t
4020 Session::next_return_id ()
4021 {
4022         /* this doesn't really loop forever. just think about it */
4023
4024         while (true) {
4025                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
4026                         if (!return_bitset[n]) {
4027                                 return_bitset[n] = true;
4028                                 return n;
4029
4030                         }
4031                 }
4032
4033                 /* none available, so resize and try again */
4034
4035                 return_bitset.resize (return_bitset.size() + 16, false);
4036         }
4037 }
4038
4039 void
4040 Session::mark_send_id (uint32_t id)
4041 {
4042         if (id >= send_bitset.size()) {
4043                 send_bitset.resize (id+16, false);
4044         }
4045         if (send_bitset[id]) {
4046                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4047         }
4048         send_bitset[id] = true;
4049 }
4050
4051 void
4052 Session::mark_aux_send_id (uint32_t id)
4053 {
4054         if (id >= aux_send_bitset.size()) {
4055                 aux_send_bitset.resize (id+16, false);
4056         }
4057         if (aux_send_bitset[id]) {
4058                 warning << string_compose (_("aux send ID %1 appears to be in use already"), id) << endmsg;
4059         }
4060         aux_send_bitset[id] = true;
4061 }
4062
4063 void
4064 Session::mark_return_id (uint32_t id)
4065 {
4066         if (id >= return_bitset.size()) {
4067                 return_bitset.resize (id+16, false);
4068         }
4069         if (return_bitset[id]) {
4070                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4071         }
4072         return_bitset[id] = true;
4073 }
4074
4075 void
4076 Session::mark_insert_id (uint32_t id)
4077 {
4078         if (id >= insert_bitset.size()) {
4079                 insert_bitset.resize (id+16, false);
4080         }
4081         if (insert_bitset[id]) {
4082                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4083         }
4084         insert_bitset[id] = true;
4085 }
4086
4087 void
4088 Session::unmark_send_id (uint32_t id)
4089 {
4090         if (id < send_bitset.size()) {
4091                 send_bitset[id] = false;
4092         }
4093 }
4094
4095 void
4096 Session::unmark_aux_send_id (uint32_t id)
4097 {
4098         if (id < aux_send_bitset.size()) {
4099                 aux_send_bitset[id] = false;
4100         }
4101 }
4102
4103 void
4104 Session::unmark_return_id (uint32_t id)
4105 {
4106         if (id < return_bitset.size()) {
4107                 return_bitset[id] = false;
4108         }
4109 }
4110
4111 void
4112 Session::unmark_insert_id (uint32_t id)
4113 {
4114         if (id < insert_bitset.size()) {
4115                 insert_bitset[id] = false;
4116         }
4117 }
4118
4119 void
4120 Session::reset_native_file_format ()
4121 {
4122         boost::shared_ptr<RouteList> rl = routes.reader ();
4123         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4124                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4125                 if (tr) {
4126                         /* don't save state as we do this, there's no point
4127                          */
4128
4129                         _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
4130                         tr->reset_write_sources (false);
4131                         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
4132                 }
4133         }
4134 }
4135
4136 bool
4137 Session::route_name_unique (string n) const
4138 {
4139         boost::shared_ptr<RouteList> r = routes.reader ();
4140
4141         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4142                 if ((*i)->name() == n) {
4143                         return false;
4144                 }
4145         }
4146
4147         return true;
4148 }
4149
4150 bool
4151 Session::route_name_internal (string n) const
4152 {
4153         if (auditioner && auditioner->name() == n) {
4154                 return true;
4155         }
4156
4157         if (_click_io && _click_io->name() == n) {
4158                 return true;
4159         }
4160
4161         return false;
4162 }
4163
4164 int
4165 Session::freeze_all (InterThreadInfo& itt)
4166 {
4167         boost::shared_ptr<RouteList> r = routes.reader ();
4168
4169         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4170
4171                 boost::shared_ptr<Track> t;
4172
4173                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4174                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
4175                            of every track.
4176                         */
4177                         t->freeze_me (itt);
4178                 }
4179         }
4180
4181         return 0;
4182 }
4183
4184 boost::shared_ptr<Region>
4185 Session::write_one_track (AudioTrack& track, framepos_t start, framepos_t end,
4186                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4187                           InterThreadInfo& itt, 
4188                           boost::shared_ptr<Processor> endpoint, bool include_endpoint,
4189                           bool for_export, bool for_freeze)
4190 {
4191         boost::shared_ptr<Region> result;
4192         boost::shared_ptr<Playlist> playlist;
4193         boost::shared_ptr<AudioFileSource> fsource;
4194         ChanCount diskstream_channels (track.n_channels());
4195         framepos_t position;
4196         framecnt_t this_chunk;
4197         framepos_t to_do;
4198         framepos_t latency_skip;
4199         BufferSet buffers;
4200         framepos_t len = end - start;
4201         bool need_block_size_reset = false;
4202         ChanCount const max_proc = track.max_processor_streams ();
4203         string legal_playlist_name;
4204         string possible_path;
4205
4206         if (end <= start) {
4207                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4208                                          end, start) << endmsg;
4209                 return result;
4210         }
4211
4212         diskstream_channels = track.bounce_get_output_streams (diskstream_channels, endpoint,
4213                         include_endpoint, for_export, for_freeze);
4214
4215         if (diskstream_channels.n_audio() < 1) {
4216                 error << _("Cannot write a range with no audio.") << endmsg;
4217                 return result;
4218         }
4219
4220         // block all process callback handling
4221
4222         block_processing ();
4223
4224         {
4225                 // synchronize with AudioEngine::process_callback()
4226                 // make sure processing is not currently running
4227                 // and processing_blocked() is honored before
4228                 // acquiring thread buffers
4229                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4230         }
4231
4232         _bounce_processing_active = true;
4233
4234         /* call tree *MUST* hold route_lock */
4235
4236         if ((playlist = track.playlist()) == 0) {
4237                 goto out;
4238         }
4239
4240         legal_playlist_name = legalize_for_path (playlist->name());
4241
4242         for (uint32_t chan_n = 0; chan_n < diskstream_channels.n_audio(); ++chan_n) {
4243
4244                 string base_name = string_compose ("%1-%2-bounce", playlist->name(), chan_n);
4245                 string path = new_audio_source_path (legal_playlist_name, diskstream_channels.n_audio(), chan_n, false, true);
4246                 
4247                 if (path.empty()) {
4248                         goto out;
4249                 }
4250
4251                 try {
4252                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4253                                 SourceFactory::createWritable (DataType::AUDIO, *this, path, false, frame_rate()));
4254                 }
4255
4256                 catch (failed_constructor& err) {
4257                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), path, track.name()) << endmsg;
4258                         goto out;
4259                 }
4260
4261                 srcs.push_back (fsource);
4262         }
4263
4264         /* tell redirects that care that we are about to use a much larger
4265          * blocksize. this will flush all plugins too, so that they are ready
4266          * to be used for this process.
4267          */
4268
4269         need_block_size_reset = true;
4270         track.set_block_size (bounce_chunk_size);
4271         _engine.main_thread()->get_buffers ();
4272
4273         position = start;
4274         to_do = len;
4275         latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4276
4277         /* create a set of reasonably-sized buffers */
4278         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4279                 buffers.ensure_buffers(*t, max_proc.get(*t), bounce_chunk_size);
4280         }
4281         buffers.set_count (max_proc);
4282
4283         for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4284                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4285                 if (afs)
4286                         afs->prepare_for_peakfile_writes ();
4287         }
4288
4289         while (to_do && !itt.cancel) {
4290
4291                 this_chunk = min (to_do, bounce_chunk_size);
4292
4293                 if (track.export_stuff (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze)) {
4294                         goto out;
4295                 }
4296
4297                 start += this_chunk;
4298                 to_do -= this_chunk;
4299                 itt.progress = (float) (1.0 - ((double) to_do / len));
4300
4301                 if (latency_skip >= bounce_chunk_size) {
4302                         latency_skip -= bounce_chunk_size;
4303                         continue;
4304                 }
4305
4306                 const framecnt_t current_chunk = this_chunk - latency_skip;
4307
4308                 uint32_t n = 0;
4309                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4310                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4311
4312                         if (afs) {
4313                                 if (afs->write (buffers.get_audio(n).data(latency_skip), current_chunk) != current_chunk) {
4314                                         goto out;
4315                                 }
4316                         }
4317                 }
4318                 latency_skip = 0;
4319         }
4320
4321         /* post-roll, pick up delayed processor output */
4322         latency_skip = track.bounce_get_latency (endpoint, include_endpoint, for_export, for_freeze);
4323
4324         while (latency_skip && !itt.cancel) {
4325                 this_chunk = min (latency_skip, bounce_chunk_size);
4326                 latency_skip -= this_chunk;
4327
4328                 buffers.silence (this_chunk, 0);
4329                 track.bounce_process (buffers, start, this_chunk, endpoint, include_endpoint, for_export, for_freeze);
4330
4331                 uint32_t n = 0;
4332                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4333                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4334
4335                         if (afs) {
4336                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4337                                         goto out;
4338                                 }
4339                         }
4340                 }
4341         }
4342
4343         if (!itt.cancel) {
4344
4345                 time_t now;
4346                 struct tm* xnow;
4347                 time (&now);
4348                 xnow = localtime (&now);
4349
4350                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4351                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4352
4353                         if (afs) {
4354                                 afs->update_header (position, *xnow, now);
4355                                 afs->flush_header ();
4356                         }
4357                 }
4358
4359                 /* construct a region to represent the bounced material */
4360
4361                 PropertyList plist;
4362
4363                 plist.add (Properties::start, 0);
4364                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
4365                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
4366
4367                 result = RegionFactory::create (srcs, plist);
4368
4369         }
4370
4371   out:
4372         if (!result) {
4373                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4374                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4375
4376                         if (afs) {
4377                                 afs->mark_for_remove ();
4378                         }
4379
4380                         (*src)->drop_references ();
4381                 }
4382
4383         } else {
4384                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4385                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4386
4387                         if (afs)
4388                                 afs->done_with_peakfile_writes ();
4389                 }
4390         }
4391
4392         _bounce_processing_active = false;
4393
4394         if (need_block_size_reset) {
4395                 _engine.main_thread()->drop_buffers ();
4396                 track.set_block_size (get_block_size());
4397         }
4398
4399         unblock_processing ();
4400
4401         return result;
4402 }
4403
4404 gain_t*
4405 Session::gain_automation_buffer() const
4406 {
4407         return ProcessThread::gain_automation_buffer ();
4408 }
4409
4410 gain_t*
4411 Session::send_gain_automation_buffer() const
4412 {
4413         return ProcessThread::send_gain_automation_buffer ();
4414 }
4415
4416 pan_t**
4417 Session::pan_automation_buffer() const
4418 {
4419         return ProcessThread::pan_automation_buffer ();
4420 }
4421
4422 BufferSet&
4423 Session::get_silent_buffers (ChanCount count)
4424 {
4425         return ProcessThread::get_silent_buffers (count);
4426 }
4427
4428 BufferSet&
4429 Session::get_scratch_buffers (ChanCount count, bool silence)
4430 {
4431         return ProcessThread::get_scratch_buffers (count, silence);
4432 }
4433
4434 BufferSet&
4435 Session::get_route_buffers (ChanCount count, bool silence)
4436 {
4437         return ProcessThread::get_route_buffers (count, silence);
4438 }
4439
4440
4441 BufferSet&
4442 Session::get_mix_buffers (ChanCount count)
4443 {
4444         return ProcessThread::get_mix_buffers (count);
4445 }
4446
4447 uint32_t
4448 Session::ntracks () const
4449 {
4450         uint32_t n = 0;
4451         boost::shared_ptr<RouteList> r = routes.reader ();
4452
4453         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4454                 if (boost::dynamic_pointer_cast<Track> (*i)) {
4455                         ++n;
4456                 }
4457         }
4458
4459         return n;
4460 }
4461
4462 uint32_t
4463 Session::nbusses () const
4464 {
4465         uint32_t n = 0;
4466         boost::shared_ptr<RouteList> r = routes.reader ();
4467
4468         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4469                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4470                         ++n;
4471                 }
4472         }
4473
4474         return n;
4475 }
4476
4477 void
4478 Session::add_automation_list(AutomationList *al)
4479 {
4480         automation_lists[al->id()] = al;
4481 }
4482
4483 /** @return true if there is at least one record-enabled track, otherwise false */
4484 bool
4485 Session::have_rec_enabled_track () const
4486 {
4487         return g_atomic_int_get (const_cast<gint*>(&_have_rec_enabled_track)) == 1;
4488 }
4489
4490 /** Update the state of our rec-enabled tracks flag */
4491 void
4492 Session::update_have_rec_enabled_track ()
4493 {
4494         boost::shared_ptr<RouteList> rl = routes.reader ();
4495         RouteList::iterator i = rl->begin();
4496         while (i != rl->end ()) {
4497
4498                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4499                 if (tr && tr->record_enabled ()) {
4500                         break;
4501                 }
4502
4503                 ++i;
4504         }
4505
4506         int const old = g_atomic_int_get (&_have_rec_enabled_track);
4507
4508         g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
4509
4510         if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
4511                 RecordStateChanged (); /* EMIT SIGNAL */
4512         }
4513 }
4514
4515 void
4516 Session::listen_position_changed ()
4517 {
4518         boost::shared_ptr<RouteList> r = routes.reader ();
4519
4520         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4521                 (*i)->listen_position_changed ();
4522         }
4523 }
4524
4525 void
4526 Session::solo_control_mode_changed ()
4527 {
4528         /* cancel all solo or all listen when solo control mode changes */
4529
4530         if (soloing()) {
4531                 set_solo (get_routes(), false);
4532         } else if (listening()) {
4533                 set_listen (get_routes(), false);
4534         }
4535 }
4536
4537 /** Called when a property of one of our route groups changes */
4538 void
4539 Session::route_group_property_changed (RouteGroup* rg)
4540 {
4541         RouteGroupPropertyChanged (rg); /* EMIT SIGNAL */
4542 }
4543
4544 /** Called when a route is added to one of our route groups */
4545 void
4546 Session::route_added_to_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4547 {
4548         RouteAddedToRouteGroup (rg, r);
4549 }
4550
4551 /** Called when a route is removed from one of our route groups */
4552 void
4553 Session::route_removed_from_route_group (RouteGroup* rg, boost::weak_ptr<Route> r)
4554 {
4555         RouteRemovedFromRouteGroup (rg, r);
4556 }
4557
4558 boost::shared_ptr<RouteList>
4559 Session::get_routes_with_regions_at (framepos_t const p) const
4560 {
4561         boost::shared_ptr<RouteList> r = routes.reader ();
4562         boost::shared_ptr<RouteList> rl (new RouteList);
4563
4564         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4565                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4566                 if (!tr) {
4567                         continue;
4568                 }
4569
4570                 boost::shared_ptr<Playlist> pl = tr->playlist ();
4571                 if (!pl) {
4572                         continue;
4573                 }
4574
4575                 if (pl->has_region_at (p)) {
4576                         rl->push_back (*i);
4577                 }
4578         }
4579
4580         return rl;
4581 }
4582
4583 void
4584 Session::goto_end ()
4585 {
4586         if (_session_range_location) {
4587                 request_locate (_session_range_location->end(), false);
4588         } else {
4589                 request_locate (0, false);
4590         }
4591 }
4592
4593 void
4594 Session::goto_start ()
4595 {
4596         if (_session_range_location) {
4597                 request_locate (_session_range_location->start(), false);
4598         } else {
4599                 request_locate (0, false);
4600         }
4601 }
4602
4603 framepos_t
4604 Session::current_start_frame () const
4605 {
4606         return _session_range_location ? _session_range_location->start() : 0;
4607 }
4608
4609 framepos_t
4610 Session::current_end_frame () const
4611 {
4612         return _session_range_location ? _session_range_location->end() : 0;
4613 }
4614
4615 void
4616 Session::add_session_range_location (framepos_t start, framepos_t end)
4617 {
4618         _session_range_location = new Location (*this, start, end, _("session"), Location::IsSessionRange);
4619         _locations->add (_session_range_location);
4620 }
4621
4622 void
4623 Session::step_edit_status_change (bool yn)
4624 {
4625         bool send = false;
4626
4627         bool val = false;
4628         if (yn) {
4629                 send = (_step_editors == 0);
4630                 val = true;
4631
4632                 _step_editors++;
4633         } else {
4634                 send = (_step_editors == 1);
4635                 val = false;
4636
4637                 if (_step_editors > 0) {
4638                         _step_editors--;
4639                 }
4640         }
4641
4642         if (send) {
4643                 StepEditStatusChange (val);
4644         }
4645 }
4646
4647
4648 void
4649 Session::start_time_changed (framepos_t old)
4650 {
4651         /* Update the auto loop range to match the session range
4652            (unless the auto loop range has been changed by the user)
4653         */
4654
4655         Location* s = _locations->session_range_location ();
4656         if (s == 0) {
4657                 return;
4658         }
4659
4660         Location* l = _locations->auto_loop_location ();
4661
4662         if (l && l->start() == old) {
4663                 l->set_start (s->start(), true);
4664         }
4665 }
4666
4667 void
4668 Session::end_time_changed (framepos_t old)
4669 {
4670         /* Update the auto loop range to match the session range
4671            (unless the auto loop range has been changed by the user)
4672         */
4673
4674         Location* s = _locations->session_range_location ();
4675         if (s == 0) {
4676                 return;
4677         }
4678
4679         Location* l = _locations->auto_loop_location ();
4680
4681         if (l && l->end() == old) {
4682                 l->set_end (s->end(), true);
4683         }
4684 }
4685
4686 std::vector<std::string>
4687 Session::source_search_path (DataType type) const
4688 {
4689         Searchpath sp;
4690
4691         if (session_dirs.size() == 1) {
4692                 switch (type) {
4693                 case DataType::AUDIO:
4694                         sp.push_back (_session_dir->sound_path());
4695                         break;
4696                 case DataType::MIDI:
4697                         sp.push_back (_session_dir->midi_path());
4698                         break;
4699                 }
4700         } else {
4701                 for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
4702                         SessionDirectory sdir (i->path);
4703                         switch (type) {
4704                         case DataType::AUDIO:
4705                                 sp.push_back (sdir.sound_path());
4706                                 break;
4707                         case DataType::MIDI:
4708                                 sp.push_back (sdir.midi_path());
4709                                 break;
4710                         }
4711                 }
4712         }
4713
4714         if (type == DataType::AUDIO) {
4715                 const string sound_path_2X = _session_dir->sound_path_2X();
4716                 if (Glib::file_test (sound_path_2X, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_DIR)) {
4717                         if (find (sp.begin(), sp.end(), sound_path_2X) == sp.end()) {
4718                                 sp.push_back (sound_path_2X);
4719                         }
4720                 }
4721         }
4722
4723         // now check the explicit (possibly user-specified) search path
4724
4725         switch (type) {
4726         case DataType::AUDIO:
4727                 sp += Searchpath(config.get_audio_search_path ());
4728                 break;
4729         case DataType::MIDI:
4730                 sp += Searchpath(config.get_midi_search_path ());
4731                 break;
4732         }
4733
4734         return sp;
4735 }
4736
4737 void
4738 Session::ensure_search_path_includes (const string& path, DataType type)
4739 {
4740         Searchpath sp;
4741
4742         if (path == ".") {
4743                 return;
4744         }
4745
4746         switch (type) {
4747         case DataType::AUDIO:
4748                 sp += Searchpath(config.get_audio_search_path ());
4749                 break;
4750         case DataType::MIDI:
4751                 sp += Searchpath (config.get_midi_search_path ());
4752                 break;
4753         }
4754
4755         for (vector<std::string>::iterator i = sp.begin(); i != sp.end(); ++i) {
4756                 /* No need to add this new directory if it has the same inode as
4757                    an existing one; checking inode rather than name prevents duplicated
4758                    directories when we are using symlinks.
4759
4760                    On Windows, I think we could just do if (*i == path) here.
4761                 */
4762                 if (PBD::equivalent_paths (*i, path)) {
4763                         return;
4764                 }
4765         }
4766
4767         sp += path;
4768
4769         switch (type) {
4770         case DataType::AUDIO:
4771                 config.set_audio_search_path (sp.to_string());
4772                 break;
4773         case DataType::MIDI:
4774                 config.set_midi_search_path (sp.to_string());
4775                 break;
4776         }
4777 }
4778
4779 boost::shared_ptr<Speakers>
4780 Session::get_speakers()
4781 {
4782         return _speakers;
4783 }
4784
4785 list<string>
4786 Session::unknown_processors () const
4787 {
4788         list<string> p;
4789
4790         boost::shared_ptr<RouteList> r = routes.reader ();
4791         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4792                 list<string> t = (*i)->unknown_processors ();
4793                 copy (t.begin(), t.end(), back_inserter (p));
4794         }
4795
4796         p.sort ();
4797         p.unique ();
4798
4799         return p;
4800 }
4801
4802 void
4803 Session::update_latency (bool playback)
4804 {
4805         DEBUG_TRACE (DEBUG::Latency, string_compose ("JACK latency callback: %1\n", (playback ? "PLAYBACK" : "CAPTURE")));
4806
4807         if ((_state_of_the_state & (InitialConnecting|Deletion)) || _adding_routes_in_progress) {
4808                 return;
4809         }
4810
4811         boost::shared_ptr<RouteList> r = routes.reader ();
4812         framecnt_t max_latency = 0;
4813
4814         if (playback) {
4815                 /* reverse the list so that we work backwards from the last route to run to the first */
4816                 RouteList* rl = routes.reader().get();
4817                 r.reset (new RouteList (*rl));
4818                 reverse (r->begin(), r->end());
4819         }
4820
4821         /* compute actual latency values for the given direction and store them all in per-port
4822            structures. this will also publish the same values (to JACK) so that computation of latency
4823            for routes can consistently use public latency values.
4824         */
4825
4826         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4827                 max_latency = max (max_latency, (*i)->set_private_port_latencies (playback));
4828         }
4829
4830         /* because we latency compensate playback, our published playback latencies should
4831            be the same for all output ports - all material played back by ardour has
4832            the same latency, whether its caused by plugins or by latency compensation. since
4833            these may differ from the values computed above, reset all playback port latencies
4834            to the same value.
4835         */
4836
4837         DEBUG_TRACE (DEBUG::Latency, string_compose ("Set public port latencies to %1\n", max_latency));
4838
4839         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4840                 (*i)->set_public_port_latencies (max_latency, playback);
4841         }
4842
4843         if (playback) {
4844
4845                 post_playback_latency ();
4846
4847         } else {
4848
4849                 post_capture_latency ();
4850         }
4851
4852         DEBUG_TRACE (DEBUG::Latency, "JACK latency callback: DONE\n");
4853 }
4854
4855 void
4856 Session::post_playback_latency ()
4857 {
4858         set_worst_playback_latency ();
4859
4860         boost::shared_ptr<RouteList> r = routes.reader ();
4861
4862         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4863                 if (!(*i)->is_auditioner() && ((*i)->active())) {
4864                         _worst_track_latency = max (_worst_track_latency, (*i)->update_signal_latency ());
4865                 }
4866         }
4867
4868         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4869                 (*i)->set_latency_compensation (_worst_track_latency);
4870         }
4871 }
4872
4873 void
4874 Session::post_capture_latency ()
4875 {
4876         set_worst_capture_latency ();
4877
4878         /* reflect any changes in capture latencies into capture offsets
4879          */
4880
4881         boost::shared_ptr<RouteList> rl = routes.reader();
4882         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
4883                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4884                 if (tr) {
4885                         tr->set_capture_offset ();
4886                 }
4887         }
4888 }
4889
4890 void
4891 Session::initialize_latencies ()
4892 {
4893         {
4894                 Glib::Threads::Mutex::Lock lm (_engine.process_lock());
4895                 update_latency (false);
4896                 update_latency (true);
4897         }
4898
4899         set_worst_io_latencies ();
4900 }
4901
4902 void
4903 Session::set_worst_io_latencies ()
4904 {
4905         set_worst_playback_latency ();
4906         set_worst_capture_latency ();
4907 }
4908
4909 void
4910 Session::set_worst_playback_latency ()
4911 {
4912         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4913                 return;
4914         }
4915
4916         _worst_output_latency = 0;
4917
4918         if (!_engine.connected()) {
4919                 return;
4920         }
4921
4922         boost::shared_ptr<RouteList> r = routes.reader ();
4923
4924         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4925                 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
4926         }
4927
4928         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst output latency: %1\n", _worst_output_latency));
4929 }
4930
4931 void
4932 Session::set_worst_capture_latency ()
4933 {
4934         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4935                 return;
4936         }
4937
4938         _worst_input_latency = 0;
4939
4940         if (!_engine.connected()) {
4941                 return;
4942         }
4943
4944         boost::shared_ptr<RouteList> r = routes.reader ();
4945
4946         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4947                 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
4948         }
4949
4950         DEBUG_TRACE (DEBUG::Latency, string_compose ("Worst input latency: %1\n", _worst_input_latency));
4951 }
4952
4953 void
4954 Session::update_latency_compensation (bool force_whole_graph)
4955 {
4956         bool some_track_latency_changed = false;
4957
4958         if (_state_of_the_state & (InitialConnecting|Deletion)) {
4959                 return;
4960         }
4961
4962         DEBUG_TRACE(DEBUG::Latency, "---------------------------- update latency compensation\n\n");
4963
4964         _worst_track_latency = 0;
4965
4966         boost::shared_ptr<RouteList> r = routes.reader ();
4967
4968         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4969                 if (!(*i)->is_auditioner() && ((*i)->active())) {
4970                         framecnt_t tl;
4971                         if ((*i)->signal_latency () != (tl = (*i)->update_signal_latency ())) {
4972                                 some_track_latency_changed = true;
4973                         }
4974                         _worst_track_latency = max (tl, _worst_track_latency);
4975                 }
4976         }
4977
4978         DEBUG_TRACE (DEBUG::Latency, string_compose ("worst signal processing latency: %1 (changed ? %2)\n", _worst_track_latency,
4979                                                      (some_track_latency_changed ? "yes" : "no")));
4980
4981         DEBUG_TRACE(DEBUG::Latency, "---------------------------- DONE update latency compensation\n\n");
4982         
4983         if (some_track_latency_changed || force_whole_graph)  {
4984                 _engine.update_latencies ();
4985         }
4986
4987
4988         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4989                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4990                 if (!tr) {
4991                         continue;
4992                 }
4993                 tr->set_capture_offset ();
4994         }
4995 }
4996
4997 char
4998 Session::session_name_is_legal (const string& path)
4999 {
5000         char illegal_chars[] = { '/', '\\', ':', ';', '\0' };
5001
5002         for (int i = 0; illegal_chars[i]; ++i) {
5003                 if (path.find (illegal_chars[i]) != string::npos) {
5004                         return illegal_chars[i];
5005                 }
5006         }
5007
5008         return 0;
5009 }
5010
5011 uint32_t 
5012 Session::next_control_id () const
5013 {
5014         int subtract = 0;
5015
5016         /* the monitor bus remote ID is in a different
5017          * "namespace" than regular routes. its existence doesn't
5018          * affect normal (low) numbered routes.
5019          */
5020
5021         if (_monitor_out) {
5022                 subtract++;
5023         }
5024
5025         return nroutes() - subtract;
5026 }
5027
5028 void
5029 Session::notify_remote_id_change ()
5030 {
5031         if (deletion_in_progress()) {
5032                 return;
5033         }
5034
5035         switch (Config->get_remote_model()) {
5036         case MixerOrdered:
5037                 Route::RemoteControlIDChange (); /* EMIT SIGNAL */
5038                 break;
5039         default:
5040                 break;
5041         }
5042 }
5043
5044 void
5045 Session::sync_order_keys ()
5046 {
5047         if (deletion_in_progress()) {
5048                 return;
5049         }
5050
5051         /* tell everyone that something has happened to the sort keys
5052            and let them sync up with the change(s)
5053            this will give objects that manage the sort order keys the
5054            opportunity to keep them in sync if they wish to.
5055         */
5056
5057         DEBUG_TRACE (DEBUG::OrderKeys, "Sync Order Keys.\n");
5058
5059         reassign_track_numbers();
5060
5061         Route::SyncOrderKeys (); /* EMIT SIGNAL */
5062
5063         DEBUG_TRACE (DEBUG::OrderKeys, "\tsync done\n");
5064 }
5065
5066 bool
5067 Session::operation_in_progress (GQuark op) const
5068 {
5069         return (find (_current_trans_quarks.begin(), _current_trans_quarks.end(), op) != _current_trans_quarks.end());
5070 }
5071
5072 boost::shared_ptr<Port>
5073 Session::ltc_input_port () const
5074 {
5075         return _ltc_input->nth (0);
5076 }
5077
5078 boost::shared_ptr<Port>
5079 Session::ltc_output_port () const
5080 {
5081         return _ltc_output->nth (0);
5082 }
5083
5084 void
5085 Session::reconnect_ltc_input ()
5086 {
5087         if (_ltc_input) {
5088
5089                 string src = Config->get_ltc_source_port();
5090
5091                 _ltc_input->disconnect (this);
5092
5093                 if (src != _("None") && !src.empty())  {
5094                         _ltc_input->nth (0)->connect (src);
5095                 }
5096         }
5097 }
5098
5099 void
5100 Session::reconnect_ltc_output ()
5101 {
5102         if (_ltc_output) {
5103
5104 #if 0
5105                 string src = Config->get_ltc_sink_port();
5106
5107                 _ltc_output->disconnect (this);
5108
5109                 if (src != _("None") && !src.empty())  {
5110                         _ltc_output->nth (0)->connect (src);
5111                 }
5112 #endif
5113         }
5114 }