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