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