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