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