Make the session start/end location a single location (with start and end) rather...
[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 session_range_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 session_range_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_session_range()) {
958                         _session_range_location = location;
959                 }
960         }
961
962         if (!set_loop) {
963                 set_auto_loop_location (0);
964         }
965         if (!set_punch) {
966                 set_auto_punch_location (0);
967         }
968
969         set_dirty();
970 }
971
972 void
973 Session::enable_record ()
974 {
975         /* XXX really atomic compare+swap here */
976         if (g_atomic_int_get (&_record_status) != Recording) {
977                 g_atomic_int_set (&_record_status, Recording);
978                 _last_record_location = _transport_frame;
979                 deliver_mmc(MIDI::MachineControl::cmdRecordStrobe, _last_record_location);
980
981                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
982                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
983                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
984                                 if ((*i)->record_enabled ()) {
985                                         (*i)->monitor_input (true);
986                                 }
987                         }
988                 }
989
990                 RecordStateChanged ();
991         }
992 }
993
994 void
995 Session::disable_record (bool rt_context, bool force)
996 {
997         RecordState rs;
998
999         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1000
1001                 if ((!Config->get_latched_record_enable () && !play_loop) || force) {
1002                         g_atomic_int_set (&_record_status, Disabled);
1003                 } else {
1004                         if (rs == Recording) {
1005                                 g_atomic_int_set (&_record_status, Enabled);
1006                         }
1007                 }
1008
1009                 // FIXME: timestamp correct? [DR]
1010                 // FIXME FIXME FIXME: rt_context?  this must be called in the process thread.
1011                 // does this /need/ to be sent in all cases?
1012                 if (rt_context) {
1013                         deliver_mmc (MIDI::MachineControl::cmdRecordExit, _transport_frame);
1014                 }
1015
1016                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1017                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1018
1019                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1020                                 if ((*i)->record_enabled ()) {
1021                                         (*i)->monitor_input (false);
1022                                 }
1023                         }
1024                 }
1025
1026                 RecordStateChanged (); /* emit signal */
1027
1028                 if (!rt_context) {
1029                         remove_pending_capture_state ();
1030                 }
1031         }
1032 }
1033
1034 void
1035 Session::step_back_from_record ()
1036 {
1037         if (g_atomic_int_compare_and_exchange (&_record_status, Recording, Enabled)) {
1038
1039                 if (Config->get_monitoring_model() == HardwareMonitoring && config.get_auto_input()) {
1040                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1041
1042                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1043                                 if ((*i)->record_enabled ()) {
1044                                         //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1045                                         (*i)->monitor_input (false);
1046                                 }
1047                         }
1048                 }
1049         }
1050 }
1051
1052 void
1053 Session::maybe_enable_record ()
1054 {
1055         g_atomic_int_set (&_record_status, Enabled);
1056
1057         /* this function is currently called from somewhere other than an RT thread.
1058            this save_state() call therefore doesn't impact anything.
1059         */
1060
1061         save_state ("", true);
1062
1063         if (_transport_speed) {
1064                 if (!config.get_punch_in()) {
1065                         enable_record ();
1066                 }
1067         } else {
1068                 deliver_mmc (MIDI::MachineControl::cmdRecordPause, _transport_frame);
1069                 RecordStateChanged (); /* EMIT SIGNAL */
1070         }
1071
1072         set_dirty();
1073 }
1074
1075 nframes64_t
1076 Session::audible_frame () const
1077 {
1078         nframes64_t ret;
1079         nframes64_t tf;
1080         nframes_t offset;
1081
1082         /* the first of these two possible settings for "offset"
1083            mean that the audible frame is stationary until
1084            audio emerges from the latency compensation
1085            "pseudo-pipeline".
1086
1087            the second means that the audible frame is stationary
1088            until audio would emerge from a physical port
1089            in the absence of any plugin latency compensation
1090         */
1091
1092         offset = _worst_output_latency;
1093
1094         if (offset > current_block_size) {
1095                 offset -= current_block_size;
1096         } else {
1097                 /* XXX is this correct? if we have no external
1098                    physical connections and everything is internal
1099                    then surely this is zero? still, how
1100                    likely is that anyway?
1101                 */
1102                 offset = current_block_size;
1103         }
1104
1105         if (synced_to_jack()) {
1106                 tf = _engine.transport_frame();
1107         } else {
1108                 tf = _transport_frame;
1109         }
1110
1111         ret = tf;
1112
1113         if (!non_realtime_work_pending()) {
1114
1115                 /* MOVING */
1116
1117                 /* check to see if we have passed the first guaranteed
1118                    audible frame past our last start position. if not,
1119                    return that last start point because in terms
1120                    of audible frames, we have not moved yet.
1121                 */
1122
1123                 if (_transport_speed > 0.0f) {
1124
1125                         if (!play_loop || !have_looped) {
1126                                 if (tf < _last_roll_location + offset) {
1127                                         return _last_roll_location;
1128                                 }
1129                         }
1130
1131
1132                         /* forwards */
1133                         ret -= offset;
1134
1135                 } else if (_transport_speed < 0.0f) {
1136
1137                         /* XXX wot? no backward looping? */
1138
1139                         if (tf > _last_roll_location - offset) {
1140                                 return _last_roll_location;
1141                         } else {
1142                                 /* backwards */
1143                                 ret += offset;
1144                         }
1145                 }
1146         }
1147
1148         return ret;
1149 }
1150
1151 void
1152 Session::set_frame_rate (nframes_t frames_per_second)
1153 {
1154         /** \fn void Session::set_frame_size(nframes_t)
1155                 the AudioEngine object that calls this guarantees
1156                 that it will not be called while we are also in
1157                 ::process(). Its fine to do things that block
1158                 here.
1159         */
1160
1161         _base_frame_rate = frames_per_second;
1162
1163         sync_time_vars();
1164
1165         Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1166
1167         clear_clicks ();
1168
1169         // XXX we need some equivalent to this, somehow
1170         // SndFileSource::setup_standard_crossfades (frames_per_second);
1171
1172         set_dirty();
1173
1174         /* XXX need to reset/reinstantiate all LADSPA plugins */
1175 }
1176
1177 void
1178 Session::set_block_size (nframes_t nframes)
1179 {
1180         /* the AudioEngine guarantees
1181            that it will not be called while we are also in
1182            ::process(). It is therefore fine to do things that block
1183            here.
1184         */
1185
1186         {
1187                 current_block_size = nframes;
1188
1189                 ensure_buffers ();
1190
1191                 boost::shared_ptr<RouteList> r = routes.reader ();
1192
1193                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1194                         (*i)->set_block_size (nframes);
1195                 }
1196
1197                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
1198                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
1199                         (*i)->set_block_size (nframes);
1200                 }
1201
1202                 set_worst_io_latencies ();
1203         }
1204 }
1205
1206 void
1207 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1208 {
1209 #if 0
1210         nframes_t fade_frames;
1211
1212         /* Don't allow fade of less 1 frame */
1213
1214         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1215
1216                 fade_msecs = 0;
1217                 fade_frames = 0;
1218
1219         } else {
1220
1221                 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1222
1223         }
1224
1225         default_fade_msecs = fade_msecs;
1226         default_fade_steepness = steepness;
1227
1228         {
1229                 // jlc, WTF is this!
1230                 Glib::RWLock::ReaderLock lm (route_lock);
1231                 AudioRegion::set_default_fade (steepness, fade_frames);
1232         }
1233
1234         set_dirty();
1235
1236         /* XXX have to do this at some point */
1237         /* foreach region using default fade, reset, then
1238            refill_all_diskstream_buffers ();
1239         */
1240 #endif
1241 }
1242
1243 struct RouteSorter {
1244     bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1245             if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1246                     return false;
1247             } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1248                     return true;
1249             } else {
1250                     if (r1->fed_by.empty()) {
1251                             if (r2->fed_by.empty()) {
1252                                     /* no ardour-based connections inbound to either route. just use signal order */
1253                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1254                             } else {
1255                                     /* r2 has connections, r1 does not; run r1 early */
1256                                     return true;
1257                             }
1258                     } else {
1259                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1260                     }
1261             }
1262     }
1263 };
1264
1265 static void
1266 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1267 {
1268         shared_ptr<Route> r2;
1269
1270         if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1271                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1272                 return;
1273         }
1274
1275         /* make a copy of the existing list of routes that feed r1 */
1276
1277         set<weak_ptr<Route> > existing = r1->fed_by;
1278
1279         /* for each route that feeds r1, recurse, marking it as feeding
1280            rbase as well.
1281         */
1282
1283         for (set<weak_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1284                 if (!(r2 = (*i).lock ())) {
1285                         /* (*i) went away, ignore it */
1286                         continue;
1287                 }
1288                 
1289                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1290                    base as being fed by r2
1291                 */
1292
1293                 rbase->fed_by.insert (r2);
1294
1295                 if (r2 != rbase) {
1296
1297                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1298                            stop here.
1299                         */
1300
1301                         if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1302                                 continue;
1303                         }
1304
1305                         /* now recurse, so that we can mark base as being fed by
1306                            all routes that feed r2
1307                         */
1308
1309                         trace_terminal (r2, rbase);
1310                 }
1311
1312         }
1313 }
1314
1315 void
1316 Session::resort_routes ()
1317 {
1318         /* don't do anything here with signals emitted
1319            by Routes while we are being destroyed.
1320         */
1321
1322         if (_state_of_the_state & Deletion) {
1323                 return;
1324         }
1325
1326
1327         {
1328
1329                 RCUWriter<RouteList> writer (routes);
1330                 shared_ptr<RouteList> r = writer.get_copy ();
1331                 resort_routes_using (r);
1332                 /* writer goes out of scope and forces update */
1333         }
1334
1335 }
1336 void
1337 Session::resort_routes_using (shared_ptr<RouteList> r)
1338 {
1339         RouteList::iterator i, j;
1340
1341         for (i = r->begin(); i != r->end(); ++i) {
1342
1343                 (*i)->fed_by.clear ();
1344
1345                 for (j = r->begin(); j != r->end(); ++j) {
1346
1347                         /* although routes can feed themselves, it will
1348                            cause an endless recursive descent if we
1349                            detect it. so don't bother checking for
1350                            self-feeding.
1351                         */
1352
1353                         if (*j == *i) {
1354                                 continue;
1355                         }
1356
1357                         if ((*j)->feeds (*i)) {
1358                                 (*i)->fed_by.insert (*j);
1359                         }
1360                 }
1361         }
1362
1363         for (i = r->begin(); i != r->end(); ++i) {
1364                 trace_terminal (*i, *i);
1365         }
1366
1367         RouteSorter cmp;
1368         r->sort (cmp);
1369
1370 #if 0
1371         cerr << "finished route resort\n";
1372
1373         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1374                 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1375         }
1376         cerr << endl;
1377 #endif
1378
1379 }
1380
1381 /** Find the route name starting with \a base with the lowest \a id.
1382  *
1383  * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1384  * The available route name with the lowest ID will be used, and \a id
1385  * will be set to the ID.
1386  *
1387  * \return false if a route name could not be found, and \a track_name
1388  * and \a id do not reflect a free route name.
1389  */
1390 bool
1391 Session::find_route_name (const char* base, uint32_t& id, char* name, size_t name_len)
1392 {
1393         do {
1394                 snprintf (name, name_len, "%s %" PRIu32, base, id);
1395
1396                 if (route_by_name (name) == 0) {
1397                         return true;
1398                 }
1399
1400                 ++id;
1401
1402         } while (id < (UINT_MAX-1));
1403
1404         return false;
1405 }
1406
1407 void
1408 Session::count_existing_route_channels (ChanCount& in, ChanCount& out)
1409 {
1410         in  = ChanCount::ZERO;
1411         out = ChanCount::ZERO;
1412         shared_ptr<RouteList> r = routes.reader ();
1413         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1414                 if (!(*i)->is_hidden()) {
1415                         in += (*i)->n_inputs();
1416                         out     += (*i)->n_outputs();
1417                 }
1418         }
1419 }
1420
1421 list<boost::shared_ptr<MidiTrack> >
1422 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1423 {
1424         char track_name[32];
1425         uint32_t track_id = 0;
1426         ChanCount existing_inputs;
1427         ChanCount existing_outputs;
1428         string port;
1429         RouteList new_routes;
1430         list<boost::shared_ptr<MidiTrack> > ret;
1431         uint32_t control_id;
1432
1433         count_existing_route_channels (existing_inputs, existing_outputs);
1434
1435         control_id = ntracks() + nbusses();
1436
1437         while (how_many) {
1438                 if (!find_route_name ("Midi", ++track_id, track_name, sizeof(track_name))) {
1439                         error << "cannot find name for new midi track" << endmsg;
1440                         goto failed;
1441                 }
1442
1443                 shared_ptr<MidiTrack> track;
1444
1445                 try {
1446                         MidiTrack* mt = new MidiTrack (*this, track_name, Route::Flag (0), mode);
1447
1448                         if (mt->init ()) {
1449                                 delete mt;
1450                                 goto failed;
1451                         }
1452
1453                         mt->use_new_diskstream();
1454
1455                         boost_debug_shared_ptr_mark_interesting (mt, "Track");
1456                         track = boost::shared_ptr<MidiTrack>(mt);
1457
1458                         if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1459                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1460                                 goto failed;
1461                         }
1462
1463
1464                         if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1465                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1466                                 goto failed;
1467                         }
1468
1469                         auto_connect_route (track, existing_inputs, existing_outputs);
1470
1471                         track->midi_diskstream()->non_realtime_input_change();
1472                         if (route_group) {
1473                                 route_group->add (track);
1474                         }
1475
1476                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1477                         track->set_remote_control_id (control_id);
1478
1479                         new_routes.push_back (track);
1480                         ret.push_back (track);
1481                 }
1482
1483                 catch (failed_constructor &err) {
1484                         error << _("Session: could not create new midi track.") << endmsg;
1485
1486                         if (track) {
1487                                 /* we need to get rid of this, since the track failed to be created */
1488                                 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1489
1490                                 {
1491                                         RCUWriter<DiskstreamList> writer (diskstreams);
1492                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1493                                         ds->remove (track->midi_diskstream());
1494                                 }
1495                         }
1496
1497                         goto failed;
1498                 }
1499
1500                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1501
1502                         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;
1503
1504                         if (track) {
1505                                 /* we need to get rid of this, since the track failed to be created */
1506                                 /* XXX arguably, MidiTrack::MidiTrack should not do the Session::add_diskstream() */
1507
1508                                 {
1509                                         RCUWriter<DiskstreamList> writer (diskstreams);
1510                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1511                                         ds->remove (track->midi_diskstream());
1512                                 }
1513                         }
1514
1515                         goto failed;
1516                 }
1517
1518                 --how_many;
1519         }
1520
1521   failed:
1522         if (!new_routes.empty()) {
1523                 add_routes (new_routes, false);
1524                 save_state (_current_snapshot_name);
1525         }
1526
1527         return ret;
1528 }
1529
1530 void
1531 Session::auto_connect_route (boost::shared_ptr<Route> route,
1532                 ChanCount& existing_inputs, ChanCount& existing_outputs)
1533 {
1534         /* If both inputs and outputs are auto-connected to physical ports,
1535            use the max of input and output offsets to ensure auto-connected
1536            port numbers always match up (e.g. the first audio input and the
1537            first audio output of the route will have the same physical
1538            port number).  Otherwise just use the lowest input or output
1539            offset possible.
1540         */
1541         const bool in_out_physical =
1542                    (Config->get_input_auto_connect() & AutoConnectPhysical)
1543                 && (Config->get_output_auto_connect() & AutoConnectPhysical);
1544
1545         const ChanCount in_offset = in_out_physical
1546                 ? ChanCount::max(existing_inputs, existing_outputs)
1547                 : existing_inputs;
1548
1549         const ChanCount out_offset = in_out_physical
1550                 ? ChanCount::max(existing_inputs, existing_outputs)
1551                 : existing_outputs;
1552
1553         static string empty_string;
1554         string& port = empty_string;
1555
1556         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1557                 vector<string> physinputs;
1558                 vector<string> physoutputs;
1559
1560                 _engine.get_physical_outputs (*t, physoutputs);
1561                 _engine.get_physical_inputs (*t, physinputs);
1562
1563                 if (!physinputs.empty()) {
1564                         uint32_t nphysical_in = physinputs.size();
1565                         for (uint32_t i = 0; i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1566                                 port = empty_string;
1567
1568                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1569                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1570                                 }
1571
1572                                 if (!port.empty() && route->input()->connect (
1573                                                 route->input()->ports().port(*t, i), port, this)) {
1574                                         break;
1575                                 }
1576                         }
1577                 }
1578
1579                 if (!physoutputs.empty()) {
1580                         uint32_t nphysical_out = physoutputs.size();
1581                         for (uint32_t i = 0; i < route->n_outputs().get(*t); ++i) {
1582                                 port = empty_string;
1583
1584                                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1585                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1586                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1587                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1588                                                 port = _master_out->input()->ports().port(*t,
1589                                                                 i % _master_out->input()->n_ports().get(*t))->name();
1590                                         }
1591                                 }
1592
1593                                 if (!port.empty() && route->output()->connect (
1594                                                 route->output()->ports().port(*t, i), port, this)) {
1595                                         break;
1596                                 }
1597                         }
1598                 }
1599         }
1600
1601         existing_inputs += route->n_inputs();
1602         existing_outputs += route->n_outputs();
1603 }
1604
1605 list< boost::shared_ptr<AudioTrack> >
1606 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1607 {
1608         char track_name[32];
1609         uint32_t track_id = 0;
1610         ChanCount existing_inputs;
1611         ChanCount existing_outputs;
1612         string port;
1613         RouteList new_routes;
1614         list<boost::shared_ptr<AudioTrack> > ret;
1615         uint32_t control_id;
1616
1617         count_existing_route_channels (existing_inputs, existing_outputs);
1618
1619         control_id = ntracks() + nbusses() + 1;
1620
1621         while (how_many) {
1622                 if (!find_route_name ("Audio", ++track_id, track_name, sizeof(track_name))) {
1623                         error << "cannot find name for new audio track" << endmsg;
1624                         goto failed;
1625                 }
1626
1627                 shared_ptr<AudioTrack> track;
1628
1629                 try {
1630                         AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1631
1632                         if (at->init ()) {
1633                                 delete at;
1634                                 goto failed;
1635                         }
1636
1637                         at->use_new_diskstream();
1638
1639                         boost_debug_shared_ptr_mark_interesting (at, "Track");
1640                         track = boost::shared_ptr<AudioTrack>(at);
1641
1642                         if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1643                                 error << string_compose (
1644                                                         _("cannot configure %1 in/%2 out configuration for new audio track"),
1645                                                          input_channels, output_channels)
1646                                       << endmsg;
1647                                 goto failed;
1648                         }
1649
1650                         if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1651                                 error << string_compose (
1652                                                         _("cannot configure %1 in/%2 out configuration for new audio track"),
1653                                                          input_channels, output_channels)
1654                                       << endmsg;
1655                                 goto failed;
1656                         }
1657
1658                         auto_connect_route (track, existing_inputs, existing_outputs);
1659
1660                         if (route_group) {
1661                                 route_group->add (track);
1662                         }
1663
1664                         track->audio_diskstream()->non_realtime_input_change();
1665
1666                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1667                         track->set_remote_control_id (control_id);
1668                         ++control_id;
1669
1670                         new_routes.push_back (track);
1671                         ret.push_back (track);
1672                 }
1673
1674                 catch (failed_constructor &err) {
1675                         error << _("Session: could not create new audio track.") << endmsg;
1676
1677                         if (track) {
1678                                 /* we need to get rid of this, since the track failed to be created */
1679                                 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1680
1681                                 {
1682                                         RCUWriter<DiskstreamList> writer (diskstreams);
1683                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1684                                         ds->remove (track->audio_diskstream());
1685                                 }
1686                         }
1687
1688                         goto failed;
1689                 }
1690
1691                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1692
1693                         error << pfe.what() << endmsg;
1694
1695                         if (track) {
1696                                 /* we need to get rid of this, since the track failed to be created */
1697                                 /* XXX arguably, AudioTrack::AudioTrack should not do the Session::add_diskstream() */
1698
1699                                 {
1700                                         RCUWriter<DiskstreamList> writer (diskstreams);
1701                                         boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1702                                         ds->remove (track->audio_diskstream());
1703                                 }
1704                         }
1705
1706                         goto failed;
1707                 }
1708
1709                 --how_many;
1710         }
1711
1712   failed:
1713         if (!new_routes.empty()) {
1714                 add_routes (new_routes, true);
1715         }
1716
1717         return ret;
1718 }
1719
1720 void
1721 Session::set_remote_control_ids ()
1722 {
1723         RemoteModel m = Config->get_remote_model();
1724         bool emit_signal = false;
1725
1726         shared_ptr<RouteList> r = routes.reader ();
1727
1728         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1729                 if (MixerOrdered == m) {
1730                         long order = (*i)->order_key(N_("signal"));
1731                         (*i)->set_remote_control_id (order+1, false);
1732                         emit_signal = true;
1733                 } else if (EditorOrdered == m) {
1734                         long order = (*i)->order_key(N_("editor"));
1735                         (*i)->set_remote_control_id (order+1, false);
1736                         emit_signal = true;
1737                 } else if (UserOrdered == m) {
1738                         //do nothing ... only changes to remote id's are initiated by user
1739                 }
1740         }
1741
1742         if (emit_signal) {
1743                 Route::RemoteControlIDChange();
1744         }
1745 }
1746
1747
1748 RouteList
1749 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1750 {
1751         char bus_name[32];
1752         uint32_t bus_id = 0;
1753         ChanCount existing_inputs;
1754         ChanCount existing_outputs;
1755         string port;
1756         RouteList ret;
1757         uint32_t control_id;
1758
1759         count_existing_route_channels (existing_inputs, existing_outputs);
1760
1761         control_id = ntracks() + nbusses() + 1;
1762
1763         while (how_many) {
1764                 if (!find_route_name ("Bus", ++bus_id, bus_name, sizeof(bus_name))) {
1765                         error << "cannot find name for new audio bus" << endmsg;
1766                         goto failure;
1767                 }
1768
1769                 try {
1770                         Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1771
1772                         if (rt->init ()) {
1773                                 delete rt;
1774                                 goto failure;
1775                         }
1776
1777                         boost_debug_shared_ptr_mark_interesting (rt, "Route");
1778                         shared_ptr<Route> bus (rt);
1779
1780                         if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1781                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1782                                                          input_channels, output_channels)
1783                                       << endmsg;
1784                                 goto failure;
1785                         }
1786
1787
1788                         if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1789                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1790                                                          input_channels, output_channels)
1791                                       << endmsg;
1792                                 goto failure;
1793                         }
1794
1795                         auto_connect_route (bus, existing_inputs, existing_outputs);
1796
1797                         if (route_group) {
1798                                 route_group->add (bus);
1799                         }
1800                         bus->set_remote_control_id (control_id);
1801                         ++control_id;
1802
1803                         if (aux) {
1804                                 bus->add_internal_return ();
1805                         }
1806
1807                         ret.push_back (bus);
1808                 }
1809
1810
1811                 catch (failed_constructor &err) {
1812                         error << _("Session: could not create new audio route.") << endmsg;
1813                         goto failure;
1814                 }
1815
1816                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1817                         error << pfe.what() << endmsg;
1818                         goto failure;
1819                 }
1820
1821
1822                 --how_many;
1823         }
1824
1825   failure:
1826         if (!ret.empty()) {
1827                 add_routes (ret, true);
1828         }
1829
1830         return ret;
1831
1832 }
1833
1834 RouteList
1835 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1836 {
1837         char name[32];
1838         RouteList ret;
1839         uint32_t control_id;
1840         XMLTree tree;
1841         uint32_t number = 0;
1842
1843         if (!tree.read (template_path.c_str())) {
1844                 return ret;
1845         }
1846
1847         XMLNode* node = tree.root();
1848
1849         control_id = ntracks() + nbusses() + 1;
1850
1851         while (how_many) {
1852
1853                 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1854
1855                 std::string node_name = IO::name_from_state (*node_copy.children().front());
1856
1857                 /* generate a new name by adding a number to the end of the template name */
1858                 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name))) {
1859                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1860                         /*NOTREACHED*/
1861                 }
1862
1863                 IO::set_name_in_state (*node_copy.children().front(), name);
1864
1865                 Track::zero_diskstream_id_in_xml (node_copy);
1866
1867                 try {
1868                         shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1869             
1870                         if (route == 0) {
1871                                 error << _("Session: cannot create track/bus from template description") << endmsg;
1872                                 goto out;
1873                         }
1874
1875                         if (boost::dynamic_pointer_cast<Track>(route)) {
1876                                 /* force input/output change signals so that the new diskstream
1877                                    picks up the configuration of the route. During session
1878                                    loading this normally happens in a different way.
1879                                 */
1880                                 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1881                                 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1882                         }
1883
1884                         route->set_remote_control_id (control_id);
1885                         ++control_id;
1886
1887                         ret.push_back (route);
1888                 }
1889
1890                 catch (failed_constructor &err) {
1891                         error << _("Session: could not create new route from template") << endmsg;
1892                         goto out;
1893                 }
1894
1895                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1896                         error << pfe.what() << endmsg;
1897                         goto out;
1898                 }
1899
1900                 --how_many;
1901         }
1902
1903   out:
1904         if (!ret.empty()) {
1905                 add_routes (ret, true);
1906         }
1907
1908         return ret;
1909 }
1910
1911 void
1912 Session::add_routes (RouteList& new_routes, bool save)
1913 {
1914         {
1915                 RCUWriter<RouteList> writer (routes);
1916                 shared_ptr<RouteList> r = writer.get_copy ();
1917                 r->insert (r->end(), new_routes.begin(), new_routes.end());
1918
1919
1920                 /* if there is no control out and we're not in the middle of loading,
1921                    resort the graph here. if there is a control out, we will resort
1922                    toward the end of this method. if we are in the middle of loading,
1923                    we will resort when done.
1924                 */
1925
1926                 if (!_monitor_out && IO::connecting_legal) {
1927                         resort_routes_using (r);
1928                 }
1929         }
1930
1931         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1932
1933                 boost::weak_ptr<Route> wpr (*x);
1934                 boost::shared_ptr<Route> r (*x);
1935
1936                 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1937                 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, wpr));
1938                 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1939                 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1940                 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
1941                 r->route_group_changed.connect_same_thread (*this, boost::bind (&Session::route_group_changed, this));
1942
1943                 if (r->is_master()) {
1944                         _master_out = r;
1945                 }
1946
1947                 if (r->is_monitor()) {
1948                         _monitor_out = r;
1949                 }
1950         }
1951
1952         if (_monitor_out && IO::connecting_legal) {
1953
1954                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1955                         if ((*x)->is_monitor()) {
1956                                 /* relax */
1957                         } else if ((*x)->is_master()) {
1958                                 /* relax */
1959                         } else {
1960                                 (*x)->listen_via (_monitor_out,
1961                                                   (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
1962                                                   false, false);
1963                         }
1964                 }
1965
1966                 resort_routes ();
1967         }
1968
1969         set_dirty();
1970
1971         if (save) {
1972                 save_state (_current_snapshot_name);
1973         }
1974
1975         RouteAdded (new_routes); /* EMIT SIGNAL */
1976         Route::RemoteControlIDChange (); /* EMIT SIGNAL */
1977 }
1978
1979 void
1980 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
1981 {
1982         boost::shared_ptr<RouteList> r = routes.reader ();
1983         boost::shared_ptr<Send> s;
1984
1985         /* only tracks */
1986
1987         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1988                 if (boost::dynamic_pointer_cast<Track>(*i)) {
1989                         if ((s = (*i)->internal_send_for (dest)) != 0) {
1990                                 s->amp()->gain_control()->set_value (0.0);
1991                         }
1992                 }
1993         }
1994 }
1995
1996 void
1997 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
1998 {
1999         boost::shared_ptr<RouteList> r = routes.reader ();
2000         boost::shared_ptr<Send> s;
2001
2002         /* only tracks */
2003
2004         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2005                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2006                         if ((s = (*i)->internal_send_for (dest)) != 0) {
2007                                 s->amp()->gain_control()->set_value (1.0);
2008                         }
2009                 }
2010         }
2011 }
2012
2013 void
2014 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2015 {
2016         boost::shared_ptr<RouteList> r = routes.reader ();
2017         boost::shared_ptr<Send> s;
2018
2019         /* only tracks */
2020
2021         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2022                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2023                         if ((s = (*i)->internal_send_for (dest)) != 0) {
2024                                 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2025                         }
2026                 }
2027         }
2028 }
2029
2030 void
2031 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2032 {
2033         boost::shared_ptr<RouteList> r = routes.reader ();
2034         boost::shared_ptr<RouteList> t (new RouteList);
2035
2036         /* only send tracks */
2037
2038         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2039                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2040                         t->push_back (*i);
2041                 }
2042         }
2043
2044         add_internal_sends (dest, p, t);
2045 }
2046
2047 void
2048 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2049 {
2050         if (dest->is_monitor() || dest->is_master()) {
2051                 return;
2052         }
2053
2054         if (!dest->internal_return()) {
2055                 dest->add_internal_return();
2056         }
2057
2058         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2059
2060                 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2061                         continue;
2062                 }
2063
2064                 (*i)->listen_via (dest, p, true, true);
2065         }
2066
2067         graph_reordered ();
2068 }
2069
2070 void
2071 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
2072 {
2073         /* need to do this in case we're rolling at the time, to prevent false underruns */
2074         dstream->do_refill_with_alloc ();
2075
2076         dstream->set_block_size (current_block_size);
2077
2078         {
2079                 RCUWriter<DiskstreamList> writer (diskstreams);
2080                 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
2081                 ds->push_back (dstream);
2082                 /* writer goes out of scope, copies ds back to main */
2083         }
2084
2085         dstream->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::diskstream_playlist_changed, this, boost::weak_ptr<Diskstream> (dstream)));
2086         /* this will connect to future changes, and check the current length */
2087         diskstream_playlist_changed (boost::weak_ptr<Diskstream> (dstream));
2088
2089         dstream->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_diskstream, this));
2090 }
2091
2092 void
2093 Session::remove_route (shared_ptr<Route> route)
2094 {
2095         {
2096                 RCUWriter<RouteList> writer (routes);
2097                 shared_ptr<RouteList> rs = writer.get_copy ();
2098
2099                 rs->remove (route);
2100
2101                 /* deleting the master out seems like a dumb
2102                    idea, but its more of a UI policy issue
2103                    than our concern.
2104                 */
2105
2106                 if (route == _master_out) {
2107                         _master_out = shared_ptr<Route> ();
2108                 }
2109
2110                 if (route == _monitor_out) {
2111
2112                         /* cancel control outs for all routes */
2113
2114                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2115                                 (*r)->drop_listen (_monitor_out);
2116                         }
2117
2118                         _monitor_out.reset ();
2119                 }
2120
2121                 update_route_solo_state ();
2122
2123                 /* writer goes out of scope, forces route list update */
2124         }
2125
2126         boost::shared_ptr<Track> t;
2127         boost::shared_ptr<Diskstream> ds;
2128
2129         if ((t = boost::dynamic_pointer_cast<Track>(route)) != 0) {
2130                 ds = t->diskstream();
2131         }
2132
2133         if (ds) {
2134
2135                 {
2136                         RCUWriter<DiskstreamList> dsl (diskstreams);
2137                         boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
2138                         d->remove (ds);
2139                 }
2140         }
2141
2142         find_current_end ();
2143
2144         // We need to disconnect the routes inputs and outputs
2145
2146         route->input()->disconnect (0);
2147         route->output()->disconnect (0);
2148
2149         /* if the route had internal sends sending to it, remove them */
2150         if (route->internal_return()) {
2151
2152                 boost::shared_ptr<RouteList> r = routes.reader ();
2153                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2154                         boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2155                         if (s) {
2156                                 (*i)->remove_processor (s);
2157                         }
2158                 }
2159         }       
2160
2161         update_latency_compensation (false, false);
2162         set_dirty();
2163
2164         /* get rid of it from the dead wood collection in the route list manager */
2165
2166         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2167
2168         routes.flush ();
2169
2170         /* try to cause everyone to drop their references */
2171
2172         route->drop_references ();
2173
2174         sync_order_keys (N_("session"));
2175
2176         Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2177
2178         /* save the new state of the world */
2179
2180         if (save_state (_current_snapshot_name)) {
2181                 save_history (_current_snapshot_name);
2182         }
2183 }
2184
2185 void
2186 Session::route_mute_changed (void* /*src*/)
2187 {
2188         set_dirty ();
2189 }
2190
2191 void
2192 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2193 {
2194         boost::shared_ptr<Route> route = wpr.lock();
2195         if (!route) {
2196                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2197                 return;
2198         }
2199
2200         if (route->listening()) {
2201                 _listen_cnt++;
2202         } else if (_listen_cnt > 0) {
2203                 _listen_cnt--;
2204         }
2205 }
2206
2207 void
2208 Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2209 {
2210         if (solo_update_disabled) {
2211                 // We know already
2212                 return;
2213         }
2214
2215         boost::shared_ptr<Route> route = wpr.lock ();
2216
2217         if (!route) {
2218                 /* should not happen */
2219                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2220                 return;
2221         }
2222
2223         shared_ptr<RouteList> r = routes.reader ();
2224         int32_t delta;
2225
2226         if (route->self_soloed()) {
2227                 delta = 1;
2228         } else {
2229                 delta = -1;
2230         }
2231
2232         /* now mod the solo level of all other routes except master/control outs/auditioner
2233            so that they will be silent if appropriate.
2234         */
2235
2236         solo_update_disabled = true;
2237
2238         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2239                 bool via_sends_only;
2240
2241                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2242                         continue;
2243                 } else if ((*i)->feeds (route, &via_sends_only)) {
2244                         if (!via_sends_only) {
2245                                 (*i)->mod_solo_by_others (delta);
2246                         }
2247                 } 
2248         }
2249
2250         /* make sure master is never muted by solo */
2251
2252         if (_master_out && route != _master_out && _master_out->soloed_by_others() == 0 && !_master_out->soloed()) {
2253                 _master_out->mod_solo_by_others (1);
2254         }
2255  
2256         /* ditto for control outs make sure it is never muted by solo */
2257
2258         if (_monitor_out && route != _monitor_out && _monitor_out && _monitor_out->soloed_by_others() == 0) {
2259                 _monitor_out->mod_solo_by_others (1);
2260         }
2261
2262         /* ditto for auditioner make sure it is never muted by solo */
2263
2264         if (auditioner) {
2265                 auditioner->mod_solo_by_others (1);
2266         }
2267
2268         solo_update_disabled = false;
2269         update_route_solo_state (r);
2270         SoloChanged (); /* EMIT SIGNAL */
2271         set_dirty();
2272 }
2273
2274 void
2275 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2276 {
2277         /* now figure out if anything that matters is soloed (or is "listening")*/
2278
2279         bool something_soloed = false;
2280         uint32_t listeners = 0;
2281
2282         if (!r) {
2283                 r = routes.reader();
2284         }
2285
2286         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2287                 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2288                         something_soloed = true;
2289                         break;
2290                 }
2291
2292                 if (!(*i)->is_hidden() && (*i)->listening()) {
2293                         if (Config->get_solo_control_is_listen_control()) {
2294                                 listeners++;
2295                         } else {
2296                                 (*i)->set_listen (false, this);
2297                         }
2298                 }
2299         }
2300
2301         if (something_soloed != _non_soloed_outs_muted) {
2302                 _non_soloed_outs_muted = something_soloed;
2303                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2304         }
2305
2306         if (listeners) {
2307                  _listen_cnt = listeners;
2308         }
2309 }
2310
2311 boost::shared_ptr<RouteList> 
2312 Session::get_routes_with_internal_returns() const
2313 {
2314         shared_ptr<RouteList> r = routes.reader ();
2315         boost::shared_ptr<RouteList> rl (new RouteList);
2316
2317         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2318                 if ((*i)->internal_return ()) {
2319                         rl->push_back (*i);
2320                 }
2321         }
2322         return rl;
2323 }
2324
2325 shared_ptr<Route>
2326 Session::route_by_name (string name)
2327 {
2328         shared_ptr<RouteList> r = routes.reader ();
2329
2330         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2331                 if ((*i)->name() == name) {
2332                         return *i;
2333                 }
2334         }
2335
2336         return shared_ptr<Route> ((Route*) 0);
2337 }
2338
2339 shared_ptr<Route>
2340 Session::route_by_id (PBD::ID id)
2341 {
2342         shared_ptr<RouteList> r = routes.reader ();
2343
2344         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2345                 if ((*i)->id() == id) {
2346                         return *i;
2347                 }
2348         }
2349
2350         return shared_ptr<Route> ((Route*) 0);
2351 }
2352
2353 shared_ptr<Route>
2354 Session::route_by_remote_id (uint32_t id)
2355 {
2356         shared_ptr<RouteList> r = routes.reader ();
2357
2358         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2359                 if ((*i)->remote_control_id() == id) {
2360                         return *i;
2361                 }
2362         }
2363
2364         return shared_ptr<Route> ((Route*) 0);
2365 }
2366
2367 void
2368 Session::find_current_end ()
2369 {
2370         if (_state_of_the_state & Loading) {
2371                 return;
2372         }
2373
2374         nframes_t max = get_maximum_extent ();
2375
2376         if (max > _session_range_location->end()) {
2377                 _session_range_location->set_end (max);
2378                 set_dirty();
2379                 DurationChanged(); /* EMIT SIGNAL */
2380         }
2381 }
2382
2383 nframes_t
2384 Session::get_maximum_extent () const
2385 {
2386         nframes_t max = 0;
2387         nframes_t me;
2388
2389         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2390
2391         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2392                 if ((*i)->destructive())  //ignore tape tracks when getting max extents
2393                         continue;
2394                 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2395                 if ((me = pl->get_maximum_extent()) > max) {
2396                         max = me;
2397                 }
2398         }
2399
2400         return max;
2401 }
2402
2403 boost::shared_ptr<Diskstream>
2404 Session::diskstream_by_name (string name)
2405 {
2406         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2407
2408         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2409                 if ((*i)->name() == name) {
2410                         return *i;
2411                 }
2412         }
2413
2414         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2415 }
2416
2417 boost::shared_ptr<Diskstream>
2418 Session::diskstream_by_id (const PBD::ID& id)
2419 {
2420         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2421
2422         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2423                 if ((*i)->id() == id) {
2424                         return *i;
2425                 }
2426         }
2427
2428         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2429 }
2430
2431 /* Region management */
2432
2433 boost::shared_ptr<Region>
2434 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2435 {
2436         const RegionFactory::RegionMap& regions (RegionFactory::regions());
2437         RegionFactory::RegionMap::const_iterator i;
2438         boost::shared_ptr<Region> region;
2439
2440         Glib::Mutex::Lock lm (region_lock);
2441
2442         for (i = regions.begin(); i != regions.end(); ++i) {
2443
2444                 region = i->second;
2445
2446                 if (region->whole_file()) {
2447
2448                         if (child->source_equivalent (region)) {
2449                                 return region;
2450                         }
2451                 }
2452         }
2453
2454         return boost::shared_ptr<Region> ();
2455 }
2456
2457 int
2458 Session::destroy_region (boost::shared_ptr<Region> region)
2459 {
2460         vector<boost::shared_ptr<Source> > srcs;
2461
2462         {
2463                 if (region->playlist()) {
2464                         region->playlist()->destroy_region (region);
2465                 }
2466
2467                 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2468                         srcs.push_back (region->source (n));
2469                 }
2470         }
2471
2472         region->drop_references ();
2473
2474         for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2475
2476                 (*i)->mark_for_remove ();
2477                 (*i)->drop_references ();
2478                 
2479                 cerr << "source was not used by any playlist\n";
2480         }
2481
2482         return 0;
2483 }
2484
2485 int
2486 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2487 {
2488         for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2489                 destroy_region (*i);
2490         }
2491         return 0;
2492 }
2493
2494 int
2495 Session::remove_last_capture ()
2496 {
2497         list<boost::shared_ptr<Region> > r;
2498
2499         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2500
2501         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2502                 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2503
2504                 if (!l.empty()) {
2505                         r.insert (r.end(), l.begin(), l.end());
2506                         l.clear ();
2507                 }
2508         }
2509
2510         destroy_regions (r);
2511
2512         save_state (_current_snapshot_name);
2513
2514         return 0;
2515 }
2516
2517 /* Source Management */
2518
2519 void
2520 Session::add_source (boost::shared_ptr<Source> source)
2521 {
2522         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2523         pair<SourceMap::iterator,bool> result;
2524
2525         entry.first = source->id();
2526         entry.second = source;
2527
2528         {
2529                 Glib::Mutex::Lock lm (source_lock);
2530                 result = sources.insert (entry);
2531         }
2532
2533         if (result.second) {
2534                 set_dirty();
2535         }
2536
2537         boost::shared_ptr<AudioFileSource> afs;
2538
2539         if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2540                 if (Config->get_auto_analyse_audio()) {
2541                         Analyser::queue_source_for_analysis (source, false);
2542                 }
2543         }
2544 }
2545
2546 void
2547 Session::remove_source (boost::weak_ptr<Source> src)
2548 {
2549         SourceMap::iterator i;
2550         boost::shared_ptr<Source> source = src.lock();
2551
2552         if (!source) {
2553                 return;
2554         }
2555
2556         {
2557                 Glib::Mutex::Lock lm (source_lock);
2558
2559                 if ((i = sources.find (source->id())) != sources.end()) {
2560                         sources.erase (i);
2561                 }
2562         }
2563
2564         if (!_state_of_the_state & InCleanup) {
2565
2566                 /* save state so we don't end up with a session file
2567                    referring to non-existent sources.
2568                 */
2569
2570                 save_state (_current_snapshot_name);
2571         }
2572 }
2573
2574 boost::shared_ptr<Source>
2575 Session::source_by_id (const PBD::ID& id)
2576 {
2577         Glib::Mutex::Lock lm (source_lock);
2578         SourceMap::iterator i;
2579         boost::shared_ptr<Source> source;
2580
2581         if ((i = sources.find (id)) != sources.end()) {
2582                 source = i->second;
2583         }
2584
2585         return source;
2586 }
2587
2588 boost::shared_ptr<Source>
2589 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2590 {
2591         Glib::Mutex::Lock lm (source_lock);
2592
2593         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2594                 cerr << "comparing " << path << " with " << i->second->name() << endl;
2595                 boost::shared_ptr<AudioFileSource> afs
2596                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2597
2598                 if (afs && afs->path() == path && chn == afs->channel()) {
2599                         return afs;
2600                 }
2601         }
2602         return boost::shared_ptr<Source>();
2603 }
2604
2605
2606 string
2607 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2608 {
2609         string look_for;
2610         string old_basename = PBD::basename_nosuffix (oldname);
2611         string new_legalized = legalize_for_path (newname);
2612
2613         /* note: we know (or assume) the old path is already valid */
2614
2615         if (destructive) {
2616
2617                 /* destructive file sources have a name of the form:
2618
2619                     /path/to/Tnnnn-NAME(%[LR])?.wav
2620
2621                     the task here is to replace NAME with the new name.
2622                 */
2623
2624                 /* find last slash */
2625
2626                 string dir;
2627                 string prefix;
2628                 string::size_type slash;
2629                 string::size_type dash;
2630
2631                 if ((slash = path.find_last_of ('/')) == string::npos) {
2632                         return "";
2633                 }
2634
2635                 dir = path.substr (0, slash+1);
2636
2637                 /* '-' is not a legal character for the NAME part of the path */
2638
2639                 if ((dash = path.find_last_of ('-')) == string::npos) {
2640                         return "";
2641                 }
2642
2643                 prefix = path.substr (slash+1, dash-(slash+1));
2644
2645                 path = dir;
2646                 path += prefix;
2647                 path += '-';
2648                 path += new_legalized;
2649                 path += ".wav";  /* XXX gag me with a spoon */
2650
2651         } else {
2652
2653                 /* non-destructive file sources have a name of the form:
2654
2655                     /path/to/NAME-nnnnn(%[LR])?.ext
2656
2657                     the task here is to replace NAME with the new name.
2658                 */
2659
2660                 string dir;
2661                 string suffix;
2662                 string::size_type slash;
2663                 string::size_type dash;
2664                 string::size_type postfix;
2665
2666                 /* find last slash */
2667
2668                 if ((slash = path.find_last_of ('/')) == string::npos) {
2669                         return "";
2670                 }
2671
2672                 dir = path.substr (0, slash+1);
2673
2674                 /* '-' is not a legal character for the NAME part of the path */
2675
2676                 if ((dash = path.find_last_of ('-')) == string::npos) {
2677                         return "";
2678                 }
2679
2680                 suffix = path.substr (dash+1);
2681
2682                 // Suffix is now everything after the dash. Now we need to eliminate
2683                 // the nnnnn part, which is done by either finding a '%' or a '.'
2684
2685                 postfix = suffix.find_last_of ("%");
2686                 if (postfix == string::npos) {
2687                         postfix = suffix.find_last_of ('.');
2688                 }
2689
2690                 if (postfix != string::npos) {
2691                         suffix = suffix.substr (postfix);
2692                 } else {
2693                         error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2694                         return "";
2695                 }
2696
2697                 const uint32_t limit = 10000;
2698                 char buf[PATH_MAX+1];
2699
2700                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2701
2702                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2703
2704                         if (access (buf, F_OK) != 0) {
2705                                 path = buf;
2706                                 break;
2707                         }
2708                         path = "";
2709                 }
2710
2711                 if (path == "") {
2712                         error << "FATAL ERROR! Could not find a " << endl;
2713                 }
2714
2715         }
2716
2717         return path;
2718 }
2719
2720 /** Return the full path (in some session directory) for a new within-session source.
2721  * \a name must be a session-unique name that does not contain slashes
2722  *         (e.g. as returned by new_*_source_name)
2723  */
2724 string
2725 Session::new_source_path_from_name (DataType type, const string& name)
2726 {
2727         assert(name.find("/") == string::npos);
2728
2729         SessionDirectory sdir(get_best_session_directory_for_new_source());
2730
2731         sys::path p;
2732         if (type == DataType::AUDIO) {
2733                 p = sdir.sound_path();
2734         } else if (type == DataType::MIDI) {
2735                 p = sdir.midi_path();
2736         } else {
2737                 error << "Unknown source type, unable to create file path" << endmsg;
2738                 return "";
2739         }
2740
2741         p /= name;
2742         return p.to_string();
2743 }
2744
2745 Glib::ustring
2746 Session::peak_path (Glib::ustring base) const
2747 {
2748         sys::path peakfile_path(_session_dir->peak_path());
2749         peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2750         return peakfile_path.to_string();
2751 }
2752
2753 /** Return a unique name based on \a base for a new internal audio source */
2754 string
2755 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
2756 {
2757         string spath;
2758         uint32_t cnt;
2759         char buf[PATH_MAX+1];
2760         const uint32_t limit = 10000;
2761         string legalized;
2762
2763         buf[0] = '\0';
2764         legalized = legalize_for_path (base);
2765
2766         // Find a "version" of the base name that doesn't exist in any of the possible directories.
2767         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2768
2769                 vector<space_and_path>::iterator i;
2770                 uint32_t existing = 0;
2771
2772                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2773
2774                         SessionDirectory sdir((*i).path);
2775
2776                         spath = sdir.sound_path().to_string();
2777
2778                         if (destructive) {
2779
2780                                 if (nchan < 2) {
2781                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2782                                                         spath.c_str(), cnt, legalized.c_str());
2783                                 } else if (nchan == 2) {
2784                                         if (chan == 0) {
2785                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
2786                                                                 spath.c_str(), cnt, legalized.c_str());
2787                                         } else {
2788                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
2789                                                                 spath.c_str(), cnt, legalized.c_str());
2790                                         }
2791                                 } else if (nchan < 26) {
2792                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
2793                                                         spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2794                                 } else {
2795                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
2796                                                         spath.c_str(), cnt, legalized.c_str());
2797                                 }
2798
2799                         } else {
2800
2801                                 spath += '/';
2802                                 spath += legalized;
2803
2804                                 if (nchan < 2) {
2805                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2806                                 } else if (nchan == 2) {
2807                                         if (chan == 0) {
2808                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2809                                         } else {
2810                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2811                                         }
2812                                 } else if (nchan < 26) {
2813                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2814                                 } else {
2815                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2816                                 }
2817                         }
2818
2819                         if (sys::exists(buf)) {
2820                                 existing++;
2821                         }
2822
2823                 }
2824
2825                 if (existing == 0) {
2826                         break;
2827                 }
2828
2829                 if (cnt > limit) {
2830                         error << string_compose(
2831                                         _("There are already %1 recordings for %2, which I consider too many."),
2832                                         limit, base) << endmsg;
2833                         destroy ();
2834                         throw failed_constructor();
2835                 }
2836         }
2837
2838         return Glib::path_get_basename(buf);
2839 }
2840
2841 /** Create a new within-session audio source */
2842 boost::shared_ptr<AudioFileSource>
2843 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
2844 {
2845         const size_t n_chans = ds.n_channels().n_audio();
2846         const string name    = new_audio_source_name (ds.name(), n_chans, chan, destructive);
2847         const string path    = new_source_path_from_name(DataType::AUDIO, name);
2848
2849         return boost::dynamic_pointer_cast<AudioFileSource> (
2850                 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
2851 }
2852
2853 /** Return a unique name based on \a base for a new internal MIDI source */
2854 string
2855 Session::new_midi_source_name (const string& base)
2856 {
2857         uint32_t cnt;
2858         char buf[PATH_MAX+1];
2859         const uint32_t limit = 10000;
2860         string legalized;
2861
2862         buf[0] = '\0';
2863         legalized = legalize_for_path (base);
2864
2865         // Find a "version" of the file name that doesn't exist in any of the possible directories.
2866         for (cnt = 1; cnt <= limit; ++cnt) {
2867
2868                 vector<space_and_path>::iterator i;
2869                 uint32_t existing = 0;
2870
2871                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2872
2873                         SessionDirectory sdir((*i).path);
2874
2875                         sys::path p = sdir.midi_path();
2876                         p /= legalized;
2877
2878                         snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
2879
2880                         if (sys::exists (buf)) {
2881                                 existing++;
2882                         }
2883                 }
2884
2885                 if (existing == 0) {
2886                         break;
2887                 }
2888
2889                 if (cnt > limit) {
2890                         error << string_compose(
2891                                         _("There are already %1 recordings for %2, which I consider too many."),
2892                                         limit, base) << endmsg;
2893                         destroy ();
2894                         throw failed_constructor();
2895                 }
2896         }
2897
2898         return Glib::path_get_basename(buf);
2899 }
2900
2901
2902 /** Create a new within-session MIDI source */
2903 boost::shared_ptr<MidiSource>
2904 Session::create_midi_source_for_session (MidiDiskstream& ds)
2905 {
2906         const string name = new_midi_source_name (ds.name());
2907         const string path = new_source_path_from_name (DataType::MIDI, name);
2908
2909         return boost::dynamic_pointer_cast<SMFSource> (
2910                         SourceFactory::createWritable (
2911                                         DataType::MIDI, *this, path, false, frame_rate()));
2912 }
2913
2914
2915 void
2916 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
2917 {
2918         if (playlist->hidden()) {
2919                 return;
2920         }
2921
2922         playlists->add (playlist);
2923
2924         if (unused) {
2925                 playlist->release();
2926         }
2927
2928         set_dirty();
2929 }
2930
2931 void
2932 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
2933 {
2934         if (_state_of_the_state & Deletion) {
2935                 return;
2936         }
2937
2938         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
2939
2940         if (!playlist) {
2941                 return;
2942         }
2943
2944         playlists->remove (playlist);
2945
2946         set_dirty();
2947 }
2948
2949 void
2950 Session::set_audition (boost::shared_ptr<Region> r)
2951 {
2952         pending_audition_region = r;
2953         add_post_transport_work (PostTransportAudition);
2954         _butler->schedule_transport_work ();
2955 }
2956
2957 void
2958 Session::audition_playlist ()
2959 {
2960         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
2961         ev->region.reset ();
2962         queue_event (ev);
2963 }
2964
2965 void
2966 Session::non_realtime_set_audition ()
2967 {
2968         if (!pending_audition_region) {
2969                 auditioner->audition_current_playlist ();
2970         } else {
2971                 auditioner->audition_region (pending_audition_region);
2972                 pending_audition_region.reset ();
2973         }
2974         AuditionActive (true); /* EMIT SIGNAL */
2975 }
2976
2977 void
2978 Session::audition_region (boost::shared_ptr<Region> r)
2979 {
2980         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
2981         ev->region = r;
2982         queue_event (ev);
2983 }
2984
2985 void
2986 Session::cancel_audition ()
2987 {
2988         if (auditioner->auditioning()) {
2989                 auditioner->cancel_audition ();
2990                 AuditionActive (false); /* EMIT SIGNAL */
2991         }
2992 }
2993
2994 bool
2995 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
2996 {
2997         if (a->is_monitor()) { 
2998                 return true;
2999         }
3000         if (b->is_monitor()) {
3001                 return false;
3002         }
3003         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3004 }
3005
3006 void
3007 Session::remove_empty_sounds ()
3008 {
3009         vector<string> audio_filenames;
3010
3011         get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3012
3013         Glib::Mutex::Lock lm (source_lock);
3014
3015         TapeFileMatcher tape_file_matcher;
3016
3017         remove_if (audio_filenames.begin(), audio_filenames.end(),
3018                    boost::bind (&TapeFileMatcher::matches, &tape_file_matcher, _1));
3019         
3020         for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3021
3022                 sys::path audio_file_path (_session_dir->sound_path());
3023
3024                 audio_file_path /= *i;
3025
3026                 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3027
3028                         try
3029                         {
3030                                 sys::remove (audio_file_path);
3031                                 const string peakfile = peak_path (audio_file_path.to_string());
3032                                 sys::remove (peakfile);
3033                         }
3034                         catch (const sys::filesystem_error& err)
3035                         {
3036                                 error << err.what() << endmsg;
3037                         }
3038                 }
3039         }
3040 }
3041
3042 bool
3043 Session::is_auditioning () const
3044 {
3045         /* can be called before we have an auditioner object */
3046         if (auditioner) {
3047                 return auditioner->auditioning();
3048         } else {
3049                 return false;
3050         }
3051 }
3052
3053 uint32_t
3054 Session::n_diskstreams () const
3055 {
3056         uint32_t n = 0;
3057
3058         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3059
3060         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3061                 if (!(*i)->hidden()) {
3062                         n++;
3063                 }
3064         }
3065         return n;
3066 }
3067
3068 void
3069 Session::graph_reordered ()
3070 {
3071         /* don't do this stuff if we are setting up connections
3072            from a set_state() call or creating new tracks. Ditto for deletion.
3073         */
3074
3075         if (_state_of_the_state & (InitialConnecting|Deletion)) {
3076                 return;
3077         }
3078
3079         /* every track/bus asked for this to be handled but it was deferred because
3080            we were connecting. do it now.
3081         */
3082
3083         request_input_change_handling ();
3084
3085         resort_routes ();
3086
3087         /* force all diskstreams to update their capture offset values to
3088            reflect any changes in latencies within the graph.
3089         */
3090
3091         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3092
3093         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3094                 (*i)->set_capture_offset ();
3095         }
3096 }
3097
3098 nframes_t
3099 Session::available_capture_duration ()
3100 {
3101         float sample_bytes_on_disk = 4.0; // keep gcc happy
3102
3103         switch (config.get_native_file_data_format()) {
3104         case FormatFloat:
3105                 sample_bytes_on_disk = 4.0;
3106                 break;
3107
3108         case FormatInt24:
3109                 sample_bytes_on_disk = 3.0;
3110                 break;
3111
3112         case FormatInt16:
3113                 sample_bytes_on_disk = 2.0;
3114                 break;
3115
3116         default:
3117                 /* impossible, but keep some gcc versions happy */
3118                 fatal << string_compose (_("programming error: %1"),
3119                                          X_("illegal native file data format"))
3120                       << endmsg;
3121                 /*NOTREACHED*/
3122         }
3123
3124         double scale = 4096.0 / sample_bytes_on_disk;
3125
3126         if (_total_free_4k_blocks * scale > (double) max_frames) {
3127                 return max_frames;
3128         }
3129
3130         return (nframes_t) floor (_total_free_4k_blocks * scale);
3131 }
3132
3133 void
3134 Session::add_bundle (shared_ptr<Bundle> bundle)
3135 {
3136         {
3137                 RCUWriter<BundleList> writer (_bundles);
3138                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3139                 b->push_back (bundle);
3140         }
3141
3142         BundleAdded (bundle); /* EMIT SIGNAL */
3143
3144         set_dirty();
3145 }
3146
3147 void
3148 Session::remove_bundle (shared_ptr<Bundle> bundle)
3149 {
3150         bool removed = false;
3151
3152         {
3153                 RCUWriter<BundleList> writer (_bundles);
3154                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3155                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3156
3157                 if (i != b->end()) {
3158                         b->erase (i);
3159                         removed = true;
3160                 }
3161         }
3162
3163         if (removed) {
3164                  BundleRemoved (bundle); /* EMIT SIGNAL */
3165         }
3166
3167         set_dirty();
3168 }
3169
3170 shared_ptr<Bundle>
3171 Session::bundle_by_name (string name) const
3172 {
3173         boost::shared_ptr<BundleList> b = _bundles.reader ();
3174
3175         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3176                 if ((*i)->name() == name) {
3177                         return* i;
3178                 }
3179         }
3180
3181         return boost::shared_ptr<Bundle> ();
3182 }
3183
3184 void
3185 Session::tempo_map_changed (const PropertyChange&)
3186 {
3187         clear_clicks ();
3188
3189         playlists->update_after_tempo_map_change ();
3190
3191         set_dirty ();
3192 }
3193
3194 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3195  * the given count with the current block size.
3196  */
3197 void
3198 Session::ensure_buffers (ChanCount howmany)
3199 {
3200         BufferManager::ensure_buffers (howmany);
3201 }
3202
3203 void
3204 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3205 {
3206         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3207                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3208         }
3209 }
3210
3211 uint32_t
3212 Session::next_insert_id ()
3213 {
3214         /* this doesn't really loop forever. just think about it */
3215
3216         while (true) {
3217                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3218                         if (!insert_bitset[n]) {
3219                                 insert_bitset[n] = true;
3220                                 return n;
3221
3222                         }
3223                 }
3224
3225                 /* none available, so resize and try again */
3226
3227                 insert_bitset.resize (insert_bitset.size() + 16, false);
3228         }
3229 }
3230
3231 uint32_t
3232 Session::next_send_id ()
3233 {
3234         /* this doesn't really loop forever. just think about it */
3235
3236         while (true) {
3237                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3238                         if (!send_bitset[n]) {
3239                                 send_bitset[n] = true;
3240                                 return n;
3241
3242                         }
3243                 }
3244
3245                 /* none available, so resize and try again */
3246
3247                 send_bitset.resize (send_bitset.size() + 16, false);
3248         }
3249 }
3250
3251 uint32_t
3252 Session::next_return_id ()
3253 {
3254         /* this doesn't really loop forever. just think about it */
3255
3256         while (true) {
3257                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3258                         if (!return_bitset[n]) {
3259                                 return_bitset[n] = true;
3260                                 return n;
3261
3262                         }
3263                 }
3264
3265                 /* none available, so resize and try again */
3266
3267                 return_bitset.resize (return_bitset.size() + 16, false);
3268         }
3269 }
3270
3271 void
3272 Session::mark_send_id (uint32_t id)
3273 {
3274         if (id >= send_bitset.size()) {
3275                 send_bitset.resize (id+16, false);
3276         }
3277         if (send_bitset[id]) {
3278                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3279         }
3280         send_bitset[id] = true;
3281 }
3282
3283 void
3284 Session::mark_return_id (uint32_t id)
3285 {
3286         if (id >= return_bitset.size()) {
3287                 return_bitset.resize (id+16, false);
3288         }
3289         if (return_bitset[id]) {
3290                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3291         }
3292         return_bitset[id] = true;
3293 }
3294
3295 void
3296 Session::mark_insert_id (uint32_t id)
3297 {
3298         if (id >= insert_bitset.size()) {
3299                 insert_bitset.resize (id+16, false);
3300         }
3301         if (insert_bitset[id]) {
3302                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3303         }
3304         insert_bitset[id] = true;
3305 }
3306
3307 void
3308 Session::unmark_send_id (uint32_t id)
3309 {
3310         if (id < send_bitset.size()) {
3311                 send_bitset[id] = false;
3312         }
3313 }
3314
3315 void
3316 Session::unmark_return_id (uint32_t id)
3317 {
3318         if (id < return_bitset.size()) {
3319                 return_bitset[id] = false;
3320         }
3321 }
3322
3323 void
3324 Session::unmark_insert_id (uint32_t id)
3325 {
3326         if (id < insert_bitset.size()) {
3327                 insert_bitset[id] = false;
3328         }
3329 }
3330
3331
3332 /* Named Selection management */
3333
3334 boost::shared_ptr<NamedSelection>
3335 Session::named_selection_by_name (string name)
3336 {
3337         Glib::Mutex::Lock lm (named_selection_lock);
3338         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3339                 if ((*i)->name == name) {
3340                         return *i;
3341                 }
3342         }
3343         return boost::shared_ptr<NamedSelection>();
3344 }
3345
3346 void
3347 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3348 {
3349         {
3350                 Glib::Mutex::Lock lm (named_selection_lock);
3351                 named_selections.insert (named_selections.begin(), named_selection);
3352         }
3353
3354         set_dirty();
3355
3356         NamedSelectionAdded (); /* EMIT SIGNAL */
3357 }
3358
3359 void
3360 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3361 {
3362         bool removed = false;
3363
3364         {
3365                 Glib::Mutex::Lock lm (named_selection_lock);
3366
3367                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3368
3369                 if (i != named_selections.end()) {
3370                         named_selections.erase (i);
3371                         set_dirty();
3372                         removed = true;
3373                 }
3374         }
3375
3376         if (removed) {
3377                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3378         }
3379 }
3380
3381 void
3382 Session::reset_native_file_format ()
3383 {
3384         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3385
3386         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3387                 (*i)->reset_write_sources (false);
3388         }
3389 }
3390
3391 bool
3392 Session::route_name_unique (string n) const
3393 {
3394         shared_ptr<RouteList> r = routes.reader ();
3395
3396         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3397                 if ((*i)->name() == n) {
3398                         return false;
3399                 }
3400         }
3401
3402         return true;
3403 }
3404
3405 bool
3406 Session::route_name_internal (string n) const
3407 {
3408         if (auditioner && auditioner->name() == n) {
3409                 return true;
3410         }
3411
3412         if (_click_io && _click_io->name() == n) {
3413                 return true;
3414         }
3415
3416         return false;
3417 }
3418
3419 int
3420 Session::freeze_all (InterThreadInfo& itt)
3421 {
3422         shared_ptr<RouteList> r = routes.reader ();
3423
3424         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3425
3426                 boost::shared_ptr<Track> t;
3427
3428                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3429                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3430                            of every track.
3431                         */
3432                         t->freeze_me (itt);
3433                 }
3434         }
3435
3436         return 0;
3437 }
3438
3439 boost::shared_ptr<Region>
3440 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3441                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3442                           InterThreadInfo& itt, bool enable_processing)
3443 {
3444         boost::shared_ptr<Region> result;
3445         boost::shared_ptr<Playlist> playlist;
3446         boost::shared_ptr<AudioFileSource> fsource;
3447         uint32_t x;
3448         char buf[PATH_MAX+1];
3449         ChanCount nchans(track.audio_diskstream()->n_channels());
3450         nframes_t position;
3451         nframes_t this_chunk;
3452         nframes_t to_do;
3453         BufferSet buffers;
3454         SessionDirectory sdir(get_best_session_directory_for_new_source ());
3455         const string sound_dir = sdir.sound_path().to_string();
3456         nframes_t len = end - start;
3457
3458         if (end <= start) {
3459                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3460                                          end, start) << endmsg;
3461                 return result;
3462         }
3463
3464         const nframes_t chunk_size = (256 * 1024)/4;
3465
3466         // block all process callback handling
3467
3468         block_processing ();
3469
3470         /* call tree *MUST* hold route_lock */
3471
3472         if ((playlist = track.diskstream()->playlist()) == 0) {
3473                 goto out;
3474         }
3475
3476         /* external redirects will be a problem */
3477
3478         if (track.has_external_redirects()) {
3479                 goto out;
3480         }
3481
3482         for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3483
3484                 for (x = 0; x < 99999; ++x) {
3485                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3486                         if (access (buf, F_OK) != 0) {
3487                                 break;
3488                         }
3489                 }
3490
3491                 if (x == 99999) {
3492                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3493                         goto out;
3494                 }
3495
3496                 try {
3497                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3498                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3499                 }
3500
3501                 catch (failed_constructor& err) {
3502                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3503                         goto out;
3504                 }
3505
3506                 srcs.push_back (fsource);
3507         }
3508
3509         /* XXX need to flush all redirects */
3510
3511         position = start;
3512         to_do = len;
3513
3514         /* create a set of reasonably-sized buffers */
3515         buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3516         buffers.set_count(nchans);
3517
3518         for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3519                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3520                 if (afs)
3521                         afs->prepare_for_peakfile_writes ();
3522         }
3523
3524         while (to_do && !itt.cancel) {
3525
3526                 this_chunk = min (to_do, chunk_size);
3527
3528                 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3529                         goto out;
3530                 }
3531
3532                 uint32_t n = 0;
3533                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3534                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3535
3536                         if (afs) {
3537                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3538                                         goto out;
3539                                 }
3540                         }
3541                 }
3542
3543                 start += this_chunk;
3544                 to_do -= this_chunk;
3545
3546                 itt.progress = (float) (1.0 - ((double) to_do / len));
3547
3548         }
3549
3550         if (!itt.cancel) {
3551
3552                 time_t now;
3553                 struct tm* xnow;
3554                 time (&now);
3555                 xnow = localtime (&now);
3556
3557                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3558                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3559
3560                         if (afs) {
3561                                 afs->update_header (position, *xnow, now);
3562                                 afs->flush_header ();
3563                         }
3564                 }
3565
3566                 /* construct a region to represent the bounced material */
3567
3568                 PropertyList plist;
3569                 
3570                 plist.add (Properties::start, 0);
3571                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3572                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3573                 
3574                 result = RegionFactory::create (srcs, plist);
3575                            
3576         }
3577
3578   out:
3579         if (!result) {
3580                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3581                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3582
3583                         if (afs) {
3584                                 afs->mark_for_remove ();
3585                         }
3586
3587                         (*src)->drop_references ();
3588                 }
3589
3590         } else {
3591                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3592                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3593
3594                         if (afs)
3595                                 afs->done_with_peakfile_writes ();
3596                 }
3597         }
3598
3599         unblock_processing ();
3600
3601         return result;
3602 }
3603
3604 gain_t*
3605 Session::gain_automation_buffer() const
3606 {
3607         return ProcessThread::gain_automation_buffer ();
3608 }
3609
3610 pan_t**
3611 Session::pan_automation_buffer() const
3612 {
3613         return ProcessThread::pan_automation_buffer ();
3614 }
3615
3616 BufferSet&
3617 Session::get_silent_buffers (ChanCount count)
3618 {
3619         return ProcessThread::get_silent_buffers (count);
3620 #if 0
3621         assert(_silent_buffers->available() >= count);
3622         _silent_buffers->set_count(count);
3623
3624         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3625                 for (size_t i= 0; i < count.get(*t); ++i) {
3626                         _silent_buffers->get(*t, i).clear();
3627                 }
3628         }
3629
3630         return *_silent_buffers;
3631 #endif
3632 }
3633
3634 BufferSet&
3635 Session::get_scratch_buffers (ChanCount count)
3636 {
3637         return ProcessThread::get_scratch_buffers (count);
3638 #if 0
3639         if (count != ChanCount::ZERO) {
3640                 assert(_scratch_buffers->available() >= count);
3641                 _scratch_buffers->set_count(count);
3642         } else {
3643                 _scratch_buffers->set_count (_scratch_buffers->available());
3644         }
3645
3646         return *_scratch_buffers;
3647 #endif
3648 }
3649
3650 BufferSet&
3651 Session::get_mix_buffers (ChanCount count)
3652 {
3653         return ProcessThread::get_mix_buffers (count);
3654 #if 0
3655         assert(_mix_buffers->available() >= count);
3656         _mix_buffers->set_count(count);
3657         return *_mix_buffers;
3658 #endif
3659 }
3660
3661 uint32_t
3662 Session::ntracks () const
3663 {
3664         uint32_t n = 0;
3665         shared_ptr<RouteList> r = routes.reader ();
3666
3667         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3668                 if (boost::dynamic_pointer_cast<Track> (*i)) {
3669                         ++n;
3670                 }
3671         }
3672
3673         return n;
3674 }
3675
3676 uint32_t
3677 Session::nbusses () const
3678 {
3679         uint32_t n = 0;
3680         shared_ptr<RouteList> r = routes.reader ();
3681
3682         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3683                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3684                         ++n;
3685                 }
3686         }
3687
3688         return n;
3689 }
3690
3691 void
3692 Session::add_automation_list(AutomationList *al)
3693 {
3694         automation_lists[al->id()] = al;
3695 }
3696
3697 nframes_t
3698 Session::compute_initial_length ()
3699 {
3700         return _engine.frame_rate() * 60 * 5;
3701 }
3702
3703 void
3704 Session::sync_order_keys (std::string const & base)
3705 {
3706         if (deletion_in_progress()) {
3707                 return;
3708         }
3709
3710         if (!Config->get_sync_all_route_ordering()) {
3711                 /* leave order keys as they are */
3712                 return;
3713         }
3714
3715         boost::shared_ptr<RouteList> r = routes.reader ();
3716
3717         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3718                 (*i)->sync_order_keys (base);
3719         }
3720
3721         Route::SyncOrderKeys (base); // EMIT SIGNAL
3722
3723         /* this might not do anything */
3724
3725         set_remote_control_ids ();
3726 }
3727
3728 /** @return true if there is at least one record-enabled diskstream, otherwise false */
3729 bool
3730 Session::have_rec_enabled_diskstream () const
3731 {
3732         return g_atomic_int_get (&_have_rec_enabled_diskstream) == 1;
3733 }
3734
3735 /** Update the state of our rec-enabled diskstreams flag */
3736 void
3737 Session::update_have_rec_enabled_diskstream ()
3738 {
3739         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
3740         DiskstreamList::iterator i = dsl->begin ();
3741         while (i != dsl->end () && (*i)->record_enabled () == false) {
3742                 ++i;
3743         }
3744
3745         int const old = g_atomic_int_get (&_have_rec_enabled_diskstream);
3746
3747         g_atomic_int_set (&_have_rec_enabled_diskstream, i != dsl->end () ? 1 : 0);
3748
3749         if (g_atomic_int_get (&_have_rec_enabled_diskstream) != old) {
3750                 RecordStateChanged (); /* EMIT SIGNAL */
3751         }
3752 }
3753
3754 void
3755 Session::listen_position_changed ()
3756 {
3757         Placement p;
3758
3759         switch (Config->get_listen_position()) {
3760         case AfterFaderListen:
3761                 p = PostFader;
3762                 break;
3763
3764         case PreFaderListen:
3765                 p = PreFader;
3766                 break;
3767         }
3768
3769         boost::shared_ptr<RouteList> r = routes.reader ();
3770
3771         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3772                 (*i)->put_monitor_send_at (p);
3773         }
3774 }
3775
3776 void
3777 Session::solo_control_mode_changed ()
3778 {
3779         /* cancel all solo or all listen when solo control mode changes */
3780
3781         if (soloing()) {
3782                 set_solo (get_routes(), false);
3783         } else if (listening()) {
3784                 set_listen (get_routes(), false);
3785         }
3786 }
3787
3788 void
3789 Session::route_group_changed ()
3790 {
3791         RouteGroupChanged (); /* EMIT SIGNAL */
3792 }
3793
3794 vector<SyncSource>
3795 Session::get_available_sync_options () const
3796 {
3797         vector<SyncSource> ret;
3798         
3799         ret.push_back (JACK);
3800
3801         if (mtc_port()) {
3802                 ret.push_back (MTC);
3803         } 
3804
3805         if (midi_clock_port()) {
3806                 ret.push_back (MIDIClock);
3807         } 
3808
3809         return ret;
3810 }
3811
3812 boost::shared_ptr<RouteList>
3813 Session::get_routes_with_regions_at (nframes64_t const p) const
3814 {
3815         shared_ptr<RouteList> r = routes.reader ();
3816         shared_ptr<RouteList> rl (new RouteList);
3817
3818         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3819                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3820                 if (!tr) {
3821                         continue;
3822                 }
3823                 
3824                 boost::shared_ptr<Diskstream> ds = tr->diskstream ();
3825                 if (!ds) {
3826                         continue;
3827                 }
3828
3829                 boost::shared_ptr<Playlist> pl = ds->playlist ();
3830                 if (!pl) {
3831                         continue;
3832                 }
3833                 
3834                 if (pl->has_region_at (p)) {
3835                         rl->push_back (*i);
3836                 }
3837         }
3838
3839         return rl;
3840 }