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