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