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