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