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