lots of odds and ends to do with solo isolate and its GUI
[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 #define __STDC_LIMIT_MACROS
21 #include <stdint.h>
22
23 #include <algorithm>
24 #include <string>
25 #include <vector>
26 #include <sstream>
27 #include <fstream>
28 #include <cstdio> /* sprintf(3) ... grrr */
29 #include <cmath>
30 #include <cerrno>
31 #include <unistd.h>
32 #include <limits.h>
33
34 #include <glibmm/thread.h>
35 #include <glibmm/miscutils.h>
36 #include <glibmm/fileutils.h>
37
38 #include "pbd/error.h"
39 #include "pbd/boost_debug.h"
40 #include "pbd/pathscanner.h"
41 #include "pbd/stl_delete.h"
42 #include "pbd/basename.h"
43 #include "pbd/stacktrace.h"
44 #include "pbd/file_utils.h"
45 #include "pbd/convert.h"
46
47 #include "ardour/amp.h"
48 #include "ardour/analyser.h"
49 #include "ardour/audio_buffer.h"
50 #include "ardour/audio_diskstream.h"
51 #include "ardour/audio_port.h"
52 #include "ardour/audio_track.h"
53 #include "ardour/audioengine.h"
54 #include "ardour/audiofilesource.h"
55 #include "ardour/audioplaylist.h"
56 #include "ardour/audioregion.h"
57 #include "ardour/auditioner.h"
58 #include "ardour/buffer_manager.h"
59 #include "ardour/buffer_set.h"
60 #include "ardour/bundle.h"
61 #include "ardour/butler.h"
62 #include "ardour/click.h"
63 #include "ardour/configuration.h"
64 #include "ardour/crossfade.h"
65 #include "ardour/cycle_timer.h"
66 #include "ardour/data_type.h"
67 #include "ardour/debug.h"
68 #include "ardour/filename_extensions.h"
69 #include "ardour/internal_send.h"
70 #include "ardour/io_processor.h"
71 #include "ardour/midi_diskstream.h"
72 #include "ardour/midi_playlist.h"
73 #include "ardour/midi_region.h"
74 #include "ardour/midi_track.h"
75 #include "ardour/midi_ui.h"
76 #include "ardour/named_selection.h"
77 #include "ardour/process_thread.h"
78 #include "ardour/playlist.h"
79 #include "ardour/plugin_insert.h"
80 #include "ardour/port_insert.h"
81 #include "ardour/processor.h"
82 #include "ardour/rc_configuration.h"
83 #include "ardour/recent_sessions.h"
84 #include "ardour/region_factory.h"
85 #include "ardour/return.h"
86 #include "ardour/route_group.h"
87 #include "ardour/send.h"
88 #include "ardour/session.h"
89 #include "ardour/session_directory.h"
90 #include "ardour/session_directory.h"
91 #include "ardour/session_metadata.h"
92 #include "ardour/session_playlists.h"
93 #include "ardour/slave.h"
94 #include "ardour/smf_source.h"
95 #include "ardour/source_factory.h"
96 #include "ardour/tape_file_matcher.h"
97 #include "ardour/tempo.h"
98 #include "ardour/utils.h"
99
100 #include "midi++/jack.h"
101
102 #include "i18n.h"
103
104 using namespace std;
105 using namespace ARDOUR;
106 using namespace PBD;
107 using boost::shared_ptr;
108 using boost::weak_ptr;
109
110 bool Session::_disable_all_loaded_plugins = false;
111
112 PBD::Signal1<void,std::string> Session::Dialog;
113 PBD::Signal0<int> Session::AskAboutPendingState;
114 PBD::Signal2<int,nframes_t,nframes_t> Session::AskAboutSampleRateMismatch;
115 PBD::Signal0<void> Session::SendFeedback;
116
117 PBD::Signal0<void> Session::TimecodeOffsetChanged;
118 PBD::Signal0<void> Session::StartTimeChanged;
119 PBD::Signal0<void> Session::EndTimeChanged;
120 PBD::Signal0<void> Session::AutoBindingOn;
121 PBD::Signal0<void> Session::AutoBindingOff;
122 PBD::Signal2<void,std::string, std::string> Session::Exported;
123 PBD::Signal1<int,boost::shared_ptr<Playlist> > Session::AskAboutPlaylistDeletion;
124
125 static void clean_up_session_event (SessionEvent* ev) { delete ev; }
126 const SessionEvent::RTeventCallback Session::rt_cleanup (clean_up_session_event);
127
128 Session::Session (AudioEngine &eng,
129                   const string& fullpath,
130                   const string& snapshot_name,
131                   BusProfile* bus_profile,
132                   string mix_template)
133
134         : _engine (eng),
135           _target_transport_speed (0.0),
136           _requested_return_frame (-1),
137           mmc (0),
138           _mmc_port (default_mmc_port),
139           _mtc_port (default_mtc_port),
140           _midi_port (default_midi_port),
141           _midi_clock_port (default_midi_clock_port),
142           _session_dir (new SessionDirectory(fullpath)),
143           state_tree (0),
144           _butler (new Butler (*this)),
145           _post_transport_work (0),
146           _send_timecode_update (false),
147           routes (new RouteList),
148           _total_free_4k_blocks (0),
149           _bundles (new BundleList),
150           _bundle_xml_node (0),
151           _click_io ((IO*) 0),
152           click_data (0),
153           click_emphasis_data (0),
154           main_outs (0),
155           _metadata (new SessionMetadata()),
156           _have_rec_enabled_track (false)
157
158 {
159         playlists.reset (new SessionPlaylists);
160         
161         interpolation.add_channel_to (0, 0);
162
163         if (!eng.connected()) {
164                 throw failed_constructor();
165         }
166
167         n_physical_outputs = _engine.n_physical_outputs(DataType::AUDIO);
168         n_physical_inputs =  _engine.n_physical_inputs(DataType::AUDIO);
169
170         first_stage_init (fullpath, snapshot_name);
171
172         _is_new = !Glib::file_test (_path, Glib::FileTest (G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR));
173
174         if (_is_new) {
175                 if (create (mix_template, compute_initial_length(), bus_profile)) {
176                         destroy ();
177                         throw failed_constructor ();
178                 }
179         }
180
181         if (second_stage_init ()) {
182                 destroy ();
183                 throw failed_constructor ();
184         }
185
186         store_recent_sessions(_name, _path);
187
188         bool was_dirty = dirty();
189
190         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
191
192         Config->ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, false));
193         config.ParameterChanged.connect_same_thread (*this, boost::bind (&Session::config_changed, this, _1, true));
194
195         if (was_dirty) {
196                 DirtyChanged (); /* EMIT SIGNAL */
197         }
198
199         _is_new = false;
200 }
201
202 Session::~Session ()
203 {
204         destroy ();
205 }
206
207 void
208 Session::destroy ()
209 {
210         vector<void*> debug_pointers;
211
212         /* if we got to here, leaving pending capture state around
213            is a mistake.
214         */
215
216         remove_pending_capture_state ();
217
218         _state_of_the_state = StateOfTheState (CannotSave|Deletion);
219
220         _engine.remove_session ();
221
222         /* clear history so that no references to objects are held any more */
223
224         _history.clear ();
225
226         /* clear state tree so that no references to objects are held any more */
227
228         delete state_tree;
229
230         /* reset dynamic state version back to default */
231
232         Stateful::loading_state_version = 0;
233
234         _butler->drop_references ();
235         delete _butler;
236         delete midi_control_ui;
237
238         if (click_data != default_click) {
239                 delete [] click_data;
240         }
241
242         if (click_emphasis_data != default_click_emphasis) {
243                 delete [] click_emphasis_data;
244         }
245
246         clear_clicks ();
247
248         /* clear out any pending dead wood from RCU managed objects */
249
250         routes.flush ();
251         _bundles.flush ();
252         
253         AudioDiskstream::free_working_buffers();
254
255         /* tell everyone who is still standing that we're about to die */
256         drop_references ();
257
258         /* tell everyone to drop references and delete objects as we go */
259
260         DEBUG_TRACE (DEBUG::Destruction, "delete named selections\n");
261         named_selections.clear ();
262
263         DEBUG_TRACE (DEBUG::Destruction, "delete regions\n");
264         RegionFactory::delete_all_regions ();
265
266         DEBUG_TRACE (DEBUG::Destruction, "delete routes\n");
267         
268         /* reset these three references to special routes before we do the usual route delete thing */
269
270         auditioner.reset ();
271         _master_out.reset ();
272         _monitor_out.reset ();
273
274         {
275                 RCUWriter<RouteList> writer (routes);
276                 boost::shared_ptr<RouteList> r = writer.get_copy ();
277
278                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
279                         DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for route %1 ; pre-ref = %2\n", (*i)->name(), (*i).use_count()));
280                         (*i)->drop_references ();
281                 }
282
283                 r->clear ();
284                 /* writer goes out of scope and updates master */
285         }
286         routes.flush ();
287
288         boost::shared_ptr<RouteList> r = routes.reader ();
289
290         DEBUG_TRACE (DEBUG::Destruction, "delete sources\n");
291         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
292                 DEBUG_TRACE(DEBUG::Destruction, string_compose ("Dropping for source %1 ; pre-ref = %2\n", i->second->path(), i->second.use_count()));
293                 i->second->drop_references ();
294         }
295
296         sources.clear ();
297
298         DEBUG_TRACE (DEBUG::Destruction, "delete route groups\n");
299         for (list<RouteGroup *>::iterator i = _route_groups.begin(); i != _route_groups.end(); ++i) {
300                 
301                 delete *i;
302         }
303
304         Crossfade::set_buffer_size (0);
305
306         delete mmc;
307
308         /* not strictly necessary, but doing it here allows the shared_ptr debugging to work */
309         playlists.reset ();
310
311         boost_debug_list_ptrs ();
312
313         DEBUG_TRACE (DEBUG::Destruction, "Session::destroy() done\n");
314 }
315
316 void
317 Session::set_worst_io_latencies ()
318 {
319         _worst_output_latency = 0;
320         _worst_input_latency = 0;
321
322         if (!_engine.connected()) {
323                 return;
324         }
325
326         boost::shared_ptr<RouteList> r = routes.reader ();
327
328         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
329                 _worst_output_latency = max (_worst_output_latency, (*i)->output()->latency());
330                 _worst_input_latency = max (_worst_input_latency, (*i)->input()->latency());
331         }
332 }
333
334 void
335 Session::when_engine_running ()
336 {
337         string first_physical_output;
338
339         BootMessage (_("Set block size and sample rate"));
340
341         set_block_size (_engine.frames_per_cycle());
342         set_frame_rate (_engine.frame_rate());
343
344         BootMessage (_("Using configuration"));
345
346         boost::function<void (std::string)> ff (boost::bind (&Session::config_changed, this, _1, false));
347         boost::function<void (std::string)> ft (boost::bind (&Session::config_changed, this, _1, true));
348
349         Config->map_parameters (ff);
350         config.map_parameters (ft);
351
352         /* every time we reconnect, recompute worst case output latencies */
353
354         _engine.Running.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies, this));
355
356         if (synced_to_jack()) {
357                 _engine.transport_stop ();
358         }
359
360         if (config.get_jack_time_master()) {
361                 _engine.transport_locate (_transport_frame);
362         }
363
364         _clicking = false;
365
366         try {
367                 XMLNode* child = 0;
368
369                 _click_io.reset (new ClickIO (*this, "click"));
370
371                 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
372
373                         /* existing state for Click */
374                         int c;
375
376                         if (Stateful::loading_state_version < 3000) {
377                                 c = _click_io->set_state_2X (*child->children().front(), Stateful::loading_state_version, false);
378                         } else {
379                                 c = _click_io->set_state (*child->children().front(), Stateful::loading_state_version);
380                         }
381                                         
382
383                         if (c == 0) {
384                                 _clicking = Config->get_clicking ();
385                                 
386                         } else {
387                                 
388                                 error << _("could not setup Click I/O") << endmsg;
389                                 _clicking = false;
390                         }
391
392
393                 } else {
394
395                         /* default state for Click: dual-mono to first 2 physical outputs */
396
397                        for (int physport = 0; physport < 2; ++physport) {
398                                string physical_output = _engine.get_nth_physical_output (DataType::AUDIO, physport);
399
400                                if (physical_output.length()) {
401                                        if (_click_io->add_port (physical_output, this)) {
402                                                // relax, even though its an error
403                                        }
404                                }
405                        }
406
407                        if (_click_io->n_ports () > ChanCount::ZERO) {
408                                _clicking = Config->get_clicking ();
409                        }
410                 }
411         }
412
413         catch (failed_constructor& err) {
414                 error << _("cannot setup Click I/O") << endmsg;
415         }
416
417         BootMessage (_("Compute I/O Latencies"));
418
419         set_worst_io_latencies ();
420
421         if (_clicking) {
422                 // XXX HOW TO ALERT UI TO THIS ? DO WE NEED TO?
423         }
424
425         BootMessage (_("Set up standard connections"));
426
427         /* Create a set of Bundle objects that map
428            to the physical I/O currently available.  We create both
429            mono and stereo bundles, so that the common cases of mono
430            and stereo tracks get bundles to put in their mixer strip
431            in / out menus.  There may be a nicer way of achieving that;
432            it doesn't really scale that well to higher channel counts
433         */
434
435         /* mono output bundles */
436
437         for (uint32_t np = 0; np < n_physical_outputs; ++np) {
438                 char buf[32];
439                 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
440
441                 shared_ptr<Bundle> c (new Bundle (buf, true));
442                 c->add_channel (_("mono"));
443                 c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
444
445                 add_bundle (c);
446         }
447
448         /* stereo output bundles */
449
450         for (uint32_t np = 0; np < n_physical_outputs; np += 2) {
451                 if (np + 1 < n_physical_outputs) {
452                         char buf[32];
453                         snprintf (buf, sizeof(buf), _("out %" PRIu32 "+%" PRIu32), np + 1, np + 2);
454                         shared_ptr<Bundle> c (new Bundle (buf, true));
455                         c->add_channel (_("L"));
456                         c->set_port (0, _engine.get_nth_physical_output (DataType::AUDIO, np));
457                         c->add_channel (_("R"));
458                         c->set_port (1, _engine.get_nth_physical_output (DataType::AUDIO, np + 1));
459
460                         add_bundle (c);
461                 }
462         }
463
464         /* mono input bundles */
465
466         for (uint32_t np = 0; np < n_physical_inputs; ++np) {
467                 char buf[32];
468                 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
469
470                 shared_ptr<Bundle> c (new Bundle (buf, false));
471                 c->add_channel (_("mono"));
472                 c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
473
474                 add_bundle (c);
475         }
476
477         /* stereo input bundles */
478
479         for (uint32_t np = 0; np < n_physical_inputs; np += 2) {
480                 if (np + 1 < n_physical_inputs) {
481                         char buf[32];
482                         snprintf (buf, sizeof(buf), _("in %" PRIu32 "+%" PRIu32), np + 1, np + 2);
483
484                         shared_ptr<Bundle> c (new Bundle (buf, false));
485                         c->add_channel (_("L"));
486                         c->set_port (0, _engine.get_nth_physical_input (DataType::AUDIO, np));
487                         c->add_channel (_("R"));
488                         c->set_port (1, _engine.get_nth_physical_input (DataType::AUDIO, np + 1));
489
490                         add_bundle (c);
491                 }
492         }
493
494         BootMessage (_("Setup signal flow and plugins"));
495
496         hookup_io ();
497
498         if (_is_new && !no_auto_connect()) {
499
500                 /* don't connect the master bus outputs if there is a monitor bus */
501
502                 if (_master_out && Config->get_auto_connect_standard_busses() && !_monitor_out) {
503
504                         /* if requested auto-connect the outputs to the first N physical ports.
505                          */
506
507                         uint32_t limit = _master_out->n_outputs().n_total();
508
509                         for (uint32_t n = 0; n < limit; ++n) {
510                                 Port* p = _master_out->output()->nth (n);
511                                 string connect_to = _engine.get_nth_physical_output (DataType (p->type()), n);
512
513                                 if (!connect_to.empty() && p->connected_to (connect_to) == false) {
514                                         if (_master_out->output()->connect (p, connect_to, this)) {
515                                                 error << string_compose (_("cannot connect master output %1 to %2"), n, connect_to)
516                                                       << endmsg;
517                                                 break;
518                                         }
519                                 }
520                         }
521                 }
522
523                 if (_monitor_out) {
524
525                         /* AUDIO ONLY as of june 29th 2009, because listen semantics for anything else
526                            are undefined, at best.
527                          */
528
529                         /* control out listens to master bus (but ignores it
530                            under some conditions)
531                         */
532
533                         uint32_t limit = _monitor_out->n_inputs().n_audio();
534
535                         if (_master_out) {
536                                 for (uint32_t n = 0; n < limit; ++n) {
537                                         AudioPort* p = _monitor_out->input()->ports().nth_audio_port (n);
538                                         AudioPort* o = _master_out->output()->ports().nth_audio_port (n);
539
540                                         if (o) {
541                                                 string connect_to = o->name();
542                                                 if (_monitor_out->input()->connect (p, connect_to, this)) {
543                                                         error << string_compose (_("cannot connect control input %1 to %2"), n, connect_to)
544                                                               << endmsg;
545                                                         break;
546                                                 }
547                                         }
548                                 }
549                         }
550
551                         /* if control out is not connected, connect control out to physical outs
552                         */
553
554                         if (!_monitor_out->output()->connected ()) {
555
556                                 if (!Config->get_monitor_bus_preferred_bundle().empty()) {
557
558                                         boost::shared_ptr<Bundle> b = bundle_by_name (Config->get_monitor_bus_preferred_bundle());
559
560                                         if (b) {
561                                                 _monitor_out->output()->connect_ports_to_bundle (b, this);
562                                         } else {
563                                                 warning << string_compose (_("The preferred I/O for the monitor bus (%1) cannot be found"),
564                                                                            Config->get_monitor_bus_preferred_bundle())
565                                                         << endmsg;
566                                         }
567
568                                 } else {
569                                         
570                                         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
571                                                 uint32_t mod = _engine.n_physical_outputs (*t);
572                                                 uint32_t limit = _monitor_out->n_outputs().get(*t);
573
574                                                 for (uint32_t n = 0; n < limit; ++n) {
575
576                                                         Port* p = _monitor_out->output()->ports().port(*t, n);
577                                                         string connect_to = _engine.get_nth_physical_output (*t, (n % mod));
578
579                                                         if (!connect_to.empty()) {
580                                                                 if (_monitor_out->output()->connect (p, connect_to, this)) {
581                                                                         error << string_compose (
582                                                                                         _("cannot connect control output %1 to %2"),
583                                                                                         n, connect_to)
584                                                                                 << endmsg;
585                                                                         break;
586                                                                 }
587                                                         }
588                                                 }
589                                         }
590                                 }
591                         }
592                 }
593         }
594
595         /* catch up on send+insert cnts */
596
597         _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
598
599         /* hook us up to the engine */
600
601         BootMessage (_("Connect to engine"));
602
603         _engine.set_session (this);
604 }
605
606 void
607 Session::hookup_io ()
608 {
609         /* stop graph reordering notifications from
610            causing resorts, etc.
611         */
612
613         _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
614
615
616         if (!auditioner) {
617
618                 /* we delay creating the auditioner till now because
619                    it makes its own connections to ports.
620                 */
621
622                 try {
623                         Auditioner* a = new Auditioner (*this);
624                         if (a->init()) {
625                                 delete a;
626                                 throw failed_constructor();
627                         }
628                         a->use_new_diskstream ();
629                         auditioner.reset (a);
630                 }
631
632                 catch (failed_constructor& err) {
633                         warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
634                 }
635         }
636
637         /* load bundles, which we may have postponed earlier on */
638         if (_bundle_xml_node) {
639                 load_bundles (*_bundle_xml_node);
640                 delete _bundle_xml_node;
641         }
642
643         /* Tell all IO objects to connect themselves together */
644
645         IO::enable_connecting ();
646         MIDI::JACK_MidiPort::MakeConnections ();
647
648         /* Now reset all panners */
649
650         Delivery::reset_panners ();
651
652         /* Connect tracks to monitor/listen bus if there is one.
653            Note that in an existing session, the internal sends will
654            already exist, but we want the routes to notice that
655            they connect to the control out specifically.
656          */
657
658         if (_monitor_out) {
659                 boost::shared_ptr<RouteList> r = routes.reader ();
660                 for (RouteList::iterator x = r->begin(); x != r->end(); ++x) {
661                         
662                         if ((*x)->is_monitor()) {
663                                 
664                                 /* relax */
665                                 
666                         } else if ((*x)->is_master()) {
667                                 
668                                 /* relax */
669                                 
670                         } else {
671                                 
672                                 (*x)->listen_via (_monitor_out,
673                                                   (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
674                                                   false, false);
675                         }
676                 }
677         }
678
679         /* Anyone who cares about input state, wake up and do something */
680
681         IOConnectionsComplete (); /* EMIT SIGNAL */
682
683         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
684
685         /* now handle the whole enchilada as if it was one
686            graph reorder event.
687         */
688
689         graph_reordered ();
690
691         /* update the full solo state, which can't be
692            correctly determined on a per-route basis, but
693            needs the global overview that only the session
694            has.
695         */
696
697         update_route_solo_state ();
698 }
699
700 void
701 Session::playlist_length_changed ()
702 {
703         /* we can't just increase session_range_location->end() if pl->get_maximum_extent()
704            if larger. if the playlist used to be the longest playlist,
705            and its now shorter, we have to decrease session_range_location->end(). hence,
706            we have to iterate over all diskstreams and check the
707            playlists currently in use.
708         */
709         find_current_end ();
710 }
711
712 void
713 Session::track_playlist_changed (boost::weak_ptr<Track> wp)
714 {
715         boost::shared_ptr<Track> track = wp.lock ();
716         if (!track) {
717                 return;
718         }
719         
720         boost::shared_ptr<Playlist> playlist;
721
722         if ((playlist = track->playlist()) != 0) {
723                 playlist->LengthChanged.connect_same_thread (*this, boost::bind (&Session::playlist_length_changed, this));
724         }
725
726         /* see comment in playlist_length_changed () */
727         find_current_end ();
728 }
729
730 bool
731 Session::record_enabling_legal () const
732 {
733         /* this used to be in here, but survey says.... we don't need to restrict it */
734         // if (record_status() == Recording) {
735         //      return false;
736         // }
737
738         if (Config->get_all_safe()) {
739                 return false;
740         }
741         return true;
742 }
743
744 void
745 Session::reset_input_monitor_state ()
746 {
747         if (transport_rolling()) {
748
749                 boost::shared_ptr<RouteList> rl = routes.reader ();
750                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
751                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
752                         if (tr && tr->record_enabled ()) {
753                                 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
754                                 tr->monitor_input (Config->get_monitoring_model() == HardwareMonitoring && !config.get_auto_input());
755                         }
756                 }
757                 
758         } else {
759                 
760                 boost::shared_ptr<RouteList> rl = routes.reader ();
761                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
762                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
763                         if (tr && tr->record_enabled ()) {
764                                 //cerr << "switching to input = " << !Config->get_auto_input() << __FILE__ << __LINE__ << endl << endl;
765                                 tr->monitor_input (Config->get_monitoring_model() == HardwareMonitoring);
766                         }
767                 }
768         }
769 }
770
771 void
772 Session::auto_punch_start_changed (Location* location)
773 {
774         replace_event (SessionEvent::PunchIn, location->start());
775
776         if (get_record_enabled() && config.get_punch_in()) {
777                 /* capture start has been changed, so save new pending state */
778                 save_state ("", true);
779         }
780 }
781
782 void
783 Session::auto_punch_end_changed (Location* location)
784 {
785         nframes_t when_to_stop = location->end();
786         // when_to_stop += _worst_output_latency + _worst_input_latency;
787         replace_event (SessionEvent::PunchOut, when_to_stop);
788 }
789
790 void
791 Session::auto_punch_changed (Location* location)
792 {
793         nframes_t when_to_stop = location->end();
794
795         replace_event (SessionEvent::PunchIn, location->start());
796         //when_to_stop += _worst_output_latency + _worst_input_latency;
797         replace_event (SessionEvent::PunchOut, when_to_stop);
798 }
799
800 void
801 Session::auto_loop_changed (Location* location)
802 {
803         replace_event (SessionEvent::AutoLoop, location->end(), location->start());
804
805         if (transport_rolling() && play_loop) {
806
807
808                 // if (_transport_frame > location->end()) {
809
810                 if (_transport_frame < location->start() || _transport_frame > location->end()) {
811                         // relocate to beginning of loop
812                         clear_events (SessionEvent::LocateRoll);
813
814                         request_locate (location->start(), true);
815
816                 }
817                 else if (Config->get_seamless_loop() && !loop_changing) {
818
819                         // schedule a locate-roll to refill the diskstreams at the
820                         // previous loop end
821                         loop_changing = true;
822
823                         if (location->end() > last_loopend) {
824                                 clear_events (SessionEvent::LocateRoll);
825                                 SessionEvent *ev = new SessionEvent (SessionEvent::LocateRoll, SessionEvent::Add, last_loopend, last_loopend, 0, true);
826                                 queue_event (ev);
827                         }
828
829                 }
830         }
831
832         last_loopend = location->end();
833 }
834
835 void
836 Session::set_auto_punch_location (Location* location)
837 {
838         Location* existing;
839
840         if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
841                 punch_connections.drop_connections();
842                 existing->set_auto_punch (false, this);
843                 remove_event (existing->start(), SessionEvent::PunchIn);
844                 clear_events (SessionEvent::PunchOut);
845                 auto_punch_location_changed (0);
846         }
847
848         set_dirty();
849
850         if (location == 0) {
851                 return;
852         }
853
854         if (location->end() <= location->start()) {
855                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
856                 return;
857         }
858
859         punch_connections.drop_connections ();
860
861         location->start_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_start_changed, this, _1));
862         location->end_changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_end_changed, this, _1));
863         location->changed.connect_same_thread (punch_connections, boost::bind (&Session::auto_punch_changed, this, _1));
864
865         location->set_auto_punch (true, this);
866
867         auto_punch_changed (location);
868
869         auto_punch_location_changed (location);
870 }
871
872 void
873 Session::set_auto_loop_location (Location* location)
874 {
875         Location* existing;
876
877         if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
878                 loop_connections.drop_connections ();
879                 existing->set_auto_loop (false, this);
880                 remove_event (existing->end(), SessionEvent::AutoLoop);
881                 auto_loop_location_changed (0);
882         }
883
884         set_dirty();
885
886         if (location == 0) {
887                 return;
888         }
889
890         if (location->end() <= location->start()) {
891                 error << _("Session: you can't use a mark for auto loop") << endmsg;
892                 return;
893         }
894
895         last_loopend = location->end();
896
897         loop_connections.drop_connections ();
898
899         location->start_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
900         location->end_changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
901         location->changed.connect_same_thread (loop_connections, boost::bind (&Session::auto_loop_changed, this, _1));
902
903         location->set_auto_loop (true, this);
904
905         /* take care of our stuff first */
906
907         auto_loop_changed (location);
908
909         /* now tell everyone else */
910
911         auto_loop_location_changed (location);
912 }
913
914 void
915 Session::locations_added (Location *)
916 {
917         set_dirty ();
918 }
919
920 void
921 Session::locations_changed ()
922 {
923         _locations.apply (*this, &Session::handle_locations_changed);
924 }
925
926 void
927 Session::handle_locations_changed (Locations::LocationList& locations)
928 {
929         Locations::LocationList::iterator i;
930         Location* location;
931         bool set_loop = false;
932         bool set_punch = false;
933
934         for (i = locations.begin(); i != locations.end(); ++i) {
935
936                 location =* i;
937
938                 if (location->is_auto_punch()) {
939                         set_auto_punch_location (location);
940                         set_punch = true;
941                 }
942                 if (location->is_auto_loop()) {
943                         set_auto_loop_location (location);
944                         set_loop = true;
945                 }
946
947                 if (location->is_session_range()) {
948                         _session_range_location = location;
949                 }
950         }
951
952         if (!set_loop) {
953                 set_auto_loop_location (0);
954         }
955         if (!set_punch) {
956                 set_auto_punch_location (0);
957         }
958
959         set_dirty();
960 }
961
962 void
963 Session::enable_record ()
964 {
965         /* XXX really atomic compare+swap here */
966         if (g_atomic_int_get (&_record_status) != Recording) {
967                 g_atomic_int_set (&_record_status, Recording);
968                 _last_record_location = _transport_frame;
969                 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
970
971                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
972                         
973                         boost::shared_ptr<RouteList> rl = routes.reader ();
974                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
975                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
976                                 if (tr && tr->record_enabled ()) {
977                                         tr->monitor_input (true);
978                                 }
979                         }
980                 }
981
982                 RecordStateChanged ();
983         }
984 }
985
986 void
987 Session::disable_record (bool rt_context, bool force)
988 {
989         RecordState rs;
990
991         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
992
993                 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
994                         g_atomic_int_set (&_record_status, Disabled);
995                 } else {
996                         if (rs == Recording) {
997                                 g_atomic_int_set (&_record_status, Enabled);
998                         }
999                 }
1000
1001                 // FIXME: timestamp correct? [DR]
1002                 // FIXME FIXME FIXME: rt_context?  this must be called in the process thread.
1003                 // does this /need/ to be sent in all cases?
1004                 if (rt_context) {
1005                         deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1006                 }
1007
1008                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1009
1010                         boost::shared_ptr<RouteList> rl = routes.reader ();
1011                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1012                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1013                                 if (tr && tr->record_enabled ()) {
1014                                         tr->monitor_input (false);
1015                                 }
1016                         }
1017                 }
1018
1019                 RecordStateChanged (); /* emit signal */
1020
1021                 if (!rt_context) {
1022                         remove_pending_capture_state ();
1023                 }
1024         }
1025 }
1026
1027 void
1028 Session::step_back_from_record ()
1029 {
1030         if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1031
1032                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1033                         boost::shared_ptr<RouteList> rl = routes.reader ();
1034                         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1035                                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1036                                 if (tr && tr->record_enabled ()) {
1037                                         //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1038                                         tr->monitor_input (false);
1039                                 }
1040                         }
1041                 }
1042         }
1043 }
1044
1045 void
1046 Session::maybe_enable_record ()
1047 {
1048         g_atomic_int_set (&_record_status, Enabled);
1049
1050         /* this function is currently called from somewhere other than an RT thread.
1051            this save_state() call therefore doesn't impact anything.
1052         */
1053
1054         save_state ("", true);
1055
1056         if (_transport_speed) {
1057                 if (!config.get_punch_in()) {
1058                         enable_record ();
1059                 }
1060         } else {
1061                 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1062                 RecordStateChanged (); /* EMIT SIGNAL */
1063         }
1064
1065         set_dirty();
1066 }
1067
1068 nframes64_t
1069 Session::audible_frame () const
1070 {
1071         nframes64_t ret;
1072         nframes64_t tf;
1073         nframes_t offset;
1074
1075         /* the first of these two possible settings for "offset"
1076            mean that the audible frame is stationary until
1077            audio emerges from the latency compensation
1078            "pseudo-pipeline".
1079
1080            the second means that the audible frame is stationary
1081            until audio would emerge from a physical port
1082            in the absence of any plugin latency compensation
1083         */
1084
1085         offset = _worst_output_latency;
1086
1087         if (offset > current_block_size) {
1088                 offset -= current_block_size;
1089         } else {
1090                 /* XXX is this correct? if we have no external
1091                    physical connections and everything is internal
1092                    then surely this is zero? still, how
1093                    likely is that anyway?
1094                 */
1095                 offset = current_block_size;
1096         }
1097
1098         if (synced_to_jack()) {
1099                 tf = _engine.transport_frame();
1100         } else {
1101                 tf = _transport_frame;
1102         }
1103
1104         ret = tf;
1105
1106         if (!non_realtime_work_pending()) {
1107
1108                 /* MOVING */
1109
1110                 /* Check to see if we have passed the first guaranteed
1111                    audible frame past our last start position. if not,
1112                    return that last start point because in terms
1113                    of audible frames, we have not moved yet.
1114
1115                    `Start position' in this context means the time we last
1116                    either started or changed transport direction.
1117                 */
1118
1119                 if (_transport_speed > 0.0f) {
1120
1121                         if (!play_loop || !have_looped) {
1122                                 if (tf < _last_roll_or_reversal_location + offset) {
1123                                         return _last_roll_or_reversal_location;
1124                                 }
1125                         }
1126
1127
1128                         /* forwards */
1129                         ret -= offset;
1130
1131                 } else if (_transport_speed < 0.0f) {
1132
1133                         /* XXX wot? no backward looping? */
1134
1135                         if (tf > _last_roll_or_reversal_location - offset) {
1136                                 return _last_roll_or_reversal_location;
1137                         } else {
1138                                 /* backwards */
1139                                 ret += offset;
1140                         }
1141                 }
1142         }
1143
1144         return ret;
1145 }
1146
1147 void
1148 Session::set_frame_rate (nframes_t frames_per_second)
1149 {
1150         /** \fn void Session::set_frame_size(nframes_t)
1151                 the AudioEngine object that calls this guarantees
1152                 that it will not be called while we are also in
1153                 ::process(). Its fine to do things that block
1154                 here.
1155         */
1156
1157         _base_frame_rate = frames_per_second;
1158
1159         sync_time_vars();
1160
1161         Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1162
1163         clear_clicks ();
1164
1165         // XXX we need some equivalent to this, somehow
1166         // SndFileSource::setup_standard_crossfades (frames_per_second);
1167
1168         set_dirty();
1169
1170         /* XXX need to reset/reinstantiate all LADSPA plugins */
1171 }
1172
1173 void
1174 Session::set_block_size (nframes_t nframes)
1175 {
1176         /* the AudioEngine guarantees
1177            that it will not be called while we are also in
1178            ::process(). It is therefore fine to do things that block
1179            here.
1180         */
1181
1182         {
1183                 current_block_size = nframes;
1184
1185                 ensure_buffers ();
1186
1187                 boost::shared_ptr<RouteList> r = routes.reader ();
1188
1189                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1190                         (*i)->set_block_size (nframes);
1191                 }
1192
1193                 boost::shared_ptr<RouteList> rl = routes.reader ();
1194                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1195                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1196                         if (tr) {
1197                                 tr->set_block_size (nframes);
1198                         }
1199                 }
1200
1201                 set_worst_io_latencies ();
1202         }
1203 }
1204
1205 void
1206 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1207 {
1208 #if 0
1209         nframes_t fade_frames;
1210
1211         /* Don't allow fade of less 1 frame */
1212
1213         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1214
1215                 fade_msecs = 0;
1216                 fade_frames = 0;
1217
1218         } else {
1219
1220                 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1221
1222         }
1223
1224         default_fade_msecs = fade_msecs;
1225         default_fade_steepness = steepness;
1226
1227         {
1228                 // jlc, WTF is this!
1229                 Glib::RWLock::ReaderLock lm (route_lock);
1230                 AudioRegion::set_default_fade (steepness, fade_frames);
1231         }
1232
1233         set_dirty();
1234
1235         /* XXX have to do this at some point */
1236         /* foreach region using default fade, reset, then
1237            refill_all_diskstream_buffers ();
1238         */
1239 #endif
1240 }
1241
1242 struct RouteSorter {
1243     bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1244             if (r2->feeds (r1)) {
1245                     return false;
1246             } else if (r1->feeds (r2)) {
1247                     return true;
1248             } else {
1249                     if (r1->not_fed ()) {
1250                             if (r2->not_fed ()) {
1251                                     /* no ardour-based connections inbound to either route. just use signal order */
1252                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1253                             } else {
1254                                     /* r2 has connections, r1 does not; run r1 early */
1255                                     return true;
1256                             }
1257                     } else {
1258                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1259                     }
1260             }
1261     }
1262 };
1263
1264 static void
1265 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1266 {
1267         shared_ptr<Route> r2;
1268
1269         if (r1->feeds (rbase) && rbase->feeds (r1)) {
1270                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1271                 return;
1272         }
1273
1274         /* make a copy of the existing list of routes that feed r1 */
1275
1276         Route::FedBy existing (r1->fed_by());
1277                         
1278         /* for each route that feeds r1, recurse, marking it as feeding
1279            rbase as well.
1280         */
1281
1282         for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1283                 if (!(r2 = i->r.lock ())) {
1284                         /* (*i) went away, ignore it */
1285                         continue;
1286                 }
1287                 
1288                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1289                    base as being fed by r2
1290                 */
1291
1292                 rbase->add_fed_by (r2, i->sends_only);
1293
1294                 if (r2 != rbase) {
1295
1296                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1297                            stop here.
1298                         */
1299
1300                         if (r1->feeds (r2) && r2->feeds (r1)) {
1301                                 continue;
1302                         }
1303
1304                         /* now recurse, so that we can mark base as being fed by
1305                            all routes that feed r2
1306                         */
1307
1308                         trace_terminal (r2, rbase);
1309                 }
1310
1311         }
1312 }
1313
1314 void
1315 Session::resort_routes ()
1316 {
1317         /* don't do anything here with signals emitted
1318            by Routes while we are being destroyed.
1319         */
1320
1321         if (_state_of_the_state & Deletion) {
1322                 return;
1323         }
1324
1325
1326         {
1327
1328                 RCUWriter<RouteList> writer (routes);
1329                 shared_ptr<RouteList> r = writer.get_copy ();
1330                 resort_routes_using (r);
1331                 /* writer goes out of scope and forces update */
1332         }
1333
1334 #ifndef NDEBUG
1335         boost::shared_ptr<RouteList> rl = routes.reader ();
1336         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1337                 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1338                 
1339                 const Route::FedBy& fb ((*i)->fed_by());
1340
1341                 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1342                         boost::shared_ptr<Route> sf = f->r.lock();
1343                         if (sf) {
1344                                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1345                         }
1346                 }
1347         }
1348 #endif
1349
1350 }
1351 void
1352 Session::resort_routes_using (shared_ptr<RouteList> r)
1353 {
1354         RouteList::iterator i, j;
1355
1356         for (i = r->begin(); i != r->end(); ++i) {
1357                 (*i)->check_physical_connections ();
1358         }
1359
1360         for (i = r->begin(); i != r->end(); ++i) {
1361
1362                 (*i)->clear_fed_by ();
1363
1364                 for (j = r->begin(); j != r->end(); ++j) {
1365
1366                         /* although routes can feed themselves, it will
1367                            cause an endless recursive descent if we
1368                            detect it. so don't bother checking for
1369                            self-feeding.
1370                         */
1371
1372                         if (*j == *i) {
1373                                 continue;
1374                         }
1375
1376                         bool via_sends_only;
1377
1378                         if ((*j)->direct_feeds (*i, &via_sends_only)) {
1379                                 (*i)->add_fed_by (*j, via_sends_only);
1380                         }
1381                 }
1382         }
1383
1384         for (i = r->begin(); i != r->end(); ++i) {
1385                 trace_terminal (*i, *i);
1386         }
1387
1388         RouteSorter cmp;
1389         r->sort (cmp);
1390
1391         find_route_levels (r);
1392
1393 #ifndef NDEBUG
1394         DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1395         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1396                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2 level %3\n", 
1397                                                            (*i)->name(), (*i)->order_key ("signal"),
1398                                                            (*i)->graph_level()));
1399         }
1400 #endif
1401
1402 }
1403
1404 void
1405 Session::find_route_levels (shared_ptr<RouteList> rl)
1406 {
1407         uint32_t setcnt = 0;
1408         uint32_t limit = rl->size();
1409         RouteList last_level;
1410         RouteList this_level;
1411
1412         for (RouteList::iterator r = rl->begin(); r != rl->end(); ++r) {
1413                 
1414                 /* find routes with direct physical connections,
1415                    or routes with no connections at all. Mark them
1416                    with "special" level values, and push them into
1417                    the "last_level" set.
1418                 
1419                    All other routes get marked with a graph level
1420                    of -1, which indicates that it needs to be set.
1421
1422                 */
1423                 
1424                 if ((*r)->physically_connected()) {
1425                         last_level.push_back (*r);
1426                         (*r)->set_graph_level (0);
1427                         setcnt++;
1428                 } else if (!(*r)->output()->connected()) {
1429                         last_level.push_back (*r);
1430                         (*r)->set_graph_level (INT32_MAX/2);
1431                         setcnt++;
1432                 } else {
1433                         (*r)->set_graph_level (-1);
1434                 }
1435         }
1436
1437         // until we've set the graph level for every route ... 
1438
1439         while (setcnt < limit) {
1440
1441                 for (RouteList::reverse_iterator r = rl->rbegin(); r != rl->rend(); ++r) {
1442
1443                         int32_t l = INT32_MAX;
1444                         bool found = false;
1445
1446                         if ((*r)->graph_level() != -1) {
1447                                 // we already have the graph level for this route
1448                                 continue;
1449                         }
1450
1451                         /* check if this route (r) has a direction connection to anything in
1452                            the set of routes we processed last time. On the first pass
1453                            through this, last_level will contain routes with either
1454                            no connections or direct "physical" connections. If there is
1455                            at least 1 connection, store the lowest graph level of whatever
1456                            r is connected to.
1457                         */
1458
1459                         for (RouteList::iterator o = last_level.begin(); o != last_level.end(); ++o) {
1460                                 bool sends_only;
1461                                 if ((*r)->direct_feeds (*o, &sends_only)) {
1462                                         if (!sends_only) {
1463                                                 l = min (l, (*o)->graph_level());
1464                                                 found = true;
1465                                         }
1466                                 }
1467                         }
1468
1469                         /* if we found any connections, then mark the graph level of r, and push
1470                            it into the "this_level" set that will become "last_level" next time
1471                            around the while() loop.
1472                         */
1473
1474                         if (found) {
1475                                 (*r)->set_graph_level (l + 1);
1476                                 this_level.push_back (*r);
1477                                 setcnt++;
1478                         }
1479                 }
1480
1481                 last_level = this_level;
1482                 this_level.clear ();
1483         }
1484 }
1485
1486
1487 /** Find the route name starting with \a base with the lowest \a id.
1488  *
1489  * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1490  * The available route name with the lowest ID will be used, and \a id
1491  * will be set to the ID.
1492  *
1493  * \return false if a route name could not be found, and \a track_name
1494  * and \a id do not reflect a free route name.
1495  */
1496 bool
1497 Session::find_route_name (const char* base, uint32_t& id, char* name, size_t name_len)
1498 {
1499         do {
1500                 snprintf (name, name_len, "%s %" PRIu32, base, id);
1501
1502                 if (route_by_name (name) == 0) {
1503                         return true;
1504                 }
1505
1506                 ++id;
1507
1508         } while (id < (UINT_MAX-1));
1509
1510         return false;
1511 }
1512
1513 void
1514 Session::count_existing_route_channels (ChanCount& in, ChanCount& out)
1515 {
1516         in  = ChanCount::ZERO;
1517         out = ChanCount::ZERO;
1518         shared_ptr<RouteList> r = routes.reader ();
1519         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1520                 if (!(*i)->is_hidden()) {
1521                         in += (*i)->n_inputs();
1522                         out     += (*i)->n_outputs();
1523                 }
1524         }
1525 }
1526
1527 list<boost::shared_ptr<MidiTrack> >
1528 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1529 {
1530         char track_name[32];
1531         uint32_t track_id = 0;
1532         ChanCount existing_inputs;
1533         ChanCount existing_outputs;
1534         string port;
1535         RouteList new_routes;
1536         list<boost::shared_ptr<MidiTrack> > ret;
1537         uint32_t control_id;
1538
1539         count_existing_route_channels (existing_inputs, existing_outputs);
1540
1541         control_id = ntracks() + nbusses();
1542
1543         while (how_many) {
1544                 if (!find_route_name ("Midi", ++track_id, track_name, sizeof(track_name))) {
1545                         error << "cannot find name for new midi track" << endmsg;
1546                         goto failed;
1547                 }
1548
1549                 shared_ptr<MidiTrack> track;
1550
1551                 try {
1552                         MidiTrack* mt = new MidiTrack (*this, track_name, Route::Flag (0), mode);
1553
1554                         if (mt->init ()) {
1555                                 delete mt;
1556                                 goto failed;
1557                         }
1558
1559                         mt->use_new_diskstream();
1560
1561                         boost_debug_shared_ptr_mark_interesting (mt, "Track");
1562                         track = boost::shared_ptr<MidiTrack>(mt);
1563
1564                         if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1565                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1566                                 goto failed;
1567                         }
1568
1569
1570                         if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1571                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1572                                 goto failed;
1573                         }
1574
1575                         auto_connect_route (track, existing_inputs, existing_outputs);
1576
1577                         track->non_realtime_input_change();
1578                         if (route_group) {
1579                                 route_group->add (track);
1580                         }
1581
1582                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1583                         track->set_remote_control_id (control_id);
1584
1585                         new_routes.push_back (track);
1586                         ret.push_back (track);
1587                 }
1588
1589                 catch (failed_constructor &err) {
1590                         error << _("Session: could not create new midi track.") << endmsg;
1591                         goto failed;
1592                 }
1593
1594                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1595
1596                         error << string_compose (_("No more JACK ports are available. You will need to stop %1 and restart JACK with ports if you need this many tracks."), PROGRAM_NAME) << endmsg;
1597                         goto failed;
1598                 }
1599
1600                 --how_many;
1601         }
1602
1603   failed:
1604         if (!new_routes.empty()) {
1605                 add_routes (new_routes, false);
1606                 save_state (_current_snapshot_name);
1607         }
1608
1609         return ret;
1610 }
1611
1612 void
1613 Session::auto_connect_route (boost::shared_ptr<Route> route,
1614                 ChanCount& existing_inputs, ChanCount& existing_outputs)
1615 {
1616         /* If both inputs and outputs are auto-connected to physical ports,
1617            use the max of input and output offsets to ensure auto-connected
1618            port numbers always match up (e.g. the first audio input and the
1619            first audio output of the route will have the same physical
1620            port number).  Otherwise just use the lowest input or output
1621            offset possible.
1622         */
1623         const bool in_out_physical =
1624                    (Config->get_input_auto_connect() & AutoConnectPhysical)
1625                 && (Config->get_output_auto_connect() & AutoConnectPhysical);
1626
1627         const ChanCount in_offset = in_out_physical
1628                 ? ChanCount::max(existing_inputs, existing_outputs)
1629                 : existing_inputs;
1630
1631         const ChanCount out_offset = in_out_physical
1632                 ? ChanCount::max(existing_inputs, existing_outputs)
1633                 : existing_outputs;
1634
1635         static string empty_string;
1636         string& port = empty_string;
1637
1638         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1639                 vector<string> physinputs;
1640                 vector<string> physoutputs;
1641
1642                 _engine.get_physical_outputs (*t, physoutputs);
1643                 _engine.get_physical_inputs (*t, physinputs);
1644
1645                 if (!physinputs.empty()) {
1646                         uint32_t nphysical_in = physinputs.size();
1647                         for (uint32_t i = 0; i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1648                                 port = empty_string;
1649
1650                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1651                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1652                                 }
1653
1654                                 if (!port.empty() && route->input()->connect (
1655                                                 route->input()->ports().port(*t, i), port, this)) {
1656                                         break;
1657                                 }
1658                         }
1659                 }
1660
1661                 if (!physoutputs.empty()) {
1662                         uint32_t nphysical_out = physoutputs.size();
1663                         for (uint32_t i = 0; i < route->n_outputs().get(*t); ++i) {
1664                                 port = empty_string;
1665
1666                                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1667                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1668                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1669                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1670                                                 port = _master_out->input()->ports().port(*t,
1671                                                                 i % _master_out->input()->n_ports().get(*t))->name();
1672                                         }
1673                                 }
1674
1675                                 if (!port.empty() && route->output()->connect (
1676                                                 route->output()->ports().port(*t, i), port, this)) {
1677                                         break;
1678                                 }
1679                         }
1680                 }
1681         }
1682
1683         existing_inputs += route->n_inputs();
1684         existing_outputs += route->n_outputs();
1685 }
1686
1687 list< boost::shared_ptr<AudioTrack> >
1688 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1689 {
1690         char track_name[32];
1691         uint32_t track_id = 0;
1692         ChanCount existing_inputs;
1693         ChanCount existing_outputs;
1694         string port;
1695         RouteList new_routes;
1696         list<boost::shared_ptr<AudioTrack> > ret;
1697         uint32_t control_id;
1698
1699         count_existing_route_channels (existing_inputs, existing_outputs);
1700
1701         control_id = ntracks() + nbusses() + 1;
1702
1703         while (how_many) {
1704                 if (!find_route_name ("Audio", ++track_id, track_name, sizeof(track_name))) {
1705                         error << "cannot find name for new audio track" << endmsg;
1706                         goto failed;
1707                 }
1708
1709                 shared_ptr<AudioTrack> track;
1710
1711                 try {
1712                         AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1713
1714                         if (at->init ()) {
1715                                 delete at;
1716                                 goto failed;
1717                         }
1718
1719                         at->use_new_diskstream();
1720
1721                         boost_debug_shared_ptr_mark_interesting (at, "Track");
1722                         track = boost::shared_ptr<AudioTrack>(at);
1723
1724                         if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1725                                 error << string_compose (
1726                                                         _("cannot configure %1 in/%2 out configuration for new audio track"),
1727                                                          input_channels, output_channels)
1728                                       << endmsg;
1729                                 goto failed;
1730                         }
1731
1732                         if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1733                                 error << string_compose (
1734                                                         _("cannot configure %1 in/%2 out configuration for new audio track"),
1735                                                          input_channels, output_channels)
1736                                       << endmsg;
1737                                 goto failed;
1738                         }
1739
1740                         auto_connect_route (track, existing_inputs, existing_outputs);
1741
1742                         if (route_group) {
1743                                 route_group->add (track);
1744                         }
1745
1746                         track->non_realtime_input_change();
1747
1748                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1749                         track->set_remote_control_id (control_id);
1750                         ++control_id;
1751
1752                         new_routes.push_back (track);
1753                         ret.push_back (track);
1754                 }
1755
1756                 catch (failed_constructor &err) {
1757                         error << _("Session: could not create new audio track.") << endmsg;
1758                         goto failed;
1759                 }
1760
1761                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1762
1763                         error << pfe.what() << endmsg;
1764                         goto failed;
1765                 }
1766
1767                 --how_many;
1768         }
1769
1770   failed:
1771         if (!new_routes.empty()) {
1772                 add_routes (new_routes, true);
1773         }
1774
1775         return ret;
1776 }
1777
1778 void
1779 Session::set_remote_control_ids ()
1780 {
1781         RemoteModel m = Config->get_remote_model();
1782         bool emit_signal = false;
1783
1784         shared_ptr<RouteList> r = routes.reader ();
1785
1786         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1787                 if (MixerOrdered == m) {
1788                         long order = (*i)->order_key(N_("signal"));
1789                         (*i)->set_remote_control_id (order+1, false);
1790                         emit_signal = true;
1791                 } else if (EditorOrdered == m) {
1792                         long order = (*i)->order_key(N_("editor"));
1793                         (*i)->set_remote_control_id (order+1, false);
1794                         emit_signal = true;
1795                 } else if (UserOrdered == m) {
1796                         //do nothing ... only changes to remote id's are initiated by user
1797                 }
1798         }
1799
1800         if (emit_signal) {
1801                 Route::RemoteControlIDChange();
1802         }
1803 }
1804
1805
1806 RouteList
1807 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1808 {
1809         char bus_name[32];
1810         uint32_t bus_id = 0;
1811         ChanCount existing_inputs;
1812         ChanCount existing_outputs;
1813         string port;
1814         RouteList ret;
1815         uint32_t control_id;
1816
1817         count_existing_route_channels (existing_inputs, existing_outputs);
1818
1819         control_id = ntracks() + nbusses() + 1;
1820
1821         while (how_many) {
1822                 if (!find_route_name ("Bus", ++bus_id, bus_name, sizeof(bus_name))) {
1823                         error << "cannot find name for new audio bus" << endmsg;
1824                         goto failure;
1825                 }
1826
1827                 try {
1828                         Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1829
1830                         if (rt->init ()) {
1831                                 delete rt;
1832                                 goto failure;
1833                         }
1834
1835                         boost_debug_shared_ptr_mark_interesting (rt, "Route");
1836                         shared_ptr<Route> bus (rt);
1837
1838                         if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1839                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1840                                                          input_channels, output_channels)
1841                                       << endmsg;
1842                                 goto failure;
1843                         }
1844
1845
1846                         if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1847                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1848                                                          input_channels, output_channels)
1849                                       << endmsg;
1850                                 goto failure;
1851                         }
1852
1853                         auto_connect_route (bus, existing_inputs, existing_outputs);
1854
1855                         if (route_group) {
1856                                 route_group->add (bus);
1857                         }
1858                         bus->set_remote_control_id (control_id);
1859                         ++control_id;
1860
1861                         if (aux) {
1862                                 bus->add_internal_return ();
1863                         }
1864
1865                         ret.push_back (bus);
1866                 }
1867
1868
1869                 catch (failed_constructor &err) {
1870                         error << _("Session: could not create new audio route.") << endmsg;
1871                         goto failure;
1872                 }
1873
1874                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1875                         error << pfe.what() << endmsg;
1876                         goto failure;
1877                 }
1878
1879
1880                 --how_many;
1881         }
1882
1883   failure:
1884         if (!ret.empty()) {
1885                 add_routes (ret, true);
1886         }
1887
1888         return ret;
1889
1890 }
1891
1892 RouteList
1893 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1894 {
1895         char name[32];
1896         RouteList ret;
1897         uint32_t control_id;
1898         XMLTree tree;
1899         uint32_t number = 0;
1900
1901         if (!tree.read (template_path.c_str())) {
1902                 return ret;
1903         }
1904
1905         XMLNode* node = tree.root();
1906
1907         control_id = ntracks() + nbusses() + 1;
1908
1909         while (how_many) {
1910
1911                 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1912
1913                 std::string node_name = IO::name_from_state (*node_copy.children().front());
1914
1915                 /* generate a new name by adding a number to the end of the template name */
1916                 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name))) {
1917                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1918                         /*NOTREACHED*/
1919                 }
1920
1921                 IO::set_name_in_state (*node_copy.children().front(), name);
1922
1923                 Track::zero_diskstream_id_in_xml (node_copy);
1924
1925                 try {
1926                         shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1927             
1928                         if (route == 0) {
1929                                 error << _("Session: cannot create track/bus from template description") << endmsg;
1930                                 goto out;
1931                         }
1932
1933                         if (boost::dynamic_pointer_cast<Track>(route)) {
1934                                 /* force input/output change signals so that the new diskstream
1935                                    picks up the configuration of the route. During session
1936                                    loading this normally happens in a different way.
1937                                 */
1938                                 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1939                                 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1940                         }
1941
1942                         route->set_remote_control_id (control_id);
1943                         ++control_id;
1944
1945                         ret.push_back (route);
1946                 }
1947
1948                 catch (failed_constructor &err) {
1949                         error << _("Session: could not create new route from template") << endmsg;
1950                         goto out;
1951                 }
1952
1953                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1954                         error << pfe.what() << endmsg;
1955                         goto out;
1956                 }
1957
1958                 --how_many;
1959         }
1960
1961   out:
1962         if (!ret.empty()) {
1963                 add_routes (ret, true);
1964         }
1965
1966         return ret;
1967 }
1968
1969 void
1970 Session::add_routes (RouteList& new_routes, bool save)
1971 {
1972         {
1973                 RCUWriter<RouteList> writer (routes);
1974                 shared_ptr<RouteList> r = writer.get_copy ();
1975                 r->insert (r->end(), new_routes.begin(), new_routes.end());
1976
1977
1978                 /* if there is no control out and we're not in the middle of loading,
1979                    resort the graph here. if there is a control out, we will resort
1980                    toward the end of this method. if we are in the middle of loading,
1981                    we will resort when done.
1982                 */
1983
1984                 if (!_monitor_out && IO::connecting_legal) {
1985                         resort_routes_using (r);
1986                 }
1987         }
1988
1989         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1990
1991                 boost::weak_ptr<Route> wpr (*x);
1992                 boost::shared_ptr<Route> r (*x);
1993
1994                 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1995                 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
1996                 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
1997                 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1998                 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1999                 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
2000                 r->route_group_changed.connect_same_thread (*this, boost::bind (&Session::route_group_changed, this));
2001
2002                 if (r->is_master()) {
2003                         _master_out = r;
2004                 }
2005
2006                 if (r->is_monitor()) {
2007                         _monitor_out = r;
2008                 }
2009
2010                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
2011                 if (tr) {
2012                         tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
2013                         track_playlist_changed (boost::weak_ptr<Track> (tr));
2014                         tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
2015                 }
2016         }
2017
2018         if (_monitor_out && IO::connecting_legal) {
2019
2020                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
2021                         if ((*x)->is_monitor()) {
2022                                 /* relax */
2023                         } else if ((*x)->is_master()) {
2024                                 /* relax */
2025                         } else {
2026                                 (*x)->listen_via (_monitor_out,
2027                                                   (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
2028                                                   false, false);
2029                         }
2030                 }
2031
2032                 resort_routes ();
2033         }
2034
2035         set_dirty();
2036
2037         if (save) {
2038                 save_state (_current_snapshot_name);
2039         }
2040
2041         RouteAdded (new_routes); /* EMIT SIGNAL */
2042         Route::RemoteControlIDChange (); /* EMIT SIGNAL */
2043 }
2044
2045 void
2046 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
2047 {
2048         boost::shared_ptr<RouteList> r = routes.reader ();
2049         boost::shared_ptr<Send> s;
2050
2051         /* only tracks */
2052
2053         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2054                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2055                         if ((s = (*i)->internal_send_for (dest)) != 0) {
2056                                 s->amp()->gain_control()->set_value (0.0);
2057                         }
2058                 }
2059         }
2060 }
2061
2062 void
2063 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
2064 {
2065         boost::shared_ptr<RouteList> r = routes.reader ();
2066         boost::shared_ptr<Send> s;
2067
2068         /* only tracks */
2069
2070         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2071                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2072                         if ((s = (*i)->internal_send_for (dest)) != 0) {
2073                                 s->amp()->gain_control()->set_value (1.0);
2074                         }
2075                 }
2076         }
2077 }
2078
2079 void
2080 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2081 {
2082         boost::shared_ptr<RouteList> r = routes.reader ();
2083         boost::shared_ptr<Send> s;
2084
2085         /* only tracks */
2086
2087         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2088                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2089                         if ((s = (*i)->internal_send_for (dest)) != 0) {
2090                                 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2091                         }
2092                 }
2093         }
2094 }
2095
2096 void
2097 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2098 {
2099         boost::shared_ptr<RouteList> r = routes.reader ();
2100         boost::shared_ptr<RouteList> t (new RouteList);
2101
2102         /* only send tracks */
2103
2104         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2105                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2106                         t->push_back (*i);
2107                 }
2108         }
2109
2110         add_internal_sends (dest, p, t);
2111 }
2112
2113 void
2114 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2115 {
2116         if (dest->is_monitor() || dest->is_master()) {
2117                 return;
2118         }
2119
2120         if (!dest->internal_return()) {
2121                 dest->add_internal_return();
2122         }
2123
2124         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2125
2126                 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2127                         continue;
2128                 }
2129
2130                 (*i)->listen_via (dest, p, true, true);
2131         }
2132
2133         graph_reordered ();
2134 }
2135
2136 void
2137 Session::remove_route (shared_ptr<Route> route)
2138 {
2139         {
2140                 RCUWriter<RouteList> writer (routes);
2141                 shared_ptr<RouteList> rs = writer.get_copy ();
2142
2143                 rs->remove (route);
2144
2145                 /* deleting the master out seems like a dumb
2146                    idea, but its more of a UI policy issue
2147                    than our concern.
2148                 */
2149
2150                 if (route == _master_out) {
2151                         _master_out = shared_ptr<Route> ();
2152                 }
2153
2154                 if (route == _monitor_out) {
2155
2156                         /* cancel control outs for all routes */
2157
2158                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2159                                 (*r)->drop_listen (_monitor_out);
2160                         }
2161
2162                         _monitor_out.reset ();
2163                 }
2164
2165                 /* writer goes out of scope, forces route list update */
2166         }
2167         
2168         update_route_solo_state ();
2169         find_current_end ();
2170
2171         // We need to disconnect the route's inputs and outputs
2172
2173         route->input()->disconnect (0);
2174         route->output()->disconnect (0);
2175
2176         /* if the route had internal sends sending to it, remove them */
2177         if (route->internal_return()) {
2178
2179                 boost::shared_ptr<RouteList> r = routes.reader ();
2180                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2181                         boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2182                         if (s) {
2183                                 (*i)->remove_processor (s);
2184                         }
2185                 }
2186         }       
2187
2188         update_latency_compensation (false, false);
2189         set_dirty();
2190
2191         /* get rid of it from the dead wood collection in the route list manager */
2192
2193         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2194
2195         routes.flush ();
2196
2197         /* try to cause everyone to drop their references */
2198
2199         route->drop_references ();
2200
2201         sync_order_keys (N_("session"));
2202
2203         Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2204
2205         /* save the new state of the world */
2206
2207         if (save_state (_current_snapshot_name)) {
2208                 save_history (_current_snapshot_name);
2209         }
2210 }
2211
2212 void
2213 Session::route_mute_changed (void* /*src*/)
2214 {
2215         set_dirty ();
2216 }
2217
2218 void
2219 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2220 {
2221         boost::shared_ptr<Route> route = wpr.lock();
2222         if (!route) {
2223                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2224                 return;
2225         }
2226
2227         if (route->listening()) {
2228
2229                 if (Config->get_exclusive_solo()) {
2230                         /* new listen: disable all other listen */
2231                         shared_ptr<RouteList> r = routes.reader ();
2232                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2233                                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2234                                         continue;
2235                                 } 
2236                                 (*i)->set_listen (false, this);
2237                         }
2238                 }
2239
2240                 _listen_cnt++;
2241
2242         } else if (_listen_cnt > 0) {
2243
2244                 _listen_cnt--;
2245         }
2246 }
2247 void
2248 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2249 {
2250         boost::shared_ptr<Route> route = wpr.lock ();
2251
2252         if (!route) {
2253                 /* should not happen */
2254                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2255                 return;
2256         }
2257         
2258         bool send_changed = false;
2259
2260         if (route->solo_isolated()) {
2261                 if (_solo_isolated_cnt == 0) {
2262                         send_changed = true;
2263                 }
2264                 _solo_isolated_cnt++;
2265         } else if (_solo_isolated_cnt > 0) {
2266                 _solo_isolated_cnt--;
2267                 if (_solo_isolated_cnt == 0) {
2268                         send_changed = true;
2269                 }
2270         }
2271
2272         if (send_changed) {
2273                 IsolatedChanged (); /* EMIT SIGNAL */
2274         }
2275 }
2276             
2277 void
2278 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2279 {
2280         if (!self_solo_change) {
2281                 // session doesn't care about changes to soloed-by-others
2282                 return;
2283         }
2284
2285         if (solo_update_disabled) {
2286                 // We know already
2287                 return;
2288         }
2289
2290         boost::shared_ptr<Route> route = wpr.lock ();
2291
2292         if (!route) {
2293                 /* should not happen */
2294                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2295                 return;
2296         }
2297         
2298         shared_ptr<RouteList> r = routes.reader ();
2299         int32_t delta;
2300
2301         if (route->self_soloed()) {
2302                 delta = 1;
2303         } else {
2304                 delta = -1;
2305         }
2306  
2307         if (delta == 1 && Config->get_exclusive_solo()) {
2308                 /* new solo: disable all other solos */
2309                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2310                         if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2311                                 continue;
2312                         } 
2313                         (*i)->set_solo (false, this);
2314                 }
2315         }
2316
2317         solo_update_disabled = true;
2318         
2319         RouteList uninvolved;
2320         
2321         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2322                 bool via_sends_only;
2323                 bool in_signal_flow;
2324
2325                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2326                         continue;
2327                 } 
2328
2329                 in_signal_flow = false;
2330
2331                 if ((*i)->feeds (route, &via_sends_only)) {
2332                         if (!via_sends_only) {
2333                                 if (!route->soloed_by_others_upstream()) {
2334                                         (*i)->mod_solo_by_others_downstream (delta);
2335                                 }
2336                                 in_signal_flow = true;
2337                         }
2338                 } 
2339                 
2340                 if (route->feeds (*i, &via_sends_only)) {
2341                         (*i)->mod_solo_by_others_upstream (delta);
2342                         in_signal_flow = true;
2343                 }
2344
2345                 if (!in_signal_flow) {
2346                         uninvolved.push_back (*i);
2347                 }
2348         }
2349
2350         solo_update_disabled = false;
2351         update_route_solo_state (r);
2352
2353         /* now notify that the mute state of the routes not involved in the signal
2354            pathway of the just-solo-changed route may have altered.
2355         */
2356
2357         for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2358                 (*i)->mute_changed (this);
2359         }
2360
2361         SoloChanged (); /* EMIT SIGNAL */
2362         set_dirty();
2363 }
2364
2365 void
2366 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2367 {
2368         /* now figure out if anything that matters is soloed (or is "listening")*/
2369
2370         bool something_soloed = false;
2371         uint32_t listeners = 0;
2372         uint32_t isolated = 0;
2373
2374         if (!r) {
2375                 r = routes.reader();
2376         }
2377
2378         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2379                 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2380                         something_soloed = true;
2381                 }
2382
2383                 if (!(*i)->is_hidden() && (*i)->listening()) {
2384                         if (Config->get_solo_control_is_listen_control()) {
2385                                 listeners++;
2386                         } else {
2387                                 (*i)->set_listen (false, this);
2388                         }
2389                 }
2390
2391                 if ((*i)->solo_isolated()) {
2392                         isolated++;
2393                 }
2394         }
2395
2396         if (something_soloed != _non_soloed_outs_muted) {
2397                 _non_soloed_outs_muted = something_soloed;
2398                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2399         }
2400
2401         _listen_cnt = listeners;
2402
2403         if (isolated != _solo_isolated_cnt) {
2404                 _solo_isolated_cnt = isolated;
2405                 IsolatedChanged (); /* EMIT SIGNAL */
2406         }
2407 }
2408
2409 boost::shared_ptr<RouteList> 
2410 Session::get_routes_with_internal_returns() const
2411 {
2412         shared_ptr<RouteList> r = routes.reader ();
2413         boost::shared_ptr<RouteList> rl (new RouteList);
2414
2415         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2416                 if ((*i)->internal_return ()) {
2417                         rl->push_back (*i);
2418                 }
2419         }
2420         return rl;
2421 }
2422
2423 bool
2424 Session::io_name_is_legal (const std::string& name)
2425 {
2426         shared_ptr<RouteList> r = routes.reader ();
2427         
2428         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2429                 if ((*i)->name() == name) {
2430                         return false;
2431                 }
2432                 
2433                 if ((*i)->has_io_processor_named (name)) {
2434                         return false;
2435                 }
2436         }
2437         
2438         return true;
2439 }
2440
2441 shared_ptr<Route>
2442 Session::route_by_name (string name)
2443 {
2444         shared_ptr<RouteList> r = routes.reader ();
2445
2446         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2447                 if ((*i)->name() == name) {
2448                         return *i;
2449                 }
2450         }
2451
2452         return shared_ptr<Route> ((Route*) 0);
2453 }
2454
2455 shared_ptr<Route>
2456 Session::route_by_id (PBD::ID id)
2457 {
2458         shared_ptr<RouteList> r = routes.reader ();
2459
2460         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2461                 if ((*i)->id() == id) {
2462                         return *i;
2463                 }
2464         }
2465
2466         return shared_ptr<Route> ((Route*) 0);
2467 }
2468
2469 shared_ptr<Route>
2470 Session::route_by_remote_id (uint32_t id)
2471 {
2472         shared_ptr<RouteList> r = routes.reader ();
2473
2474         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2475                 if ((*i)->remote_control_id() == id) {
2476                         return *i;
2477                 }
2478         }
2479
2480         return shared_ptr<Route> ((Route*) 0);
2481 }
2482
2483 void
2484 Session::find_current_end ()
2485 {
2486         if (_state_of_the_state & Loading) {
2487                 return;
2488         }
2489
2490         nframes_t max = get_maximum_extent ();
2491
2492         if (max > _session_range_location->end()) {
2493                 _session_range_location->set_end (max);
2494                 set_dirty();
2495                 DurationChanged(); /* EMIT SIGNAL */
2496         }
2497 }
2498
2499 nframes_t
2500 Session::get_maximum_extent () const
2501 {
2502         nframes_t max = 0;
2503         nframes_t me;
2504         
2505         boost::shared_ptr<RouteList> rl = routes.reader ();
2506         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2507                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2508                 if (!tr || tr->destructive()) {
2509                         //ignore tape tracks when getting max extents
2510                         continue;
2511                 }
2512                 
2513                 boost::shared_ptr<Playlist> pl = tr->playlist();
2514                 if ((me = pl->get_maximum_extent()) > max) {
2515                         max = me;
2516                 }
2517         }
2518
2519         return max;
2520 }
2521
2522 /* Region management */
2523
2524 boost::shared_ptr<Region>
2525 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2526 {
2527         const RegionFactory::RegionMap& regions (RegionFactory::regions());
2528         RegionFactory::RegionMap::const_iterator i;
2529         boost::shared_ptr<Region> region;
2530
2531         Glib::Mutex::Lock lm (region_lock);
2532
2533         for (i = regions.begin(); i != regions.end(); ++i) {
2534
2535                 region = i->second;
2536
2537                 if (region->whole_file()) {
2538
2539                         if (child->source_equivalent (region)) {
2540                                 return region;
2541                         }
2542                 }
2543         }
2544
2545         return boost::shared_ptr<Region> ();
2546 }
2547
2548 int
2549 Session::destroy_region (boost::shared_ptr<Region> region)
2550 {
2551         vector<boost::shared_ptr<Source> > srcs;
2552
2553         {
2554                 if (region->playlist()) {
2555                         region->playlist()->destroy_region (region);
2556                 }
2557
2558                 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2559                         srcs.push_back (region->source (n));
2560                 }
2561         }
2562
2563         region->drop_references ();
2564
2565         for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2566
2567                 (*i)->mark_for_remove ();
2568                 (*i)->drop_references ();
2569                 
2570                 cerr << "source was not used by any playlist\n";
2571         }
2572
2573         return 0;
2574 }
2575
2576 int
2577 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2578 {
2579         for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2580                 destroy_region (*i);
2581         }
2582         return 0;
2583 }
2584
2585 int
2586 Session::remove_last_capture ()
2587 {
2588         list<boost::shared_ptr<Region> > r;
2589
2590         boost::shared_ptr<RouteList> rl = routes.reader ();
2591         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2592                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2593                 if (!tr) {
2594                         continue;
2595                 }
2596                 
2597                 list<boost::shared_ptr<Region> >& l = tr->last_capture_regions();
2598
2599                 if (!l.empty()) {
2600                         r.insert (r.end(), l.begin(), l.end());
2601                         l.clear ();
2602                 }
2603         }
2604
2605         destroy_regions (r);
2606
2607         save_state (_current_snapshot_name);
2608
2609         return 0;
2610 }
2611
2612 /* Source Management */
2613
2614 void
2615 Session::add_source (boost::shared_ptr<Source> source)
2616 {
2617         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2618         pair<SourceMap::iterator,bool> result;
2619
2620         entry.first = source->id();
2621         entry.second = source;
2622
2623         {
2624                 Glib::Mutex::Lock lm (source_lock);
2625                 result = sources.insert (entry);
2626         }
2627
2628         if (result.second) {
2629                 set_dirty();
2630         }
2631
2632         boost::shared_ptr<AudioFileSource> afs;
2633
2634         if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2635                 if (Config->get_auto_analyse_audio()) {
2636                         Analyser::queue_source_for_analysis (source, false);
2637                 }
2638         }
2639 }
2640
2641 void
2642 Session::remove_source (boost::weak_ptr<Source> src)
2643 {
2644         SourceMap::iterator i;
2645         boost::shared_ptr<Source> source = src.lock();
2646
2647         if (!source) {
2648                 return;
2649         }
2650
2651         {
2652                 Glib::Mutex::Lock lm (source_lock);
2653
2654                 if ((i = sources.find (source->id())) != sources.end()) {
2655                         sources.erase (i);
2656                 }
2657         }
2658
2659         if (!_state_of_the_state & InCleanup) {
2660
2661                 /* save state so we don't end up with a session file
2662                    referring to non-existent sources.
2663                 */
2664
2665                 save_state (_current_snapshot_name);
2666         }
2667 }
2668
2669 boost::shared_ptr<Source>
2670 Session::source_by_id (const PBD::ID& id)
2671 {
2672         Glib::Mutex::Lock lm (source_lock);
2673         SourceMap::iterator i;
2674         boost::shared_ptr<Source> source;
2675
2676         if ((i = sources.find (id)) != sources.end()) {
2677                 source = i->second;
2678         }
2679
2680         return source;
2681 }
2682
2683 boost::shared_ptr<Source>
2684 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2685 {
2686         Glib::Mutex::Lock lm (source_lock);
2687
2688         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2689                 cerr << "comparing " << path << " with " << i->second->name() << endl;
2690                 boost::shared_ptr<AudioFileSource> afs
2691                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2692
2693                 if (afs && afs->path() == path && chn == afs->channel()) {
2694                         return afs;
2695                 }
2696         }
2697         return boost::shared_ptr<Source>();
2698 }
2699
2700
2701 string
2702 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2703 {
2704         string look_for;
2705         string old_basename = PBD::basename_nosuffix (oldname);
2706         string new_legalized = legalize_for_path (newname);
2707
2708         /* note: we know (or assume) the old path is already valid */
2709
2710         if (destructive) {
2711
2712                 /* destructive file sources have a name of the form:
2713
2714                     /path/to/Tnnnn-NAME(%[LR])?.wav
2715
2716                     the task here is to replace NAME with the new name.
2717                 */
2718
2719                 /* find last slash */
2720
2721                 string dir;
2722                 string prefix;
2723                 string::size_type slash;
2724                 string::size_type dash;
2725
2726                 if ((slash = path.find_last_of ('/')) == string::npos) {
2727                         return "";
2728                 }
2729
2730                 dir = path.substr (0, slash+1);
2731
2732                 /* '-' is not a legal character for the NAME part of the path */
2733
2734                 if ((dash = path.find_last_of ('-')) == string::npos) {
2735                         return "";
2736                 }
2737
2738                 prefix = path.substr (slash+1, dash-(slash+1));
2739
2740                 path = dir;
2741                 path += prefix;
2742                 path += '-';
2743                 path += new_legalized;
2744                 path += ".wav";  /* XXX gag me with a spoon */
2745
2746         } else {
2747
2748                 /* non-destructive file sources have a name of the form:
2749
2750                     /path/to/NAME-nnnnn(%[LR])?.ext
2751
2752                     the task here is to replace NAME with the new name.
2753                 */
2754
2755                 string dir;
2756                 string suffix;
2757                 string::size_type slash;
2758                 string::size_type dash;
2759                 string::size_type postfix;
2760
2761                 /* find last slash */
2762
2763                 if ((slash = path.find_last_of ('/')) == string::npos) {
2764                         return "";
2765                 }
2766
2767                 dir = path.substr (0, slash+1);
2768
2769                 /* '-' is not a legal character for the NAME part of the path */
2770
2771                 if ((dash = path.find_last_of ('-')) == string::npos) {
2772                         return "";
2773                 }
2774
2775                 suffix = path.substr (dash+1);
2776
2777                 // Suffix is now everything after the dash. Now we need to eliminate
2778                 // the nnnnn part, which is done by either finding a '%' or a '.'
2779
2780                 postfix = suffix.find_last_of ("%");
2781                 if (postfix == string::npos) {
2782                         postfix = suffix.find_last_of ('.');
2783                 }
2784
2785                 if (postfix != string::npos) {
2786                         suffix = suffix.substr (postfix);
2787                 } else {
2788                         error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2789                         return "";
2790                 }
2791
2792                 const uint32_t limit = 10000;
2793                 char buf[PATH_MAX+1];
2794
2795                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2796
2797                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2798
2799                         if (access (buf, F_OK) != 0) {
2800                                 path = buf;
2801                                 break;
2802                         }
2803                         path = "";
2804                 }
2805
2806                 if (path == "") {
2807                         error << "FATAL ERROR! Could not find a " << endl;
2808                 }
2809
2810         }
2811
2812         return path;
2813 }
2814
2815 /** Return the full path (in some session directory) for a new within-session source.
2816  * \a name must be a session-unique name that does not contain slashes
2817  *         (e.g. as returned by new_*_source_name)
2818  */
2819 string
2820 Session::new_source_path_from_name (DataType type, const string& name)
2821 {
2822         assert(name.find("/") == string::npos);
2823
2824         SessionDirectory sdir(get_best_session_directory_for_new_source());
2825
2826         sys::path p;
2827         if (type == DataType::AUDIO) {
2828                 p = sdir.sound_path();
2829         } else if (type == DataType::MIDI) {
2830                 p = sdir.midi_path();
2831         } else {
2832                 error << "Unknown source type, unable to create file path" << endmsg;
2833                 return "";
2834         }
2835
2836         p /= name;
2837         return p.to_string();
2838 }
2839
2840 Glib::ustring
2841 Session::peak_path (Glib::ustring base) const
2842 {
2843         sys::path peakfile_path(_session_dir->peak_path());
2844         peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2845         return peakfile_path.to_string();
2846 }
2847
2848 /** Return a unique name based on \a base for a new internal audio source */
2849 string
2850 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
2851 {
2852         string spath;
2853         uint32_t cnt;
2854         char buf[PATH_MAX+1];
2855         const uint32_t limit = 10000;
2856         string legalized;
2857
2858         buf[0] = '\0';
2859         legalized = legalize_for_path (base);
2860
2861         // Find a "version" of the base name that doesn't exist in any of the possible directories.
2862         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2863
2864                 vector<space_and_path>::iterator i;
2865                 uint32_t existing = 0;
2866
2867                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2868
2869                         SessionDirectory sdir((*i).path);
2870
2871                         spath = sdir.sound_path().to_string();
2872
2873                         if (destructive) {
2874
2875                                 if (nchan < 2) {
2876                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2877                                                         spath.c_str(), cnt, legalized.c_str());
2878                                 } else if (nchan == 2) {
2879                                         if (chan == 0) {
2880                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
2881                                                                 spath.c_str(), cnt, legalized.c_str());
2882                                         } else {
2883                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
2884                                                                 spath.c_str(), cnt, legalized.c_str());
2885                                         }
2886                                 } else if (nchan < 26) {
2887                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
2888                                                         spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2889                                 } else {
2890                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2891                                                         spath.c_str(), cnt, legalized.c_str());
2892                                 }
2893
2894                         } else {
2895
2896                                 spath += '/';
2897                                 spath += legalized;
2898
2899                                 if (nchan < 2) {
2900                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2901                                 } else if (nchan == 2) {
2902                                         if (chan == 0) {
2903                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2904                                         } else {
2905                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2906                                         }
2907                                 } else if (nchan < 26) {
2908                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2909                                 } else {
2910                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2911                                 }
2912                         }
2913
2914                         if (sys::exists(buf)) {
2915                                 existing++;
2916                         }
2917
2918                 }
2919
2920                 if (existing == 0) {
2921                         break;
2922                 }
2923
2924                 if (cnt > limit) {
2925                         error << string_compose(
2926                                         _("There are already %1 recordings for %2, which I consider too many."),
2927                                         limit, base) << endmsg;
2928                         destroy ();
2929                         throw failed_constructor();
2930                 }
2931         }
2932
2933         return Glib::path_get_basename(buf);
2934 }
2935
2936 /** Create a new within-session audio source */
2937 boost::shared_ptr<AudioFileSource>
2938 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive)
2939 {
2940         const string name    = new_audio_source_name (n, n_chans, chan, destructive);
2941         const string path    = new_source_path_from_name(DataType::AUDIO, name);
2942
2943         return boost::dynamic_pointer_cast<AudioFileSource> (
2944                 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
2945 }
2946
2947 /** Return a unique name based on \a base for a new internal MIDI source */
2948 string
2949 Session::new_midi_source_name (const string& base)
2950 {
2951         uint32_t cnt;
2952         char buf[PATH_MAX+1];
2953         const uint32_t limit = 10000;
2954         string legalized;
2955
2956         buf[0] = '\0';
2957         legalized = legalize_for_path (base);
2958
2959         // Find a "version" of the file name that doesn't exist in any of the possible directories.
2960         for (cnt = 1; cnt <= limit; ++cnt) {
2961
2962                 vector<space_and_path>::iterator i;
2963                 uint32_t existing = 0;
2964
2965                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2966
2967                         SessionDirectory sdir((*i).path);
2968
2969                         sys::path p = sdir.midi_path();
2970                         p /= legalized;
2971
2972                         snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
2973
2974                         if (sys::exists (buf)) {
2975                                 existing++;
2976                         }
2977                 }
2978
2979                 if (existing == 0) {
2980                         break;
2981                 }
2982
2983                 if (cnt > limit) {
2984                         error << string_compose(
2985                                         _("There are already %1 recordings for %2, which I consider too many."),
2986                                         limit, base) << endmsg;
2987                         destroy ();
2988                         throw failed_constructor();
2989                 }
2990         }
2991
2992         return Glib::path_get_basename(buf);
2993 }
2994
2995
2996 /** Create a new within-session MIDI source */
2997 boost::shared_ptr<MidiSource>
2998 Session::create_midi_source_for_session (string const & n)
2999 {
3000         const string name = new_midi_source_name (n);
3001         const string path = new_source_path_from_name (DataType::MIDI, name);
3002
3003         return boost::dynamic_pointer_cast<SMFSource> (
3004                         SourceFactory::createWritable (
3005                                         DataType::MIDI, *this, path, false, frame_rate()));
3006 }
3007
3008
3009 void
3010 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3011 {
3012         if (playlist->hidden()) {
3013                 return;
3014         }
3015
3016         playlists->add (playlist);
3017
3018         if (unused) {
3019                 playlist->release();
3020         }
3021
3022         set_dirty();
3023 }
3024
3025 void
3026 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3027 {
3028         if (_state_of_the_state & Deletion) {
3029                 return;
3030         }
3031
3032         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3033
3034         if (!playlist) {
3035                 return;
3036         }
3037
3038         playlists->remove (playlist);
3039
3040         set_dirty();
3041 }
3042
3043 void
3044 Session::set_audition (boost::shared_ptr<Region> r)
3045 {
3046         pending_audition_region = r;
3047         add_post_transport_work (PostTransportAudition);
3048         _butler->schedule_transport_work ();
3049 }
3050
3051 void
3052 Session::audition_playlist ()
3053 {
3054         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3055         ev->region.reset ();
3056         queue_event (ev);
3057 }
3058
3059 void
3060 Session::non_realtime_set_audition ()
3061 {
3062         if (!pending_audition_region) {
3063                 auditioner->audition_current_playlist ();
3064         } else {
3065                 auditioner->audition_region (pending_audition_region);
3066                 pending_audition_region.reset ();
3067         }
3068         AuditionActive (true); /* EMIT SIGNAL */
3069 }
3070
3071 void
3072 Session::audition_region (boost::shared_ptr<Region> r)
3073 {
3074         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3075         ev->region = r;
3076         queue_event (ev);
3077 }
3078
3079 void
3080 Session::cancel_audition ()
3081 {
3082         if (auditioner->auditioning()) {
3083                 auditioner->cancel_audition ();
3084                 AuditionActive (false); /* EMIT SIGNAL */
3085         }
3086 }
3087
3088 bool
3089 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3090 {
3091         if (a->is_monitor()) { 
3092                 return true;
3093         }
3094         if (b->is_monitor()) {
3095                 return false;
3096         }
3097         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3098 }
3099
3100 void
3101 Session::remove_empty_sounds ()
3102 {
3103         vector<string> audio_filenames;
3104
3105         get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3106
3107         Glib::Mutex::Lock lm (source_lock);
3108
3109         TapeFileMatcher tape_file_matcher;
3110
3111         remove_if (audio_filenames.begin(), audio_filenames.end(),
3112                    boost::bind (&TapeFileMatcher::matches, &tape_file_matcher, _1));
3113         
3114         for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3115
3116                 sys::path audio_file_path (_session_dir->sound_path());
3117
3118                 audio_file_path /= *i;
3119
3120                 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3121
3122                         try
3123                         {
3124                                 sys::remove (audio_file_path);
3125                                 const string peakfile = peak_path (audio_file_path.to_string());
3126                                 sys::remove (peakfile);
3127                         }
3128                         catch (const sys::filesystem_error& err)
3129                         {
3130                                 error << err.what() << endmsg;
3131                         }
3132                 }
3133         }
3134 }
3135
3136 bool
3137 Session::is_auditioning () const
3138 {
3139         /* can be called before we have an auditioner object */
3140         if (auditioner) {
3141                 return auditioner->auditioning();
3142         } else {
3143                 return false;
3144         }
3145 }
3146
3147 void
3148 Session::graph_reordered ()
3149 {
3150         /* don't do this stuff if we are setting up connections
3151            from a set_state() call or creating new tracks. Ditto for deletion.
3152         */
3153
3154         if (_state_of_the_state & (InitialConnecting|Deletion)) {
3155                 return;
3156         }
3157
3158         /* every track/bus asked for this to be handled but it was deferred because
3159            we were connecting. do it now.
3160         */
3161
3162         request_input_change_handling ();
3163
3164         resort_routes ();
3165
3166         /* force all diskstreams to update their capture offset values to
3167            reflect any changes in latencies within the graph.
3168         */
3169
3170         boost::shared_ptr<RouteList> rl = routes.reader ();
3171         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3172                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3173                 if (tr) {
3174                         tr->set_capture_offset ();
3175                 }
3176         }
3177 }
3178
3179 nframes_t
3180 Session::available_capture_duration ()
3181 {
3182         float sample_bytes_on_disk = 4.0; // keep gcc happy
3183
3184         switch (config.get_native_file_data_format()) {
3185         case FormatFloat:
3186                 sample_bytes_on_disk = 4.0;
3187                 break;
3188
3189         case FormatInt24:
3190                 sample_bytes_on_disk = 3.0;
3191                 break;
3192
3193         case FormatInt16:
3194                 sample_bytes_on_disk = 2.0;
3195                 break;
3196
3197         default:
3198                 /* impossible, but keep some gcc versions happy */
3199                 fatal << string_compose (_("programming error: %1"),
3200                                          X_("illegal native file data format"))
3201                       << endmsg;
3202                 /*NOTREACHED*/
3203         }
3204
3205         double scale = 4096.0 / sample_bytes_on_disk;
3206
3207         if (_total_free_4k_blocks * scale > (double) max_frames) {
3208                 return max_frames;
3209         }
3210
3211         return (nframes_t) floor (_total_free_4k_blocks * scale);
3212 }
3213
3214 void
3215 Session::add_bundle (shared_ptr<Bundle> bundle)
3216 {
3217         {
3218                 RCUWriter<BundleList> writer (_bundles);
3219                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3220                 b->push_back (bundle);
3221         }
3222
3223         BundleAdded (bundle); /* EMIT SIGNAL */
3224
3225         set_dirty();
3226 }
3227
3228 void
3229 Session::remove_bundle (shared_ptr<Bundle> bundle)
3230 {
3231         bool removed = false;
3232
3233         {
3234                 RCUWriter<BundleList> writer (_bundles);
3235                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3236                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3237
3238                 if (i != b->end()) {
3239                         b->erase (i);
3240                         removed = true;
3241                 }
3242         }
3243
3244         if (removed) {
3245                  BundleRemoved (bundle); /* EMIT SIGNAL */
3246         }
3247
3248         set_dirty();
3249 }
3250
3251 shared_ptr<Bundle>
3252 Session::bundle_by_name (string name) const
3253 {
3254         boost::shared_ptr<BundleList> b = _bundles.reader ();
3255
3256         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3257                 if ((*i)->name() == name) {
3258                         return* i;
3259                 }
3260         }
3261
3262         return boost::shared_ptr<Bundle> ();
3263 }
3264
3265 void
3266 Session::tempo_map_changed (const PropertyChange&)
3267 {
3268         clear_clicks ();
3269
3270         playlists->update_after_tempo_map_change ();
3271
3272         set_dirty ();
3273 }
3274
3275 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3276  * the given count with the current block size.
3277  */
3278 void
3279 Session::ensure_buffers (ChanCount howmany)
3280 {
3281         BufferManager::ensure_buffers (howmany);
3282 }
3283
3284 void
3285 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3286 {
3287         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3288                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3289         }
3290 }
3291
3292 uint32_t
3293 Session::next_insert_id ()
3294 {
3295         /* this doesn't really loop forever. just think about it */
3296
3297         while (true) {
3298                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3299                         if (!insert_bitset[n]) {
3300                                 insert_bitset[n] = true;
3301                                 return n;
3302
3303                         }
3304                 }
3305
3306                 /* none available, so resize and try again */
3307
3308                 insert_bitset.resize (insert_bitset.size() + 16, false);
3309         }
3310 }
3311
3312 uint32_t
3313 Session::next_send_id ()
3314 {
3315         /* this doesn't really loop forever. just think about it */
3316
3317         while (true) {
3318                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3319                         if (!send_bitset[n]) {
3320                                 send_bitset[n] = true;
3321                                 return n;
3322
3323                         }
3324                 }
3325
3326                 /* none available, so resize and try again */
3327
3328                 send_bitset.resize (send_bitset.size() + 16, false);
3329         }
3330 }
3331
3332 uint32_t
3333 Session::next_return_id ()
3334 {
3335         /* this doesn't really loop forever. just think about it */
3336
3337         while (true) {
3338                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3339                         if (!return_bitset[n]) {
3340                                 return_bitset[n] = true;
3341                                 return n;
3342
3343                         }
3344                 }
3345
3346                 /* none available, so resize and try again */
3347
3348                 return_bitset.resize (return_bitset.size() + 16, false);
3349         }
3350 }
3351
3352 void
3353 Session::mark_send_id (uint32_t id)
3354 {
3355         if (id >= send_bitset.size()) {
3356                 send_bitset.resize (id+16, false);
3357         }
3358         if (send_bitset[id]) {
3359                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3360         }
3361         send_bitset[id] = true;
3362 }
3363
3364 void
3365 Session::mark_return_id (uint32_t id)
3366 {
3367         if (id >= return_bitset.size()) {
3368                 return_bitset.resize (id+16, false);
3369         }
3370         if (return_bitset[id]) {
3371                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3372         }
3373         return_bitset[id] = true;
3374 }
3375
3376 void
3377 Session::mark_insert_id (uint32_t id)
3378 {
3379         if (id >= insert_bitset.size()) {
3380                 insert_bitset.resize (id+16, false);
3381         }
3382         if (insert_bitset[id]) {
3383                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3384         }
3385         insert_bitset[id] = true;
3386 }
3387
3388 void
3389 Session::unmark_send_id (uint32_t id)
3390 {
3391         if (id < send_bitset.size()) {
3392                 send_bitset[id] = false;
3393         }
3394 }
3395
3396 void
3397 Session::unmark_return_id (uint32_t id)
3398 {
3399         if (id < return_bitset.size()) {
3400                 return_bitset[id] = false;
3401         }
3402 }
3403
3404 void
3405 Session::unmark_insert_id (uint32_t id)
3406 {
3407         if (id < insert_bitset.size()) {
3408                 insert_bitset[id] = false;
3409         }
3410 }
3411
3412
3413 /* Named Selection management */
3414
3415 boost::shared_ptr<NamedSelection>
3416 Session::named_selection_by_name (string name)
3417 {
3418         Glib::Mutex::Lock lm (named_selection_lock);
3419         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3420                 if ((*i)->name == name) {
3421                         return *i;
3422                 }
3423         }
3424         return boost::shared_ptr<NamedSelection>();
3425 }
3426
3427 void
3428 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3429 {
3430         {
3431                 Glib::Mutex::Lock lm (named_selection_lock);
3432                 named_selections.insert (named_selections.begin(), named_selection);
3433         }
3434
3435         set_dirty();
3436
3437         NamedSelectionAdded (); /* EMIT SIGNAL */
3438 }
3439
3440 void
3441 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3442 {
3443         bool removed = false;
3444
3445         {
3446                 Glib::Mutex::Lock lm (named_selection_lock);
3447
3448                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3449
3450                 if (i != named_selections.end()) {
3451                         named_selections.erase (i);
3452                         set_dirty();
3453                         removed = true;
3454                 }
3455         }
3456
3457         if (removed) {
3458                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3459         }
3460 }
3461
3462 void
3463 Session::reset_native_file_format ()
3464 {
3465         boost::shared_ptr<RouteList> rl = routes.reader ();
3466         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3467                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3468                 if (tr) {
3469                         tr->reset_write_sources (false);
3470                 }
3471         }
3472 }
3473
3474 bool
3475 Session::route_name_unique (string n) const
3476 {
3477         shared_ptr<RouteList> r = routes.reader ();
3478
3479         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3480                 if ((*i)->name() == n) {
3481                         return false;
3482                 }
3483         }
3484
3485         return true;
3486 }
3487
3488 bool
3489 Session::route_name_internal (string n) const
3490 {
3491         if (auditioner && auditioner->name() == n) {
3492                 return true;
3493         }
3494
3495         if (_click_io && _click_io->name() == n) {
3496                 return true;
3497         }
3498
3499         return false;
3500 }
3501
3502 int
3503 Session::freeze_all (InterThreadInfo& itt)
3504 {
3505         shared_ptr<RouteList> r = routes.reader ();
3506
3507         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3508
3509                 boost::shared_ptr<Track> t;
3510
3511                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3512                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3513                            of every track.
3514                         */
3515                         t->freeze_me (itt);
3516                 }
3517         }
3518
3519         return 0;
3520 }
3521
3522 boost::shared_ptr<Region>
3523 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3524                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3525                           InterThreadInfo& itt, bool enable_processing)
3526 {
3527         boost::shared_ptr<Region> result;
3528         boost::shared_ptr<Playlist> playlist;
3529         boost::shared_ptr<AudioFileSource> fsource;
3530         uint32_t x;
3531         char buf[PATH_MAX+1];
3532         ChanCount nchans(track.n_channels());
3533         nframes_t position;
3534         nframes_t this_chunk;
3535         nframes_t to_do;
3536         BufferSet buffers;
3537         SessionDirectory sdir(get_best_session_directory_for_new_source ());
3538         const string sound_dir = sdir.sound_path().to_string();
3539         nframes_t len = end - start;
3540
3541         if (end <= start) {
3542                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3543                                          end, start) << endmsg;
3544                 return result;
3545         }
3546
3547         const nframes_t chunk_size = (256 * 1024)/4;
3548
3549         // block all process callback handling
3550
3551         block_processing ();
3552
3553         /* call tree *MUST* hold route_lock */
3554
3555         if ((playlist = track.playlist()) == 0) {
3556                 goto out;
3557         }
3558
3559         /* external redirects will be a problem */
3560
3561         if (track.has_external_redirects()) {
3562                 goto out;
3563         }
3564
3565         for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3566
3567                 for (x = 0; x < 99999; ++x) {
3568                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3569                         if (access (buf, F_OK) != 0) {
3570                                 break;
3571                         }
3572                 }
3573
3574                 if (x == 99999) {
3575                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3576                         goto out;
3577                 }
3578
3579                 try {
3580                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3581                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3582                 }
3583
3584                 catch (failed_constructor& err) {
3585                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3586                         goto out;
3587                 }
3588
3589                 srcs.push_back (fsource);
3590         }
3591
3592         /* XXX need to flush all redirects */
3593
3594         position = start;
3595         to_do = len;
3596
3597         /* create a set of reasonably-sized buffers */
3598         buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3599         buffers.set_count(nchans);
3600
3601         for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3602                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3603                 if (afs)
3604                         afs->prepare_for_peakfile_writes ();
3605         }
3606
3607         while (to_do && !itt.cancel) {
3608
3609                 this_chunk = min (to_do, chunk_size);
3610
3611                 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3612                         goto out;
3613                 }
3614
3615                 uint32_t n = 0;
3616                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3617                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3618
3619                         if (afs) {
3620                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3621                                         goto out;
3622                                 }
3623                         }
3624                 }
3625
3626                 start += this_chunk;
3627                 to_do -= this_chunk;
3628
3629                 itt.progress = (float) (1.0 - ((double) to_do / len));
3630
3631         }
3632
3633         if (!itt.cancel) {
3634
3635                 time_t now;
3636                 struct tm* xnow;
3637                 time (&now);
3638                 xnow = localtime (&now);
3639
3640                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3641                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3642
3643                         if (afs) {
3644                                 afs->update_header (position, *xnow, now);
3645                                 afs->flush_header ();
3646                         }
3647                 }
3648
3649                 /* construct a region to represent the bounced material */
3650
3651                 PropertyList plist;
3652                 
3653                 plist.add (Properties::start, 0);
3654                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3655                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3656                 
3657                 result = RegionFactory::create (srcs, plist);
3658                            
3659         }
3660
3661   out:
3662         if (!result) {
3663                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3664                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3665
3666                         if (afs) {
3667                                 afs->mark_for_remove ();
3668                         }
3669
3670                         (*src)->drop_references ();
3671                 }
3672
3673         } else {
3674                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3675                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3676
3677                         if (afs)
3678                                 afs->done_with_peakfile_writes ();
3679                 }
3680         }
3681
3682         unblock_processing ();
3683
3684         return result;
3685 }
3686
3687 gain_t*
3688 Session::gain_automation_buffer() const
3689 {
3690         return ProcessThread::gain_automation_buffer ();
3691 }
3692
3693 pan_t**
3694 Session::pan_automation_buffer() const
3695 {
3696         return ProcessThread::pan_automation_buffer ();
3697 }
3698
3699 BufferSet&
3700 Session::get_silent_buffers (ChanCount count)
3701 {
3702         return ProcessThread::get_silent_buffers (count);
3703 #if 0
3704         assert(_silent_buffers->available() >= count);
3705         _silent_buffers->set_count(count);
3706
3707         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3708                 for (size_t i= 0; i < count.get(*t); ++i) {
3709                         _silent_buffers->get(*t, i).clear();
3710                 }
3711         }
3712
3713         return *_silent_buffers;
3714 #endif
3715 }
3716
3717 BufferSet&
3718 Session::get_scratch_buffers (ChanCount count)
3719 {
3720         return ProcessThread::get_scratch_buffers (count);
3721 #if 0
3722         if (count != ChanCount::ZERO) {
3723                 assert(_scratch_buffers->available() >= count);
3724                 _scratch_buffers->set_count(count);
3725         } else {
3726                 _scratch_buffers->set_count (_scratch_buffers->available());
3727         }
3728
3729         return *_scratch_buffers;
3730 #endif
3731 }
3732
3733 BufferSet&
3734 Session::get_mix_buffers (ChanCount count)
3735 {
3736         return ProcessThread::get_mix_buffers (count);
3737 #if 0
3738         assert(_mix_buffers->available() >= count);
3739         _mix_buffers->set_count(count);
3740         return *_mix_buffers;
3741 #endif
3742 }
3743
3744 uint32_t
3745 Session::ntracks () const
3746 {
3747         uint32_t n = 0;
3748         shared_ptr<RouteList> r = routes.reader ();
3749
3750         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3751                 if (boost::dynamic_pointer_cast<Track> (*i)) {
3752                         ++n;
3753                 }
3754         }
3755
3756         return n;
3757 }
3758
3759 uint32_t
3760 Session::nbusses () const
3761 {
3762         uint32_t n = 0;
3763         shared_ptr<RouteList> r = routes.reader ();
3764
3765         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3766                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3767                         ++n;
3768                 }
3769         }
3770
3771         return n;
3772 }
3773
3774 void
3775 Session::add_automation_list(AutomationList *al)
3776 {
3777         automation_lists[al->id()] = al;
3778 }
3779
3780 nframes_t
3781 Session::compute_initial_length ()
3782 {
3783         return _engine.frame_rate() * 60 * 5;
3784 }
3785
3786 void
3787 Session::sync_order_keys (std::string const & base)
3788 {
3789         if (deletion_in_progress()) {
3790                 return;
3791         }
3792
3793         if (!Config->get_sync_all_route_ordering()) {
3794                 /* leave order keys as they are */
3795                 return;
3796         }
3797
3798         boost::shared_ptr<RouteList> r = routes.reader ();
3799
3800         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3801                 (*i)->sync_order_keys (base);
3802         }
3803
3804         Route::SyncOrderKeys (base); // EMIT SIGNAL
3805
3806         /* this might not do anything */
3807
3808         set_remote_control_ids ();
3809 }
3810
3811 /** @return true if there is at least one record-enabled track, otherwise false */
3812 bool
3813 Session::have_rec_enabled_track () const
3814 {
3815         return g_atomic_int_get (&_have_rec_enabled_track) == 1;
3816 }
3817
3818 /** Update the state of our rec-enabled tracks flag */
3819 void
3820 Session::update_have_rec_enabled_track ()
3821 {
3822         boost::shared_ptr<RouteList> rl = routes.reader ();
3823         RouteList::iterator i = rl->begin();
3824         while (i != rl->end ()) {
3825
3826                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3827                 if (tr && tr->record_enabled ()) {
3828                         break;
3829                 }
3830                 
3831                 ++i;
3832         }
3833
3834         int const old = g_atomic_int_get (&_have_rec_enabled_track);
3835
3836         g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
3837
3838         if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
3839                 RecordStateChanged (); /* EMIT SIGNAL */
3840         }
3841 }
3842
3843 void
3844 Session::listen_position_changed ()
3845 {
3846         Placement p;
3847
3848         switch (Config->get_listen_position()) {
3849         case AfterFaderListen:
3850                 p = PostFader;
3851                 break;
3852
3853         case PreFaderListen:
3854                 p = PreFader;
3855                 break;
3856         }
3857
3858         boost::shared_ptr<RouteList> r = routes.reader ();
3859
3860         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3861                 (*i)->put_monitor_send_at (p);
3862         }
3863 }
3864
3865 void
3866 Session::solo_control_mode_changed ()
3867 {
3868         /* cancel all solo or all listen when solo control mode changes */
3869
3870         if (soloing()) {
3871                 set_solo (get_routes(), false);
3872         } else if (listening()) {
3873                 set_listen (get_routes(), false);
3874         }
3875 }
3876
3877 void
3878 Session::route_group_changed ()
3879 {
3880         RouteGroupChanged (); /* EMIT SIGNAL */
3881 }
3882
3883 vector<SyncSource>
3884 Session::get_available_sync_options () const
3885 {
3886         vector<SyncSource> ret;
3887         
3888         ret.push_back (JACK);
3889
3890         if (mtc_port()) {
3891                 ret.push_back (MTC);
3892         } 
3893
3894         if (midi_clock_port()) {
3895                 ret.push_back (MIDIClock);
3896         } 
3897
3898         return ret;
3899 }
3900
3901 boost::shared_ptr<RouteList>
3902 Session::get_routes_with_regions_at (nframes64_t const p) const
3903 {
3904         shared_ptr<RouteList> r = routes.reader ();
3905         shared_ptr<RouteList> rl (new RouteList);
3906
3907         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3908                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3909                 if (!tr) {
3910                         continue;
3911                 }
3912                 
3913                 boost::shared_ptr<Playlist> pl = tr->playlist ();
3914                 if (!pl) {
3915                         continue;
3916                 }
3917                 
3918                 if (pl->has_region_at (p)) {
3919                         rl->push_back (*i);
3920                 }
3921         }
3922
3923         return rl;
3924 }