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