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