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