Add test for #3356.
[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         if (_step_editors > 0) {
1045                 return;
1046         }
1047
1048         g_atomic_int_set (&_record_status, Enabled);
1049
1050         /* this function is currently called from somewhere other than an RT thread.
1051            this save_state() call therefore doesn't impact anything.
1052         */
1053
1054         save_state ("", true);
1055
1056         if (_transport_speed) {
1057                 if (!config.get_punch_in()) {
1058                         enable_record ();
1059                 }
1060         } else {
1061                 MIDI::Manager::instance()->mmc()->send (MIDI::MachineControlCommand (MIDI::MachineControl::cmdRecordPause));
1062                 RecordStateChanged (); /* EMIT SIGNAL */
1063         }
1064
1065         set_dirty();
1066 }
1067
1068 nframes64_t
1069 Session::audible_frame () const
1070 {
1071         nframes64_t ret;
1072         nframes64_t tf;
1073         nframes_t offset;
1074
1075         /* the first of these two possible settings for "offset"
1076            mean that the audible frame is stationary until
1077            audio emerges from the latency compensation
1078            "pseudo-pipeline".
1079
1080            the second means that the audible frame is stationary
1081            until audio would emerge from a physical port
1082            in the absence of any plugin latency compensation
1083         */
1084
1085         offset = _worst_output_latency;
1086
1087         if (offset > current_block_size) {
1088                 offset -= current_block_size;
1089         } else {
1090                 /* XXX is this correct? if we have no external
1091                    physical connections and everything is internal
1092                    then surely this is zero? still, how
1093                    likely is that anyway?
1094                 */
1095                 offset = current_block_size;
1096         }
1097
1098         if (synced_to_jack()) {
1099                 tf = _engine.transport_frame();
1100         } else {
1101                 tf = _transport_frame;
1102         }
1103
1104         ret = tf;
1105
1106         if (!non_realtime_work_pending()) {
1107
1108                 /* MOVING */
1109
1110                 /* Check to see if we have passed the first guaranteed
1111                    audible frame past our last start position. if not,
1112                    return that last start point because in terms
1113                    of audible frames, we have not moved yet.
1114
1115                    `Start position' in this context means the time we last
1116                    either started or changed transport direction.
1117                 */
1118
1119                 if (_transport_speed > 0.0f) {
1120
1121                         if (!play_loop || !have_looped) {
1122                                 if (tf < _last_roll_or_reversal_location + offset) {
1123                                         return _last_roll_or_reversal_location;
1124                                 }
1125                         }
1126
1127
1128                         /* forwards */
1129                         ret -= offset;
1130
1131                 } else if (_transport_speed < 0.0f) {
1132
1133                         /* XXX wot? no backward looping? */
1134
1135                         if (tf > _last_roll_or_reversal_location - offset) {
1136                                 return _last_roll_or_reversal_location;
1137                         } else {
1138                                 /* backwards */
1139                                 ret += offset;
1140                         }
1141                 }
1142         }
1143
1144         return ret;
1145 }
1146
1147 void
1148 Session::set_frame_rate (nframes_t frames_per_second)
1149 {
1150         /** \fn void Session::set_frame_size(nframes_t)
1151                 the AudioEngine object that calls this guarantees
1152                 that it will not be called while we are also in
1153                 ::process(). Its fine to do things that block
1154                 here.
1155         */
1156
1157         _base_frame_rate = frames_per_second;
1158
1159         sync_time_vars();
1160
1161         Automatable::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * (0.001 * Config->get_automation_interval())));
1162
1163         clear_clicks ();
1164
1165         // XXX we need some equivalent to this, somehow
1166         // SndFileSource::setup_standard_crossfades (frames_per_second);
1167
1168         set_dirty();
1169
1170         /* XXX need to reset/reinstantiate all LADSPA plugins */
1171 }
1172
1173 void
1174 Session::set_block_size (nframes_t nframes)
1175 {
1176         /* the AudioEngine guarantees
1177            that it will not be called while we are also in
1178            ::process(). It is therefore fine to do things that block
1179            here.
1180         */
1181
1182         {
1183                 current_block_size = nframes;
1184
1185                 ensure_buffers ();
1186
1187                 boost::shared_ptr<RouteList> r = routes.reader ();
1188
1189                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1190                         (*i)->set_block_size (nframes);
1191                 }
1192
1193                 boost::shared_ptr<RouteList> rl = routes.reader ();
1194                 for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1195                         boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
1196                         if (tr) {
1197                                 tr->set_block_size (nframes);
1198                         }
1199                 }
1200
1201                 set_worst_io_latencies ();
1202         }
1203 }
1204
1205 void
1206 Session::set_default_fade (float /*steepness*/, float /*fade_msecs*/)
1207 {
1208 #if 0
1209         nframes_t fade_frames;
1210
1211         /* Don't allow fade of less 1 frame */
1212
1213         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1214
1215                 fade_msecs = 0;
1216                 fade_frames = 0;
1217
1218         } else {
1219
1220                 fade_frames = (nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1221
1222         }
1223
1224         default_fade_msecs = fade_msecs;
1225         default_fade_steepness = steepness;
1226
1227         {
1228                 // jlc, WTF is this!
1229                 Glib::RWLock::ReaderLock lm (route_lock);
1230                 AudioRegion::set_default_fade (steepness, fade_frames);
1231         }
1232
1233         set_dirty();
1234
1235         /* XXX have to do this at some point */
1236         /* foreach region using default fade, reset, then
1237            refill_all_diskstream_buffers ();
1238         */
1239 #endif
1240 }
1241
1242 struct RouteSorter {
1243     bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1244             if (r2->feeds (r1)) {
1245                     return false;
1246             } else if (r1->feeds (r2)) {
1247                     return true;
1248             } else {
1249                     if (r1->not_fed ()) {
1250                             if (r2->not_fed ()) {
1251                                     /* no ardour-based connections inbound to either route. just use signal order */
1252                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1253                             } else {
1254                                     /* r2 has connections, r1 does not; run r1 early */
1255                                     return true;
1256                             }
1257                     } else {
1258                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1259                     }
1260             }
1261     }
1262 };
1263
1264 static void
1265 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1266 {
1267         shared_ptr<Route> r2;
1268
1269         if (r1->feeds (rbase) && rbase->feeds (r1)) {
1270                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1271                 return;
1272         }
1273
1274         /* make a copy of the existing list of routes that feed r1 */
1275
1276         Route::FedBy existing (r1->fed_by());
1277                         
1278         /* for each route that feeds r1, recurse, marking it as feeding
1279            rbase as well.
1280         */
1281
1282         for (Route::FedBy::iterator i = existing.begin(); i != existing.end(); ++i) {
1283                 if (!(r2 = i->r.lock ())) {
1284                         /* (*i) went away, ignore it */
1285                         continue;
1286                 }
1287                 
1288                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1289                    base as being fed by r2
1290                 */
1291
1292                 rbase->add_fed_by (r2, i->sends_only);
1293
1294                 if (r2 != rbase) {
1295
1296                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1297                            stop here.
1298                         */
1299
1300                         if (r1->feeds (r2) && r2->feeds (r1)) {
1301                                 continue;
1302                         }
1303
1304                         /* now recurse, so that we can mark base as being fed by
1305                            all routes that feed r2
1306                         */
1307
1308                         trace_terminal (r2, rbase);
1309                 }
1310
1311         }
1312 }
1313
1314 void
1315 Session::resort_routes ()
1316 {
1317         /* don't do anything here with signals emitted
1318            by Routes while we are being destroyed.
1319         */
1320
1321         if (_state_of_the_state & Deletion) {
1322                 return;
1323         }
1324
1325         {
1326                 RCUWriter<RouteList> writer (routes);
1327                 shared_ptr<RouteList> r = writer.get_copy ();
1328                 resort_routes_using (r);
1329                 /* writer goes out of scope and forces update */
1330         }
1331
1332         //route_graph->dump(1);
1333
1334 #ifndef NDEBUG
1335         boost::shared_ptr<RouteList> rl = routes.reader ();
1336         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
1337                 DEBUG_TRACE (DEBUG::Graph, string_compose ("%1 fed by ...\n", (*i)->name()));
1338                 
1339                 const Route::FedBy& fb ((*i)->fed_by());
1340
1341                 for (Route::FedBy::const_iterator f = fb.begin(); f != fb.end(); ++f) {
1342                         boost::shared_ptr<Route> sf = f->r.lock();
1343                         if (sf) {
1344                                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 (sends only ? %2)\n", sf->name(), f->sends_only));
1345                         }
1346                 }
1347         }
1348 #endif
1349
1350 }
1351 void
1352 Session::resort_routes_using (shared_ptr<RouteList> r)
1353 {
1354         RouteList::iterator i, j;
1355
1356         for (i = r->begin(); i != r->end(); ++i) {
1357
1358                 (*i)->clear_fed_by ();
1359
1360                 for (j = r->begin(); j != r->end(); ++j) {
1361
1362                         /* although routes can feed themselves, it will
1363                            cause an endless recursive descent if we
1364                            detect it. so don't bother checking for
1365                            self-feeding.
1366                         */
1367
1368                         if (*j == *i) {
1369                                 continue;
1370                         }
1371
1372                         bool via_sends_only;
1373
1374                         if ((*j)->direct_feeds (*i, &via_sends_only)) {
1375                                 (*i)->add_fed_by (*j, via_sends_only);
1376                         }
1377                 }
1378         }
1379
1380         for (i = r->begin(); i != r->end(); ++i) {
1381                 trace_terminal (*i, *i);
1382         }
1383
1384         RouteSorter cmp;
1385         r->sort (cmp);
1386
1387         route_graph->rechain (r);
1388
1389 #ifndef NDEBUG
1390         DEBUG_TRACE (DEBUG::Graph, "Routes resorted, order follows:\n");
1391         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1392                 DEBUG_TRACE (DEBUG::Graph, string_compose ("\t%1 signal order %2\n", 
1393                                                            (*i)->name(), (*i)->order_key ("signal")));
1394         }
1395 #endif
1396
1397 }
1398
1399 /** Find the route name starting with \a base with the lowest \a id.
1400  *
1401  * Names are constructed like e.g. "Audio 3" for base="Audio" and id=3.
1402  * The available route name with the lowest ID will be used, and \a id
1403  * will be set to the ID.
1404  *
1405  * \return false if a route name could not be found, and \a track_name
1406  * and \a id do not reflect a free route name.
1407  */
1408 bool
1409 Session::find_route_name (const char* base, uint32_t& id, char* name, size_t name_len)
1410 {
1411         do {
1412                 snprintf (name, name_len, "%s %" PRIu32, base, id);
1413
1414                 if (route_by_name (name) == 0) {
1415                         return true;
1416                 }
1417
1418                 ++id;
1419
1420         } while (id < (UINT_MAX-1));
1421
1422         return false;
1423 }
1424
1425 void
1426 Session::count_existing_route_channels (ChanCount& in, ChanCount& out)
1427 {
1428         in  = ChanCount::ZERO;
1429         out = ChanCount::ZERO;
1430         shared_ptr<RouteList> r = routes.reader ();
1431         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1432                 if (!(*i)->is_hidden()) {
1433                         in += (*i)->n_inputs();
1434                         out     += (*i)->n_outputs();
1435                 }
1436         }
1437 }
1438
1439 list<boost::shared_ptr<MidiTrack> >
1440 Session::new_midi_track (TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1441 {
1442         char track_name[32];
1443         uint32_t track_id = 0;
1444         ChanCount existing_inputs;
1445         ChanCount existing_outputs;
1446         string port;
1447         RouteList new_routes;
1448         list<boost::shared_ptr<MidiTrack> > ret;
1449         uint32_t control_id;
1450
1451         count_existing_route_channels (existing_inputs, existing_outputs);
1452
1453         control_id = ntracks() + nbusses();
1454
1455         while (how_many) {
1456                 if (!find_route_name ("Midi", ++track_id, track_name, sizeof(track_name))) {
1457                         error << "cannot find name for new midi track" << endmsg;
1458                         goto failed;
1459                 }
1460
1461                 shared_ptr<MidiTrack> track;
1462                 
1463                 try {
1464                         MidiTrack* mt = new MidiTrack (*this, track_name, Route::Flag (0), mode);
1465
1466                         if (mt->init ()) {
1467                                 delete mt;
1468                                 goto failed;
1469                         }
1470
1471                         mt->use_new_diskstream();
1472
1473                         boost_debug_shared_ptr_mark_interesting (mt, "Track");
1474                         track = boost::shared_ptr<MidiTrack>(mt);
1475
1476                         if (track->input()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1477                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1478                                 goto failed;
1479                         }
1480
1481
1482                         if (track->output()->ensure_io (ChanCount(DataType::MIDI, 1), false, this)) {
1483                                 error << "cannot configure 1 in/1 out configuration for new midi track" << endmsg;
1484                                 goto failed;
1485                         }
1486
1487                         auto_connect_route (track, existing_inputs, existing_outputs);
1488
1489                         track->non_realtime_input_change();
1490
1491                         if (route_group) {
1492                                 route_group->add (track);
1493                         }
1494
1495                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1496                         track->set_remote_control_id (control_id);
1497
1498                         new_routes.push_back (track);
1499                         ret.push_back (track);
1500                 }
1501
1502                 catch (failed_constructor &err) {
1503                         error << _("Session: could not create new midi track.") << endmsg;
1504                         goto failed;
1505                 }
1506
1507                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1508
1509                         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;
1510                         goto failed;
1511                 }
1512
1513                 --how_many;
1514         }
1515
1516   failed:
1517         if (!new_routes.empty()) {
1518                 add_routes (new_routes, false);
1519                 save_state (_current_snapshot_name);
1520         }
1521
1522         return ret;
1523 }
1524
1525 /** @param connect_inputs true to connect inputs as well as outputs, false to connect just outputs */
1526 void
1527 Session::auto_connect_route (boost::shared_ptr<Route> route, ChanCount& existing_inputs, ChanCount& existing_outputs, bool connect_inputs)
1528 {
1529         /* If both inputs and outputs are auto-connected to physical ports,
1530            use the max of input and output offsets to ensure auto-connected
1531            port numbers always match up (e.g. the first audio input and the
1532            first audio output of the route will have the same physical
1533            port number).  Otherwise just use the lowest input or output
1534            offset possible.
1535         */
1536
1537         const bool in_out_physical =
1538                    (Config->get_input_auto_connect() & AutoConnectPhysical)
1539                 && (Config->get_output_auto_connect() & AutoConnectPhysical)
1540                 && connect_inputs;
1541
1542         const ChanCount in_offset = in_out_physical
1543                 ? ChanCount::max(existing_inputs, existing_outputs)
1544                 : existing_inputs;
1545
1546         const ChanCount out_offset = in_out_physical
1547                 ? ChanCount::max(existing_inputs, existing_outputs)
1548                 : existing_outputs;
1549
1550         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
1551                 vector<string> physinputs;
1552                 vector<string> physoutputs;
1553
1554                 _engine.get_physical_outputs (*t, physoutputs);
1555                 _engine.get_physical_inputs (*t, physinputs);
1556
1557                 if (!physinputs.empty() && connect_inputs) {
1558                         uint32_t nphysical_in = physinputs.size();
1559                         for (uint32_t i = 0; i < route->n_inputs().get(*t) && i < nphysical_in; ++i) {
1560                                 string port;
1561
1562                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1563                                         port = physinputs[(in_offset.get(*t) + i) % nphysical_in];
1564                                 }
1565
1566                                 if (!port.empty() && route->input()->connect (
1567                                                 route->input()->ports().port(*t, i), port, this)) {
1568                                         break;
1569                                 }
1570                         }
1571                 }
1572
1573                 if (!physoutputs.empty()) {
1574                         uint32_t nphysical_out = physoutputs.size();
1575                         for (uint32_t i = 0; i < route->n_outputs().get(*t); ++i) {
1576                                 string port;
1577
1578                                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1579                                         port = physoutputs[(out_offset.get(*t) + i) % nphysical_out];
1580                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1581                                         if (_master_out && _master_out->n_inputs().get(*t) > 0) {
1582                                                 port = _master_out->input()->ports().port(*t,
1583                                                                 i % _master_out->input()->n_ports().get(*t))->name();
1584                                         }
1585                                 }
1586
1587                                 if (!port.empty() && route->output()->connect (
1588                                                 route->output()->ports().port(*t, i), port, this)) {
1589                                         break;
1590                                 }
1591                         }
1592                 }
1593         }
1594
1595         existing_inputs += route->n_inputs();
1596         existing_outputs += route->n_outputs();
1597 }
1598
1599 list< boost::shared_ptr<AudioTrack> >
1600 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode, RouteGroup* route_group, uint32_t how_many)
1601 {
1602         char track_name[32];
1603         uint32_t track_id = 0;
1604         ChanCount existing_inputs;
1605         ChanCount existing_outputs;
1606         string port;
1607         RouteList new_routes;
1608         list<boost::shared_ptr<AudioTrack> > ret;
1609         uint32_t control_id;
1610
1611         count_existing_route_channels (existing_inputs, existing_outputs);
1612
1613         control_id = ntracks() + nbusses() + 1;
1614
1615         while (how_many) {
1616                 if (!find_route_name ("Audio", ++track_id, track_name, sizeof(track_name))) {
1617                         error << "cannot find name for new audio track" << endmsg;
1618                         goto failed;
1619                 }
1620
1621                 shared_ptr<AudioTrack> track;
1622
1623                 try {
1624                         AudioTrack* at = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1625
1626                         if (at->init ()) {
1627                                 delete at;
1628                                 goto failed;
1629                         }
1630
1631                         at->use_new_diskstream();
1632
1633                         boost_debug_shared_ptr_mark_interesting (at, "Track");
1634                         track = boost::shared_ptr<AudioTrack>(at);
1635
1636                         if (track->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1637                                 error << string_compose (
1638                                                         _("cannot configure %1 in/%2 out configuration for new audio track"),
1639                                                          input_channels, output_channels)
1640                                       << endmsg;
1641                                 goto failed;
1642                         }
1643
1644                         if (track->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1645                                 error << string_compose (
1646                                                         _("cannot configure %1 in/%2 out configuration for new audio track"),
1647                                                          input_channels, output_channels)
1648                                       << endmsg;
1649                                 goto failed;
1650                         }
1651
1652                         auto_connect_route (track, existing_inputs, existing_outputs);
1653
1654                         if (route_group) {
1655                                 route_group->add (track);
1656                         }
1657
1658                         track->non_realtime_input_change();
1659
1660                         track->DiskstreamChanged.connect_same_thread (*this, boost::bind (&Session::resort_routes, this));
1661                         track->set_remote_control_id (control_id);
1662                         ++control_id;
1663
1664                         new_routes.push_back (track);
1665                         ret.push_back (track);
1666                 }
1667
1668                 catch (failed_constructor &err) {
1669                         error << _("Session: could not create new audio track.") << endmsg;
1670                         goto failed;
1671                 }
1672
1673                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1674
1675                         error << pfe.what() << endmsg;
1676                         goto failed;
1677                 }
1678
1679                 --how_many;
1680         }
1681
1682   failed:
1683         if (!new_routes.empty()) {
1684                 add_routes (new_routes, true);
1685         }
1686
1687         return ret;
1688 }
1689
1690 void
1691 Session::set_remote_control_ids ()
1692 {
1693         RemoteModel m = Config->get_remote_model();
1694         bool emit_signal = false;
1695
1696         shared_ptr<RouteList> r = routes.reader ();
1697
1698         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1699                 if (MixerOrdered == m) {
1700                         int32_t order = (*i)->order_key(N_("signal"));
1701                         (*i)->set_remote_control_id (order+1, false);
1702                         emit_signal = true;
1703                 } else if (EditorOrdered == m) {
1704                         int32_t order = (*i)->order_key(N_("editor"));
1705                         (*i)->set_remote_control_id (order+1, false);
1706                         emit_signal = true;
1707                 } else if (UserOrdered == m) {
1708                         //do nothing ... only changes to remote id's are initiated by user
1709                 }
1710         }
1711
1712         if (emit_signal) {
1713                 Route::RemoteControlIDChange();
1714         }
1715 }
1716
1717
1718 RouteList
1719 Session::new_audio_route (bool aux, int input_channels, int output_channels, RouteGroup* route_group, uint32_t how_many)
1720 {
1721         char bus_name[32];
1722         uint32_t bus_id = 0;
1723         ChanCount existing_inputs;
1724         ChanCount existing_outputs;
1725         string port;
1726         RouteList ret;
1727         uint32_t control_id;
1728
1729         count_existing_route_channels (existing_inputs, existing_outputs);
1730
1731         control_id = ntracks() + nbusses() + 1;
1732
1733         while (how_many) {
1734                 if (!find_route_name ("Bus", ++bus_id, bus_name, sizeof(bus_name))) {
1735                         error << "cannot find name for new audio bus" << endmsg;
1736                         goto failure;
1737                 }
1738
1739                 try {
1740                         Route* rt = new Route (*this, bus_name, Route::Flag(0), DataType::AUDIO);
1741
1742                         if (rt->init ()) {
1743                                 delete rt;
1744                                 goto failure;
1745                         }
1746
1747                         boost_debug_shared_ptr_mark_interesting (rt, "Route");
1748                         shared_ptr<Route> bus (rt);
1749
1750                         if (bus->input()->ensure_io (ChanCount(DataType::AUDIO, input_channels), false, this)) {
1751                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1752                                                          input_channels, output_channels)
1753                                       << endmsg;
1754                                 goto failure;
1755                         }
1756
1757
1758                         if (bus->output()->ensure_io (ChanCount(DataType::AUDIO, output_channels), false, this)) {
1759                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1760                                                          input_channels, output_channels)
1761                                       << endmsg;
1762                                 goto failure;
1763                         }
1764
1765                         auto_connect_route (bus, existing_inputs, existing_outputs, false);
1766
1767                         if (route_group) {
1768                                 route_group->add (bus);
1769                         }
1770                         bus->set_remote_control_id (control_id);
1771                         ++control_id;
1772
1773                         if (aux) {
1774                                 bus->add_internal_return ();
1775                         }
1776
1777                         ret.push_back (bus);
1778                 }
1779
1780
1781                 catch (failed_constructor &err) {
1782                         error << _("Session: could not create new audio route.") << endmsg;
1783                         goto failure;
1784                 }
1785
1786                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1787                         error << pfe.what() << endmsg;
1788                         goto failure;
1789                 }
1790
1791
1792                 --how_many;
1793         }
1794
1795   failure:
1796         if (!ret.empty()) {
1797                 add_routes (ret, true);
1798         }
1799
1800         return ret;
1801
1802 }
1803
1804 RouteList
1805 Session::new_route_from_template (uint32_t how_many, const std::string& template_path)
1806 {
1807         char name[32];
1808         RouteList ret;
1809         uint32_t control_id;
1810         XMLTree tree;
1811         uint32_t number = 0;
1812
1813         if (!tree.read (template_path.c_str())) {
1814                 return ret;
1815         }
1816
1817         XMLNode* node = tree.root();
1818
1819         control_id = ntracks() + nbusses() + 1;
1820
1821         while (how_many) {
1822
1823                 XMLNode node_copy (*node); // make a copy so we can change the name if we need to
1824
1825                 std::string node_name = IO::name_from_state (*node_copy.children().front());
1826
1827                 /* generate a new name by adding a number to the end of the template name */
1828                 if (!find_route_name (node_name.c_str(), ++number, name, sizeof(name))) {
1829                         fatal << _("Session: UINT_MAX routes? impossible!") << endmsg;
1830                         /*NOTREACHED*/
1831                 }
1832
1833                 /* set IO children to use the new name */
1834                 XMLNodeList const & children = node_copy.children ();
1835                 for (XMLNodeList::const_iterator i = children.begin(); i != children.end(); ++i) {
1836                         if ((*i)->name() == IO::state_node_name) {
1837                                 IO::set_name_in_state (**i, name);
1838                         }
1839                 }
1840
1841                 Track::zero_diskstream_id_in_xml (node_copy);
1842
1843                 try {
1844                         shared_ptr<Route> route (XMLRouteFactory (node_copy, 3000));
1845
1846                         if (route == 0) {
1847                                 error << _("Session: cannot create track/bus from template description") << endmsg;
1848                                 goto out;
1849                         }
1850
1851                         if (boost::dynamic_pointer_cast<Track>(route)) {
1852                                 /* force input/output change signals so that the new diskstream
1853                                    picks up the configuration of the route. During session
1854                                    loading this normally happens in a different way.
1855                                 */
1856                                 route->input()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1857                                 route->output()->changed (IOChange (ConfigurationChanged|ConnectionsChanged), this);
1858                         }
1859
1860                         route->set_remote_control_id (control_id);
1861                         ++control_id;
1862
1863                         ret.push_back (route);
1864                 }
1865
1866                 catch (failed_constructor &err) {
1867                         error << _("Session: could not create new route from template") << endmsg;
1868                         goto out;
1869                 }
1870
1871                 catch (AudioEngine::PortRegistrationFailure& pfe) {
1872                         error << pfe.what() << endmsg;
1873                         goto out;
1874                 }
1875
1876                 --how_many;
1877         }
1878
1879   out:
1880         if (!ret.empty()) {
1881                 add_routes (ret, true);
1882         }
1883
1884         return ret;
1885 }
1886
1887 void
1888 Session::add_routes (RouteList& new_routes, bool save)
1889 {
1890         {
1891                 RCUWriter<RouteList> writer (routes);
1892                 shared_ptr<RouteList> r = writer.get_copy ();
1893                 r->insert (r->end(), new_routes.begin(), new_routes.end());
1894
1895
1896                 /* if there is no control out and we're not in the middle of loading,
1897                    resort the graph here. if there is a control out, we will resort
1898                    toward the end of this method. if we are in the middle of loading,
1899                    we will resort when done.
1900                 */
1901
1902                 if (!_monitor_out && IO::connecting_legal) {
1903                         resort_routes_using (r);
1904                 }
1905         }
1906
1907         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1908
1909                 boost::weak_ptr<Route> wpr (*x);
1910                 boost::shared_ptr<Route> r (*x);
1911
1912                 r->listen_changed.connect_same_thread (*this, boost::bind (&Session::route_listen_changed, this, _1, wpr));
1913                 r->solo_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_changed, this, _1, _2, wpr));
1914                 r->solo_isolated_changed.connect_same_thread (*this, boost::bind (&Session::route_solo_isolated_changed, this, _1, wpr));
1915                 r->mute_changed.connect_same_thread (*this, boost::bind (&Session::route_mute_changed, this, _1));
1916                 r->output()->changed.connect_same_thread (*this, boost::bind (&Session::set_worst_io_latencies_x, this, _1, _2));
1917                 r->processors_changed.connect_same_thread (*this, boost::bind (&Session::route_processors_changed, this, _1));
1918                 r->order_key_changed.connect_same_thread (*this, boost::bind (&Session::route_order_key_changed, this));
1919
1920                 if (r->is_master()) {
1921                         _master_out = r;
1922                 }
1923
1924                 if (r->is_monitor()) {
1925                         _monitor_out = r;
1926                 }
1927
1928                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (r);
1929                 if (tr) {
1930                         tr->PlaylistChanged.connect_same_thread (*this, boost::bind (&Session::track_playlist_changed, this, boost::weak_ptr<Track> (tr)));
1931                         track_playlist_changed (boost::weak_ptr<Track> (tr));
1932                         tr->RecordEnableChanged.connect_same_thread (*this, boost::bind (&Session::update_have_rec_enabled_track, this));
1933
1934                         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (tr);
1935                         if (mt) {
1936                                 mt->StepEditStatusChange.connect_same_thread (*this, boost::bind (&Session::step_edit_status_change, this, _1));
1937                         }
1938                 }
1939         }
1940
1941         if (_monitor_out && IO::connecting_legal) {
1942
1943                 for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1944                         if ((*x)->is_monitor()) {
1945                                 /* relax */
1946                         } else if ((*x)->is_master()) {
1947                                 /* relax */
1948                         } else {
1949                                 (*x)->listen_via (_monitor_out,
1950                                                   (Config->get_listen_position() == AfterFaderListen ? PostFader : PreFader),
1951                                                   false, false);
1952                         }
1953                 }
1954
1955                 resort_routes ();
1956         }
1957
1958         set_dirty();
1959
1960         if (save) {
1961                 save_state (_current_snapshot_name);
1962         }
1963
1964         RouteAdded (new_routes); /* EMIT SIGNAL */
1965         Route::RemoteControlIDChange (); /* EMIT SIGNAL */
1966 }
1967
1968 void
1969 Session::globally_set_send_gains_to_zero (boost::shared_ptr<Route> dest)
1970 {
1971         boost::shared_ptr<RouteList> r = routes.reader ();
1972         boost::shared_ptr<Send> s;
1973
1974         /* only tracks */
1975
1976         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1977                 if (boost::dynamic_pointer_cast<Track>(*i)) {
1978                         if ((s = (*i)->internal_send_for (dest)) != 0) {
1979                                 s->amp()->gain_control()->set_value (0.0);
1980                         }
1981                 }
1982         }
1983 }
1984
1985 void
1986 Session::globally_set_send_gains_to_unity (boost::shared_ptr<Route> dest)
1987 {
1988         boost::shared_ptr<RouteList> r = routes.reader ();
1989         boost::shared_ptr<Send> s;
1990
1991         /* only tracks */
1992
1993         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1994                 if (boost::dynamic_pointer_cast<Track>(*i)) {
1995                         if ((s = (*i)->internal_send_for (dest)) != 0) {
1996                                 s->amp()->gain_control()->set_value (1.0);
1997                         }
1998                 }
1999         }
2000 }
2001
2002 void
2003 Session::globally_set_send_gains_from_track(boost::shared_ptr<Route> dest)
2004 {
2005         boost::shared_ptr<RouteList> r = routes.reader ();
2006         boost::shared_ptr<Send> s;
2007
2008         /* only tracks */
2009
2010         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2011                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2012                         if ((s = (*i)->internal_send_for (dest)) != 0) {
2013                                 s->amp()->gain_control()->set_value ((*i)->gain_control()->get_value());
2014                         }
2015                 }
2016         }
2017 }
2018
2019 void
2020 Session::globally_add_internal_sends (boost::shared_ptr<Route> dest, Placement p)
2021 {
2022         boost::shared_ptr<RouteList> r = routes.reader ();
2023         boost::shared_ptr<RouteList> t (new RouteList);
2024
2025         /* only send tracks */
2026
2027         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2028                 if (boost::dynamic_pointer_cast<Track>(*i)) {
2029                         t->push_back (*i);
2030                 }
2031         }
2032
2033         add_internal_sends (dest, p, t);
2034 }
2035
2036 void
2037 Session::add_internal_sends (boost::shared_ptr<Route> dest, Placement p, boost::shared_ptr<RouteList> senders)
2038 {
2039         if (dest->is_monitor() || dest->is_master()) {
2040                 return;
2041         }
2042
2043         if (!dest->internal_return()) {
2044                 dest->add_internal_return();
2045         }
2046
2047         for (RouteList::iterator i = senders->begin(); i != senders->end(); ++i) {
2048
2049                 if ((*i)->is_monitor() || (*i)->is_master() || (*i) == dest) {
2050                         continue;
2051                 }
2052
2053                 (*i)->listen_via (dest, p, true, true);
2054         }
2055
2056         graph_reordered ();
2057 }
2058
2059 void
2060 Session::remove_route (shared_ptr<Route> route)
2061 {
2062         if (((route == _master_out) || (route == _monitor_out)) && !Config->get_allow_special_bus_removal()) {
2063                 return;
2064         }
2065
2066         {
2067                 RCUWriter<RouteList> writer (routes);
2068                 shared_ptr<RouteList> rs = writer.get_copy ();
2069
2070                 rs->remove (route);
2071
2072                 /* deleting the master out seems like a dumb
2073                    idea, but its more of a UI policy issue
2074                    than our concern.
2075                 */
2076
2077                 if (route == _master_out) {
2078                         _master_out = shared_ptr<Route> ();
2079                 }
2080
2081                 if (route == _monitor_out) {
2082
2083                         /* cancel control outs for all routes */
2084
2085                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
2086                                 (*r)->drop_listen (_monitor_out);
2087                         }
2088
2089                         _monitor_out.reset ();
2090                 }
2091
2092                 /* writer goes out of scope, forces route list update */
2093         }
2094
2095         update_route_solo_state ();
2096         update_session_range_location_marker ();
2097
2098         // We need to disconnect the route's inputs and outputs
2099
2100         route->input()->disconnect (0);
2101         route->output()->disconnect (0);
2102
2103         /* if the route had internal sends sending to it, remove them */
2104         if (route->internal_return()) {
2105
2106                 boost::shared_ptr<RouteList> r = routes.reader ();
2107                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2108                         boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2109                         if (s) {
2110                                 (*i)->remove_processor (s);
2111                         }
2112                 }
2113         }       
2114
2115         boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack> (route);
2116         if (mt && mt->step_editing()) {
2117                 if (_step_editors > 0) {
2118                         _step_editors--;
2119                 }
2120         }
2121
2122         update_latency_compensation (false, false);
2123         set_dirty();
2124
2125         /* Re-sort routes to remove the graph's current references to the one that is
2126          * going away, then flush old references out of the graph.
2127          */
2128
2129         resort_routes ();
2130         route_graph->clear_other_chain ();
2131
2132         /* get rid of it from the dead wood collection in the route list manager */
2133
2134         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2135
2136         routes.flush ();
2137
2138         /* try to cause everyone to drop their references */
2139
2140         route->drop_references ();
2141
2142         sync_order_keys (N_("session"));
2143
2144         Route::RemoteControlIDChange(); /* EMIT SIGNAL */
2145
2146         /* save the new state of the world */
2147
2148         if (save_state (_current_snapshot_name)) {
2149                 save_history (_current_snapshot_name);
2150         }
2151 }
2152
2153 void
2154 Session::route_mute_changed (void* /*src*/)
2155 {
2156         set_dirty ();
2157 }
2158
2159 void
2160 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2161 {
2162         boost::shared_ptr<Route> route = wpr.lock();
2163         if (!route) {
2164                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2165                 return;
2166         }
2167
2168         if (route->listening()) {
2169
2170                 if (Config->get_exclusive_solo()) {
2171                         /* new listen: disable all other listen */
2172                         shared_ptr<RouteList> r = routes.reader ();
2173                         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2174                                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2175                                         continue;
2176                                 } 
2177                                 (*i)->set_listen (false, this);
2178                         }
2179                 }
2180
2181                 _listen_cnt++;
2182
2183         } else if (_listen_cnt > 0) {
2184
2185                 _listen_cnt--;
2186         }
2187 }
2188 void
2189 Session::route_solo_isolated_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2190 {
2191         boost::shared_ptr<Route> route = wpr.lock ();
2192
2193         if (!route) {
2194                 /* should not happen */
2195                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2196                 return;
2197         }
2198         
2199         bool send_changed = false;
2200
2201         if (route->solo_isolated()) {
2202                 if (_solo_isolated_cnt == 0) {
2203                         send_changed = true;
2204                 }
2205                 _solo_isolated_cnt++;
2206         } else if (_solo_isolated_cnt > 0) {
2207                 _solo_isolated_cnt--;
2208                 if (_solo_isolated_cnt == 0) {
2209                         send_changed = true;
2210                 }
2211         }
2212
2213         if (send_changed) {
2214                 IsolatedChanged (); /* EMIT SIGNAL */
2215         }
2216 }
2217             
2218 void
2219 Session::route_solo_changed (bool self_solo_change, void* /*src*/, boost::weak_ptr<Route> wpr)
2220 {
2221         if (!self_solo_change) {
2222                 // session doesn't care about changes to soloed-by-others
2223                 return;
2224         }
2225
2226         if (solo_update_disabled) {
2227                 // We know already
2228                 return;
2229         }
2230
2231         boost::shared_ptr<Route> route = wpr.lock ();
2232
2233         if (!route) {
2234                 /* should not happen */
2235                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2236                 return;
2237         }
2238         
2239         shared_ptr<RouteList> r = routes.reader ();
2240         int32_t delta;
2241
2242         if (route->self_soloed()) {
2243                 delta = 1;
2244         } else {
2245                 delta = -1;
2246         }
2247  
2248         if (delta == 1 && Config->get_exclusive_solo()) {
2249                 /* new solo: disable all other solos */
2250                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2251                         if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2252                                 continue;
2253                         } 
2254                         (*i)->set_solo (false, this);
2255                 }
2256         }
2257
2258         solo_update_disabled = true;
2259         
2260         RouteList uninvolved;
2261         
2262         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2263                 bool via_sends_only;
2264                 bool in_signal_flow;
2265
2266                 if ((*i) == route || (*i)->solo_isolated() || (*i)->is_master() || (*i)->is_monitor() || (*i)->is_hidden()) {
2267                         continue;
2268                 } 
2269
2270                 in_signal_flow = false;
2271
2272                 if ((*i)->feeds (route, &via_sends_only)) {
2273                         if (!via_sends_only) {
2274                                 if (!route->soloed_by_others_upstream()) {
2275                                         (*i)->mod_solo_by_others_downstream (delta);
2276                                 }
2277                                 in_signal_flow = true;
2278                         }
2279                 } 
2280                 
2281                 if (route->feeds (*i, &via_sends_only)) {
2282                         (*i)->mod_solo_by_others_upstream (delta);
2283                         in_signal_flow = true;
2284                 }
2285
2286                 if (!in_signal_flow) {
2287                         uninvolved.push_back (*i);
2288                 }
2289         }
2290
2291         solo_update_disabled = false;
2292         update_route_solo_state (r);
2293
2294         /* now notify that the mute state of the routes not involved in the signal
2295            pathway of the just-solo-changed route may have altered.
2296         */
2297
2298         for (RouteList::iterator i = uninvolved.begin(); i != uninvolved.end(); ++i) {
2299                 (*i)->mute_changed (this);
2300         }
2301
2302         SoloChanged (); /* EMIT SIGNAL */
2303         set_dirty();
2304 }
2305
2306 void
2307 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2308 {
2309         /* now figure out if anything that matters is soloed (or is "listening")*/
2310
2311         bool something_soloed = false;
2312         uint32_t listeners = 0;
2313         uint32_t isolated = 0;
2314
2315         if (!r) {
2316                 r = routes.reader();
2317         }
2318
2319         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2320                 if (!(*i)->is_master() && !(*i)->is_monitor() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2321                         something_soloed = true;
2322                 }
2323
2324                 if (!(*i)->is_hidden() && (*i)->listening()) {
2325                         if (Config->get_solo_control_is_listen_control()) {
2326                                 listeners++;
2327                         } else {
2328                                 (*i)->set_listen (false, this);
2329                         }
2330                 }
2331
2332                 if ((*i)->solo_isolated()) {
2333                         isolated++;
2334                 }
2335         }
2336
2337         if (something_soloed != _non_soloed_outs_muted) {
2338                 _non_soloed_outs_muted = something_soloed;
2339                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2340         }
2341
2342         _listen_cnt = listeners;
2343
2344         if (isolated != _solo_isolated_cnt) {
2345                 _solo_isolated_cnt = isolated;
2346                 IsolatedChanged (); /* EMIT SIGNAL */
2347         }
2348 }
2349
2350 boost::shared_ptr<RouteList> 
2351 Session::get_routes_with_internal_returns() const
2352 {
2353         shared_ptr<RouteList> r = routes.reader ();
2354         boost::shared_ptr<RouteList> rl (new RouteList);
2355
2356         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2357                 if ((*i)->internal_return ()) {
2358                         rl->push_back (*i);
2359                 }
2360         }
2361         return rl;
2362 }
2363
2364 bool
2365 Session::io_name_is_legal (const std::string& name)
2366 {
2367         shared_ptr<RouteList> r = routes.reader ();
2368         
2369         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2370                 if ((*i)->name() == name) {
2371                         return false;
2372                 }
2373                 
2374                 if ((*i)->has_io_processor_named (name)) {
2375                         return false;
2376                 }
2377         }
2378         
2379         return true;
2380 }
2381
2382 shared_ptr<Route>
2383 Session::route_by_name (string name)
2384 {
2385         shared_ptr<RouteList> r = routes.reader ();
2386
2387         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2388                 if ((*i)->name() == name) {
2389                         return *i;
2390                 }
2391         }
2392
2393         return shared_ptr<Route> ((Route*) 0);
2394 }
2395
2396 shared_ptr<Route>
2397 Session::route_by_id (PBD::ID id)
2398 {
2399         shared_ptr<RouteList> r = routes.reader ();
2400
2401         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2402                 if ((*i)->id() == id) {
2403                         return *i;
2404                 }
2405         }
2406
2407         return shared_ptr<Route> ((Route*) 0);
2408 }
2409
2410 shared_ptr<Route>
2411 Session::route_by_remote_id (uint32_t id)
2412 {
2413         shared_ptr<RouteList> r = routes.reader ();
2414
2415         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2416                 if ((*i)->remote_control_id() == id) {
2417                         return *i;
2418                 }
2419         }
2420
2421         return shared_ptr<Route> ((Route*) 0);
2422 }
2423
2424 /** If either end of the session range location marker lies inside the current
2425  *  session extent, move it to the corresponding session extent.
2426  */
2427 void
2428 Session::update_session_range_location_marker ()
2429 {
2430         if (_state_of_the_state & Loading) {
2431                 return;
2432         }
2433
2434         pair<nframes_t, nframes_t> const ext = get_extent ();
2435
2436         if (_session_range_location == 0) {
2437                 /* we don't have a session range yet; use this one (provided it is valid) */
2438                 if (ext.first != max_frames) {
2439                         add_session_range_location (ext.first, ext.second);
2440                 }
2441         } else {
2442                 /* update the existing session range */
2443                 if (ext.first < _session_range_location->start()) {
2444                         _session_range_location->set_start (ext.first);
2445                         set_dirty ();
2446                 }
2447                 
2448                 if (ext.second > _session_range_location->end()) {
2449                         _session_range_location->set_end (ext.second);
2450                         set_dirty ();
2451                 }
2452                 
2453         }
2454 }
2455
2456 /** @return Extent of the session's contents; if the session is empty, the first value of
2457  *  the pair will equal max_frames.
2458  */
2459 pair<nframes_t, nframes_t>
2460 Session::get_extent () const
2461 {
2462         pair<nframes_t, nframes_t> ext (max_frames, 0);
2463         
2464         boost::shared_ptr<RouteList> rl = routes.reader ();
2465         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2466                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2467                 if (!tr || tr->destructive()) {
2468                         // ignore tape tracks when getting extents
2469                         continue;
2470                 }
2471
2472                 pair<nframes_t, nframes_t> e = tr->playlist()->get_extent ();
2473                 if (e.first < ext.first) {
2474                         ext.first = e.first;
2475                 }
2476                 if (e.second > ext.second) {
2477                         ext.second = e.second;
2478                 }
2479         }
2480
2481         return ext;
2482 }
2483
2484 /* Region management */
2485
2486 boost::shared_ptr<Region>
2487 Session::find_whole_file_parent (boost::shared_ptr<Region const> child) const
2488 {
2489         const RegionFactory::RegionMap& regions (RegionFactory::regions());
2490         RegionFactory::RegionMap::const_iterator i;
2491         boost::shared_ptr<Region> region;
2492
2493         Glib::Mutex::Lock lm (region_lock);
2494
2495         for (i = regions.begin(); i != regions.end(); ++i) {
2496
2497                 region = i->second;
2498
2499                 if (region->whole_file()) {
2500
2501                         if (child->source_equivalent (region)) {
2502                                 return region;
2503                         }
2504                 }
2505         }
2506
2507         return boost::shared_ptr<Region> ();
2508 }
2509
2510 int
2511 Session::destroy_sources (list<boost::shared_ptr<Source> > srcs)
2512 {
2513         set<boost::shared_ptr<Region> > relevant_regions;
2514
2515         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ++s) {
2516                 RegionFactory::get_regions_using_source (*s, relevant_regions);
2517         }
2518
2519         cerr << "There are " << relevant_regions.size() << " using " << srcs.size() << " sources" << endl;
2520
2521         for (set<boost::shared_ptr<Region> >::iterator r = relevant_regions.begin(); r != relevant_regions.end(); ) {
2522                 set<boost::shared_ptr<Region> >::iterator tmp;
2523
2524                 tmp = r;
2525                 ++tmp;
2526
2527                 cerr << "Cleanup " << (*r)->name() << " UC = " << (*r).use_count() << endl;
2528
2529                 playlists->destroy_region (*r);
2530                 RegionFactory::map_remove (*r);
2531
2532                 (*r)->drop_sources ();
2533                 (*r)->drop_references ();
2534
2535                 cerr << "\tdone UC = " << (*r).use_count() << endl;
2536
2537                 relevant_regions.erase (r);
2538
2539                 r = tmp;
2540         }
2541
2542         for (list<boost::shared_ptr<Source> >::iterator s = srcs.begin(); s != srcs.end(); ) {
2543                 
2544                 {
2545                         Glib::Mutex::Lock ls (source_lock);
2546                         /* remove from the main source list */
2547                         sources.erase ((*s)->id());
2548                 }
2549
2550                 (*s)->mark_for_remove ();
2551                 (*s)->drop_references ();
2552
2553                 s = srcs.erase (s);
2554         }
2555
2556         return 0;
2557 }
2558
2559 int
2560 Session::remove_last_capture ()
2561 {
2562         list<boost::shared_ptr<Source> > srcs;
2563
2564         boost::shared_ptr<RouteList> rl = routes.reader ();
2565         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
2566                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
2567                 if (!tr) {
2568                         continue;
2569                 }
2570                 
2571                 list<boost::shared_ptr<Source> >& l = tr->last_capture_sources();
2572
2573                 if (!l.empty()) {
2574                         srcs.insert (srcs.end(), l.begin(), l.end());
2575                         l.clear ();
2576                 }
2577         }
2578
2579         destroy_sources (srcs);
2580
2581         save_state (_current_snapshot_name);
2582
2583         return 0;
2584 }
2585
2586 /* Source Management */
2587
2588 void
2589 Session::add_source (boost::shared_ptr<Source> source)
2590 {
2591         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2592         pair<SourceMap::iterator,bool> result;
2593
2594         entry.first = source->id();
2595         entry.second = source;
2596
2597         {
2598                 Glib::Mutex::Lock lm (source_lock);
2599                 result = sources.insert (entry);
2600         }
2601
2602         if (result.second) {
2603
2604                 /* yay, new source */
2605
2606                 set_dirty();
2607
2608                 boost::shared_ptr<AudioFileSource> afs;
2609                 
2610                 if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2611                         if (Config->get_auto_analyse_audio()) {
2612                                 Analyser::queue_source_for_analysis (source, false);
2613                         }
2614                 }
2615         }
2616 }
2617
2618 void
2619 Session::remove_source (boost::weak_ptr<Source> src)
2620 {
2621         SourceMap::iterator i;
2622         boost::shared_ptr<Source> source = src.lock();
2623
2624         if (!source) {
2625                 return;
2626         }
2627
2628         {
2629                 Glib::Mutex::Lock lm (source_lock);
2630
2631                 if ((i = sources.find (source->id())) != sources.end()) {
2632                         cerr << "Removing source " << source->name() << endl;
2633                         sources.erase (i);
2634                 }
2635         }
2636
2637         if (!_state_of_the_state & InCleanup) {
2638
2639                 /* save state so we don't end up with a session file
2640                    referring to non-existent sources.
2641                 */
2642
2643                 save_state (_current_snapshot_name);
2644         }
2645 }
2646
2647 boost::shared_ptr<Source>
2648 Session::source_by_id (const PBD::ID& id)
2649 {
2650         Glib::Mutex::Lock lm (source_lock);
2651         SourceMap::iterator i;
2652         boost::shared_ptr<Source> source;
2653
2654         if ((i = sources.find (id)) != sources.end()) {
2655                 source = i->second;
2656         }
2657
2658         return source;
2659 }
2660
2661 boost::shared_ptr<Source>
2662 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2663 {
2664         Glib::Mutex::Lock lm (source_lock);
2665
2666         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2667                 boost::shared_ptr<AudioFileSource> afs
2668                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2669
2670                 if (afs && afs->path() == path && chn == afs->channel()) {
2671                         return afs;
2672                 }
2673         }
2674         return boost::shared_ptr<Source>();
2675 }
2676
2677
2678 string
2679 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
2680 {
2681         string look_for;
2682         string old_basename = PBD::basename_nosuffix (oldname);
2683         string new_legalized = legalize_for_path (newname);
2684
2685         /* note: we know (or assume) the old path is already valid */
2686
2687         if (destructive) {
2688
2689                 /* destructive file sources have a name of the form:
2690
2691                     /path/to/Tnnnn-NAME(%[LR])?.wav
2692
2693                     the task here is to replace NAME with the new name.
2694                 */
2695
2696                 string dir;
2697                 string prefix;
2698                 string::size_type dash;
2699
2700                 dir = Glib::path_get_dirname (path);
2701                 path = Glib::path_get_basename (path);
2702
2703                 /* '-' is not a legal character for the NAME part of the path */
2704
2705                 if ((dash = path.find_last_of ('-')) == string::npos) {
2706                         return "";
2707                 }
2708
2709                 prefix = path.substr (0, dash);
2710
2711                 path += prefix;
2712                 path += '-';
2713                 path += new_legalized;
2714                 path += native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
2715
2716                 path = Glib::build_filename (dir, path);
2717
2718         } else {
2719
2720                 /* non-destructive file sources have a name of the form:
2721
2722                     /path/to/NAME-nnnnn(%[LR])?.ext
2723
2724                     the task here is to replace NAME with the new name.
2725                 */
2726
2727                 string dir;
2728                 string suffix;
2729                 string::size_type dash;
2730                 string::size_type postfix;
2731
2732                 dir = Glib::path_get_dirname (path);
2733                 path = Glib::path_get_basename (path);
2734
2735                 /* '-' is not a legal character for the NAME part of the path */
2736
2737                 if ((dash = path.find_last_of ('-')) == string::npos) {
2738                         return "";
2739                 }
2740
2741                 suffix = path.substr (dash+1);
2742
2743                 // Suffix is now everything after the dash. Now we need to eliminate
2744                 // the nnnnn part, which is done by either finding a '%' or a '.'
2745
2746                 postfix = suffix.find_last_of ("%");
2747                 if (postfix == string::npos) {
2748                         postfix = suffix.find_last_of ('.');
2749                 }
2750
2751                 if (postfix != string::npos) {
2752                         suffix = suffix.substr (postfix);
2753                 } else {
2754                         error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
2755                         return "";
2756                 }
2757
2758                 const uint32_t limit = 10000;
2759                 char buf[PATH_MAX+1];
2760
2761                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2762
2763                         snprintf (buf, sizeof(buf), "%s-%u%s", newname.c_str(), cnt, suffix.c_str());
2764
2765                         if (!matching_unsuffixed_filename_exists_in (dir, buf)) {
2766                                 path = Glib::build_filename (dir, buf);
2767                                 break;
2768                         }
2769
2770                         path = "";
2771                 }
2772
2773                 if (path.empty()) {
2774                         fatal << string_compose (_("FATAL ERROR! Could not find a suitable version of %1 for a rename"),
2775                                                  newname) << endl;
2776                         /*NOTREACHED*/
2777                 }
2778         }
2779
2780         return path;
2781 }
2782
2783 /** Return the full path (in some session directory) for a new within-session source.
2784  * \a name must be a session-unique name that does not contain slashes
2785  *         (e.g. as returned by new_*_source_name)
2786  */
2787 string
2788 Session::new_source_path_from_name (DataType type, const string& name, bool as_stub)
2789 {
2790         assert(name.find("/") == string::npos);
2791
2792         SessionDirectory sdir(get_best_session_directory_for_new_source());
2793
2794         sys::path p;
2795         if (type == DataType::AUDIO) {
2796                 p = (as_stub ? sdir.sound_stub_path() : sdir.sound_path());
2797         } else if (type == DataType::MIDI) {
2798                 p = (as_stub ? sdir.midi_stub_path() : sdir.midi_path());
2799         } else {
2800                 error << "Unknown source type, unable to create file path" << endmsg;
2801                 return "";
2802         }
2803
2804         p /= name;
2805         return p.to_string();
2806 }
2807
2808 Glib::ustring
2809 Session::peak_path (Glib::ustring base) const
2810 {
2811         sys::path peakfile_path(_session_dir->peak_path());
2812         peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2813         return peakfile_path.to_string();
2814 }
2815
2816 /** Return a unique name based on \a base for a new internal audio source */
2817 string
2818 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
2819 {
2820         uint32_t cnt;
2821         char buf[PATH_MAX+1];
2822         const uint32_t limit = 10000;
2823         string legalized;
2824         string ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
2825
2826         buf[0] = '\0';
2827         legalized = legalize_for_path (base);
2828
2829         // Find a "version" of the base name that doesn't exist in any of the possible directories.
2830         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2831
2832                 vector<space_and_path>::iterator i;
2833                 uint32_t existing = 0;
2834
2835                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2836
2837                         if (destructive) {
2838
2839                                 if (nchan < 2) {
2840                                         snprintf (buf, sizeof(buf), "T%04d-%s%s",
2841                                                   cnt, legalized.c_str(), ext.c_str());
2842                                 } else if (nchan == 2) {
2843                                         if (chan == 0) {
2844                                                 snprintf (buf, sizeof(buf), "T%04d-%s%%L%s",
2845                                                           cnt, legalized.c_str(), ext.c_str());
2846                                         } else {
2847                                                 snprintf (buf, sizeof(buf), "T%04d-%s%%R%s",
2848                                                           cnt, legalized.c_str(), ext.c_str());
2849                                         }
2850                                 } else if (nchan < 26) {
2851                                         snprintf (buf, sizeof(buf), "T%04d-%s%%%c%s",
2852                                                   cnt, legalized.c_str(), 'a' + chan, ext.c_str());
2853                                 } else {
2854                                         snprintf (buf, sizeof(buf), "T%04d-%s%s",
2855                                                   cnt, legalized.c_str(), ext.c_str());
2856                                 }
2857
2858                         } else {
2859
2860                                 if (nchan < 2) {
2861                                         snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
2862                                 } else if (nchan == 2) {
2863                                         if (chan == 0) {
2864                                                 snprintf (buf, sizeof(buf), "%s-%u%%L%s", legalized.c_str(), cnt, ext.c_str());
2865                                         } else {
2866                                                 snprintf (buf, sizeof(buf), "%s-%u%%R%s", legalized.c_str(), cnt, ext.c_str());
2867                                         }
2868                                 } else if (nchan < 26) {
2869                                         snprintf (buf, sizeof(buf), "%s-%u%%%c%s", legalized.c_str(), cnt, 'a' + chan, ext.c_str());
2870                                 } else {
2871                                         snprintf (buf, sizeof(buf), "%s-%u%s", legalized.c_str(), cnt, ext.c_str());
2872                                 }
2873                         }
2874
2875                         SessionDirectory sdir((*i).path);
2876
2877                         string spath = sdir.sound_path().to_string();
2878                         string spath_stubs = sdir.sound_stub_path().to_string();
2879
2880                         /* note that we search *without* the extension so that
2881                            we don't end up both "Audio 1-1.wav" and "Audio 1-1.caf" 
2882                            in the event that this new name is required for
2883                            a file format change.
2884                         */
2885
2886                         if (matching_unsuffixed_filename_exists_in (spath, buf) ||
2887                             matching_unsuffixed_filename_exists_in (spath_stubs, buf)) {
2888                                 existing++;
2889                                 break;
2890                         }
2891                 }
2892
2893                 if (existing == 0) {
2894                         break;
2895                 }
2896
2897                 if (cnt > limit) {
2898                         error << string_compose(
2899                                         _("There are already %1 recordings for %2, which I consider too many."),
2900                                         limit, base) << endmsg;
2901                         destroy ();
2902                         throw failed_constructor();
2903                 }
2904         }
2905         
2906         return Glib::path_get_basename (buf);
2907 }
2908
2909 /** Create a new within-session audio source */
2910 boost::shared_ptr<AudioFileSource>
2911 Session::create_audio_source_for_session (size_t n_chans, string const & n, uint32_t chan, bool destructive, bool as_stub)
2912 {
2913         const string name    = new_audio_source_name (n, n_chans, chan, destructive);
2914         const string path    = new_source_path_from_name(DataType::AUDIO, name, as_stub);
2915
2916         return boost::dynamic_pointer_cast<AudioFileSource> (
2917                 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
2918 }
2919
2920 /** Return a unique name based on \a base for a new internal MIDI source */
2921 string
2922 Session::new_midi_source_name (const string& base)
2923 {
2924         uint32_t cnt;
2925         char buf[PATH_MAX+1];
2926         const uint32_t limit = 10000;
2927         string legalized;
2928
2929         buf[0] = '\0';
2930         legalized = legalize_for_path (base);
2931
2932         // Find a "version" of the file name that doesn't exist in any of the possible directories.
2933         for (cnt = 1; cnt <= limit; ++cnt) {
2934
2935                 vector<space_and_path>::iterator i;
2936                 uint32_t existing = 0;
2937
2938                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2939
2940                         SessionDirectory sdir((*i).path);
2941
2942                         sys::path p = sdir.midi_path();
2943                         p /= legalized;
2944
2945                         snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
2946
2947                         if (sys::exists (buf)) {
2948                                 existing++;
2949                         }
2950                 }
2951
2952                 if (existing == 0) {
2953                         break;
2954                 }
2955
2956                 if (cnt > limit) {
2957                         error << string_compose(
2958                                         _("There are already %1 recordings for %2, which I consider too many."),
2959                                         limit, base) << endmsg;
2960                         destroy ();
2961                         throw failed_constructor();
2962                 }
2963         }
2964
2965         return Glib::path_get_basename(buf);
2966 }
2967
2968
2969 /** Create a new within-session MIDI source */
2970 boost::shared_ptr<MidiSource>
2971 Session::create_midi_source_for_session (Track* track, string const & n, bool as_stub)
2972 {
2973         /* try to use the existing write source for the track, to keep numbering sane 
2974          */
2975
2976         if (track) {
2977                 /*MidiTrack* mt = dynamic_cast<Track*> (track);
2978                 assert (mt);
2979                 */
2980
2981                 list<boost::shared_ptr<Source> > l = track->steal_write_sources ();
2982                 
2983                 if (!l.empty()) {
2984                         assert (boost::dynamic_pointer_cast<MidiSource> (l.front()));
2985                         return boost::dynamic_pointer_cast<MidiSource> (l.front());
2986                 }
2987         }
2988
2989         const string name = new_midi_source_name (n);
2990         const string path = new_source_path_from_name (DataType::MIDI, name, as_stub);
2991
2992         return boost::dynamic_pointer_cast<SMFSource> (
2993                         SourceFactory::createWritable (
2994                                         DataType::MIDI, *this, path, false, frame_rate()));
2995 }
2996
2997
2998 void
2999 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3000 {
3001         if (playlist->hidden()) {
3002                 return;
3003         }
3004
3005         playlists->add (playlist);
3006
3007         if (unused) {
3008                 playlist->release();
3009         }
3010
3011         set_dirty();
3012 }
3013
3014 void
3015 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3016 {
3017         if (_state_of_the_state & Deletion) {
3018                 return;
3019         }
3020
3021         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3022
3023         if (!playlist) {
3024                 return;
3025         }
3026
3027         playlists->remove (playlist);
3028
3029         set_dirty();
3030 }
3031
3032 void
3033 Session::set_audition (boost::shared_ptr<Region> r)
3034 {
3035         pending_audition_region = r;
3036         add_post_transport_work (PostTransportAudition);
3037         _butler->schedule_transport_work ();
3038 }
3039
3040 void
3041 Session::audition_playlist ()
3042 {
3043         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3044         ev->region.reset ();
3045         queue_event (ev);
3046 }
3047
3048 void
3049 Session::non_realtime_set_audition ()
3050 {
3051         if (!pending_audition_region) {
3052                 auditioner->audition_current_playlist ();
3053         } else {
3054                 auditioner->audition_region (pending_audition_region);
3055                 pending_audition_region.reset ();
3056         }
3057         AuditionActive (true); /* EMIT SIGNAL */
3058 }
3059
3060 void
3061 Session::audition_region (boost::shared_ptr<Region> r)
3062 {
3063         SessionEvent* ev = new SessionEvent (SessionEvent::Audition, SessionEvent::Add, SessionEvent::Immediate, 0, 0.0);
3064         ev->region = r;
3065         queue_event (ev);
3066 }
3067
3068 void
3069 Session::cancel_audition ()
3070 {
3071         if (auditioner->auditioning()) {
3072                 auditioner->cancel_audition ();
3073                 AuditionActive (false); /* EMIT SIGNAL */
3074         }
3075 }
3076
3077 bool
3078 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3079 {
3080         if (a->is_monitor()) { 
3081                 return true;
3082         }
3083         if (b->is_monitor()) {
3084                 return false;
3085         }
3086         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3087 }
3088
3089 bool
3090 Session::is_auditioning () const
3091 {
3092         /* can be called before we have an auditioner object */
3093         if (auditioner) {
3094                 return auditioner->auditioning();
3095         } else {
3096                 return false;
3097         }
3098 }
3099
3100 void
3101 Session::graph_reordered ()
3102 {
3103         /* don't do this stuff if we are setting up connections
3104            from a set_state() call or creating new tracks. Ditto for deletion.
3105         */
3106
3107         if (_state_of_the_state & (InitialConnecting|Deletion)) {
3108                 return;
3109         }
3110
3111         /* every track/bus asked for this to be handled but it was deferred because
3112            we were connecting. do it now.
3113         */
3114
3115         request_input_change_handling ();
3116
3117         resort_routes ();
3118
3119         /* force all diskstreams to update their capture offset values to
3120            reflect any changes in latencies within the graph.
3121         */
3122
3123         boost::shared_ptr<RouteList> rl = routes.reader ();
3124         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3125                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3126                 if (tr) {
3127                         tr->set_capture_offset ();
3128                 }
3129         }
3130 }
3131
3132 nframes_t
3133 Session::available_capture_duration ()
3134 {
3135         float sample_bytes_on_disk = 4.0; // keep gcc happy
3136
3137         switch (config.get_native_file_data_format()) {
3138         case FormatFloat:
3139                 sample_bytes_on_disk = 4.0;
3140                 break;
3141
3142         case FormatInt24:
3143                 sample_bytes_on_disk = 3.0;
3144                 break;
3145
3146         case FormatInt16:
3147                 sample_bytes_on_disk = 2.0;
3148                 break;
3149
3150         default:
3151                 /* impossible, but keep some gcc versions happy */
3152                 fatal << string_compose (_("programming error: %1"),
3153                                          X_("illegal native file data format"))
3154                       << endmsg;
3155                 /*NOTREACHED*/
3156         }
3157
3158         double scale = 4096.0 / sample_bytes_on_disk;
3159
3160         if (_total_free_4k_blocks * scale > (double) max_frames) {
3161                 return max_frames;
3162         }
3163
3164         return (nframes_t) floor (_total_free_4k_blocks * scale);
3165 }
3166
3167 void
3168 Session::add_bundle (shared_ptr<Bundle> bundle)
3169 {
3170         {
3171                 RCUWriter<BundleList> writer (_bundles);
3172                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3173                 b->push_back (bundle);
3174         }
3175
3176         BundleAdded (bundle); /* EMIT SIGNAL */
3177
3178         set_dirty();
3179 }
3180
3181 void
3182 Session::remove_bundle (shared_ptr<Bundle> bundle)
3183 {
3184         bool removed = false;
3185
3186         {
3187                 RCUWriter<BundleList> writer (_bundles);
3188                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3189                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3190
3191                 if (i != b->end()) {
3192                         b->erase (i);
3193                         removed = true;
3194                 }
3195         }
3196
3197         if (removed) {
3198                  BundleRemoved (bundle); /* EMIT SIGNAL */
3199         }
3200
3201         set_dirty();
3202 }
3203
3204 shared_ptr<Bundle>
3205 Session::bundle_by_name (string name) const
3206 {
3207         boost::shared_ptr<BundleList> b = _bundles.reader ();
3208
3209         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3210                 if ((*i)->name() == name) {
3211                         return* i;
3212                 }
3213         }
3214
3215         return boost::shared_ptr<Bundle> ();
3216 }
3217
3218 void
3219 Session::tempo_map_changed (const PropertyChange&)
3220 {
3221         clear_clicks ();
3222
3223         playlists->update_after_tempo_map_change ();
3224
3225         set_dirty ();
3226 }
3227
3228 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3229  * the given count with the current block size.
3230  */
3231 void
3232 Session::ensure_buffers (ChanCount howmany)
3233 {
3234         BufferManager::ensure_buffers (howmany);
3235 }
3236
3237 void
3238 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3239 {
3240         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3241                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3242         }
3243 }
3244
3245 uint32_t
3246 Session::next_insert_id ()
3247 {
3248         /* this doesn't really loop forever. just think about it */
3249
3250         while (true) {
3251                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3252                         if (!insert_bitset[n]) {
3253                                 insert_bitset[n] = true;
3254                                 return n;
3255
3256                         }
3257                 }
3258
3259                 /* none available, so resize and try again */
3260
3261                 insert_bitset.resize (insert_bitset.size() + 16, false);
3262         }
3263 }
3264
3265 uint32_t
3266 Session::next_send_id ()
3267 {
3268         /* this doesn't really loop forever. just think about it */
3269
3270         while (true) {
3271                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3272                         if (!send_bitset[n]) {
3273                                 send_bitset[n] = true;
3274                                 return n;
3275
3276                         }
3277                 }
3278
3279                 /* none available, so resize and try again */
3280
3281                 send_bitset.resize (send_bitset.size() + 16, false);
3282         }
3283 }
3284
3285 uint32_t
3286 Session::next_return_id ()
3287 {
3288         /* this doesn't really loop forever. just think about it */
3289
3290         while (true) {
3291                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3292                         if (!return_bitset[n]) {
3293                                 return_bitset[n] = true;
3294                                 return n;
3295
3296                         }
3297                 }
3298
3299                 /* none available, so resize and try again */
3300
3301                 return_bitset.resize (return_bitset.size() + 16, false);
3302         }
3303 }
3304
3305 void
3306 Session::mark_send_id (uint32_t id)
3307 {
3308         if (id >= send_bitset.size()) {
3309                 send_bitset.resize (id+16, false);
3310         }
3311         if (send_bitset[id]) {
3312                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3313         }
3314         send_bitset[id] = true;
3315 }
3316
3317 void
3318 Session::mark_return_id (uint32_t id)
3319 {
3320         if (id >= return_bitset.size()) {
3321                 return_bitset.resize (id+16, false);
3322         }
3323         if (return_bitset[id]) {
3324                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
3325         }
3326         return_bitset[id] = true;
3327 }
3328
3329 void
3330 Session::mark_insert_id (uint32_t id)
3331 {
3332         if (id >= insert_bitset.size()) {
3333                 insert_bitset.resize (id+16, false);
3334         }
3335         if (insert_bitset[id]) {
3336                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3337         }
3338         insert_bitset[id] = true;
3339 }
3340
3341 void
3342 Session::unmark_send_id (uint32_t id)
3343 {
3344         if (id < send_bitset.size()) {
3345                 send_bitset[id] = false;
3346         }
3347 }
3348
3349 void
3350 Session::unmark_return_id (uint32_t id)
3351 {
3352         if (id < return_bitset.size()) {
3353                 return_bitset[id] = false;
3354         }
3355 }
3356
3357 void
3358 Session::unmark_insert_id (uint32_t id)
3359 {
3360         if (id < insert_bitset.size()) {
3361                 insert_bitset[id] = false;
3362         }
3363 }
3364
3365
3366 /* Named Selection management */
3367
3368 boost::shared_ptr<NamedSelection>
3369 Session::named_selection_by_name (string name)
3370 {
3371         Glib::Mutex::Lock lm (named_selection_lock);
3372         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3373                 if ((*i)->name == name) {
3374                         return *i;
3375                 }
3376         }
3377         return boost::shared_ptr<NamedSelection>();
3378 }
3379
3380 void
3381 Session::add_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3382 {
3383         {
3384                 Glib::Mutex::Lock lm (named_selection_lock);
3385                 named_selections.insert (named_selections.begin(), named_selection);
3386         }
3387
3388         set_dirty();
3389
3390         NamedSelectionAdded (); /* EMIT SIGNAL */
3391 }
3392
3393 void
3394 Session::remove_named_selection (boost::shared_ptr<NamedSelection> named_selection)
3395 {
3396         bool removed = false;
3397
3398         {
3399                 Glib::Mutex::Lock lm (named_selection_lock);
3400
3401                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3402
3403                 if (i != named_selections.end()) {
3404                         named_selections.erase (i);
3405                         set_dirty();
3406                         removed = true;
3407                 }
3408         }
3409
3410         if (removed) {
3411                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3412         }
3413 }
3414
3415 void
3416 Session::reset_native_file_format ()
3417 {
3418         boost::shared_ptr<RouteList> rl = routes.reader ();
3419         for (RouteList::iterator i = rl->begin(); i != rl->end(); ++i) {
3420                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3421                 if (tr) {
3422                         /* don't save state as we do this, there's no point
3423                          */
3424
3425                         _state_of_the_state = StateOfTheState (_state_of_the_state|InCleanup);
3426                         tr->reset_write_sources (false);
3427                         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InCleanup);
3428                 }
3429         }
3430 }
3431
3432 bool
3433 Session::route_name_unique (string n) const
3434 {
3435         shared_ptr<RouteList> r = routes.reader ();
3436
3437         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3438                 if ((*i)->name() == n) {
3439                         return false;
3440                 }
3441         }
3442
3443         return true;
3444 }
3445
3446 bool
3447 Session::route_name_internal (string n) const
3448 {
3449         if (auditioner && auditioner->name() == n) {
3450                 return true;
3451         }
3452
3453         if (_click_io && _click_io->name() == n) {
3454                 return true;
3455         }
3456
3457         return false;
3458 }
3459
3460 int
3461 Session::freeze_all (InterThreadInfo& itt)
3462 {
3463         shared_ptr<RouteList> r = routes.reader ();
3464
3465         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3466
3467                 boost::shared_ptr<Track> t;
3468
3469                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3470                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3471                            of every track.
3472                         */
3473                         t->freeze_me (itt);
3474                 }
3475         }
3476
3477         return 0;
3478 }
3479
3480 boost::shared_ptr<Region>
3481 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
3482                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
3483                           InterThreadInfo& itt, bool enable_processing)
3484 {
3485         boost::shared_ptr<Region> result;
3486         boost::shared_ptr<Playlist> playlist;
3487         boost::shared_ptr<AudioFileSource> fsource;
3488         uint32_t x;
3489         char buf[PATH_MAX+1];
3490         ChanCount nchans(track.n_channels());
3491         nframes_t position;
3492         nframes_t this_chunk;
3493         nframes_t to_do;
3494         BufferSet buffers;
3495         SessionDirectory sdir(get_best_session_directory_for_new_source ());
3496         const string sound_dir = sdir.sound_path().to_string();
3497         nframes_t len = end - start;
3498         string ext;
3499
3500         if (end <= start) {
3501                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
3502                                          end, start) << endmsg;
3503                 return result;
3504         }
3505
3506         const nframes_t chunk_size = (256 * 1024)/4;
3507
3508         // block all process callback handling
3509
3510         block_processing ();
3511
3512         /* call tree *MUST* hold route_lock */
3513
3514         if ((playlist = track.playlist()) == 0) {
3515                 goto out;
3516         }
3517
3518         /* external redirects will be a problem */
3519
3520         if (track.has_external_redirects()) {
3521                 goto out;
3522         }
3523
3524         ext = native_header_format_extension (config.get_native_file_header_format(), DataType::AUDIO);
3525
3526         for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
3527
3528                 for (x = 0; x < 99999; ++x) {
3529                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 "%s", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1, ext.c_str());
3530                         if (access (buf, F_OK) != 0) {
3531                                 break;
3532                         }
3533                 }
3534
3535                 if (x == 99999) {
3536                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3537                         goto out;
3538                 }
3539
3540                 try {
3541                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
3542                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
3543                 }
3544
3545                 catch (failed_constructor& err) {
3546                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3547                         goto out;
3548                 }
3549
3550                 srcs.push_back (fsource);
3551         }
3552
3553         /* XXX need to flush all redirects */
3554
3555         position = start;
3556         to_do = len;
3557
3558         /* create a set of reasonably-sized buffers */
3559         buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
3560         buffers.set_count(nchans);
3561
3562         for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3563                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3564                 if (afs)
3565                         afs->prepare_for_peakfile_writes ();
3566         }
3567
3568         while (to_do && !itt.cancel) {
3569
3570                 this_chunk = min (to_do, chunk_size);
3571
3572                 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
3573                         goto out;
3574                 }
3575
3576                 uint32_t n = 0;
3577                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3578                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3579
3580                         if (afs) {
3581                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
3582                                         goto out;
3583                                 }
3584                         }
3585                 }
3586
3587                 start += this_chunk;
3588                 to_do -= this_chunk;
3589
3590                 itt.progress = (float) (1.0 - ((double) to_do / len));
3591
3592         }
3593
3594         if (!itt.cancel) {
3595
3596                 time_t now;
3597                 struct tm* xnow;
3598                 time (&now);
3599                 xnow = localtime (&now);
3600
3601                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3602                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3603
3604                         if (afs) {
3605                                 afs->update_header (position, *xnow, now);
3606                                 afs->flush_header ();
3607                         }
3608                 }
3609
3610                 /* construct a region to represent the bounced material */
3611
3612                 PropertyList plist;
3613                 
3614                 plist.add (Properties::start, 0);
3615                 plist.add (Properties::length, srcs.front()->length(srcs.front()->timeline_position()));
3616                 plist.add (Properties::name, region_name_from_path (srcs.front()->name(), true));
3617                 
3618                 result = RegionFactory::create (srcs, plist);
3619                            
3620         }
3621
3622   out:
3623         if (!result) {
3624                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3625                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3626
3627                         if (afs) {
3628                                 afs->mark_for_remove ();
3629                         }
3630
3631                         (*src)->drop_references ();
3632                 }
3633
3634         } else {
3635                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3636                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3637
3638                         if (afs)
3639                                 afs->done_with_peakfile_writes ();
3640                 }
3641         }
3642
3643         unblock_processing ();
3644
3645         return result;
3646 }
3647
3648 gain_t*
3649 Session::gain_automation_buffer() const
3650 {
3651         return ProcessThread::gain_automation_buffer ();
3652 }
3653
3654 pan_t**
3655 Session::pan_automation_buffer() const
3656 {
3657         return ProcessThread::pan_automation_buffer ();
3658 }
3659
3660 BufferSet&
3661 Session::get_silent_buffers (ChanCount count)
3662 {
3663         return ProcessThread::get_silent_buffers (count);
3664 #if 0
3665         assert(_silent_buffers->available() >= count);
3666         _silent_buffers->set_count(count);
3667
3668         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3669                 for (size_t i= 0; i < count.get(*t); ++i) {
3670                         _silent_buffers->get(*t, i).clear();
3671                 }
3672         }
3673
3674         return *_silent_buffers;
3675 #endif
3676 }
3677
3678 BufferSet&
3679 Session::get_scratch_buffers (ChanCount count)
3680 {
3681         return ProcessThread::get_scratch_buffers (count);
3682 #if 0
3683         if (count != ChanCount::ZERO) {
3684                 assert(_scratch_buffers->available() >= count);
3685                 _scratch_buffers->set_count(count);
3686         } else {
3687                 _scratch_buffers->set_count (_scratch_buffers->available());
3688         }
3689
3690         return *_scratch_buffers;
3691 #endif
3692 }
3693
3694 BufferSet&
3695 Session::get_mix_buffers (ChanCount count)
3696 {
3697         return ProcessThread::get_mix_buffers (count);
3698 #if 0
3699         assert(_mix_buffers->available() >= count);
3700         _mix_buffers->set_count(count);
3701         return *_mix_buffers;
3702 #endif
3703 }
3704
3705 uint32_t
3706 Session::ntracks () const
3707 {
3708         uint32_t n = 0;
3709         shared_ptr<RouteList> r = routes.reader ();
3710
3711         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3712                 if (boost::dynamic_pointer_cast<Track> (*i)) {
3713                         ++n;
3714                 }
3715         }
3716
3717         return n;
3718 }
3719
3720 uint32_t
3721 Session::nbusses () const
3722 {
3723         uint32_t n = 0;
3724         shared_ptr<RouteList> r = routes.reader ();
3725
3726         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3727                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
3728                         ++n;
3729                 }
3730         }
3731
3732         return n;
3733 }
3734
3735 void
3736 Session::add_automation_list(AutomationList *al)
3737 {
3738         automation_lists[al->id()] = al;
3739 }
3740
3741 void
3742 Session::sync_order_keys (std::string const & base)
3743 {
3744         if (deletion_in_progress()) {
3745                 return;
3746         }
3747
3748         if (!Config->get_sync_all_route_ordering()) {
3749                 /* leave order keys as they are */
3750                 return;
3751         }
3752
3753         boost::shared_ptr<RouteList> r = routes.reader ();
3754
3755         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3756                 (*i)->sync_order_keys (base);
3757         }
3758
3759         Route::SyncOrderKeys (base); // EMIT SIGNAL
3760
3761         /* this might not do anything */
3762
3763         set_remote_control_ids ();
3764 }
3765
3766 /** @return true if there is at least one record-enabled track, otherwise false */
3767 bool
3768 Session::have_rec_enabled_track () const
3769 {
3770         return g_atomic_int_get (&_have_rec_enabled_track) == 1;
3771 }
3772
3773 /** Update the state of our rec-enabled tracks flag */
3774 void
3775 Session::update_have_rec_enabled_track ()
3776 {
3777         boost::shared_ptr<RouteList> rl = routes.reader ();
3778         RouteList::iterator i = rl->begin();
3779         while (i != rl->end ()) {
3780
3781                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3782                 if (tr && tr->record_enabled ()) {
3783                         break;
3784                 }
3785                 
3786                 ++i;
3787         }
3788
3789         int const old = g_atomic_int_get (&_have_rec_enabled_track);
3790
3791         g_atomic_int_set (&_have_rec_enabled_track, i != rl->end () ? 1 : 0);
3792
3793         if (g_atomic_int_get (&_have_rec_enabled_track) != old) {
3794                 RecordStateChanged (); /* EMIT SIGNAL */
3795         }
3796 }
3797
3798 void
3799 Session::listen_position_changed ()
3800 {
3801         Placement p;
3802
3803         switch (Config->get_listen_position()) {
3804         case AfterFaderListen:
3805                 p = PostFader;
3806                 break;
3807
3808         case PreFaderListen:
3809                 p = PreFader;
3810                 break;
3811         }
3812
3813         boost::shared_ptr<RouteList> r = routes.reader ();
3814
3815         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3816                 (*i)->put_monitor_send_at (p);
3817         }
3818 }
3819
3820 void
3821 Session::solo_control_mode_changed ()
3822 {
3823         /* cancel all solo or all listen when solo control mode changes */
3824
3825         if (soloing()) {
3826                 set_solo (get_routes(), false);
3827         } else if (listening()) {
3828                 set_listen (get_routes(), false);
3829         }
3830 }
3831
3832 /** Called when anything about any of our route groups changes (membership, state etc.) */
3833 void
3834 Session::route_group_changed ()
3835 {
3836         RouteGroupChanged (); /* EMIT SIGNAL */
3837 }
3838
3839 vector<SyncSource>
3840 Session::get_available_sync_options () const
3841 {
3842         vector<SyncSource> ret;
3843         
3844         ret.push_back (JACK);
3845         ret.push_back (MTC);
3846         ret.push_back (MIDIClock);
3847
3848         return ret;
3849 }
3850
3851 boost::shared_ptr<RouteList>
3852 Session::get_routes_with_regions_at (nframes64_t const p) const
3853 {
3854         shared_ptr<RouteList> r = routes.reader ();
3855         shared_ptr<RouteList> rl (new RouteList);
3856
3857         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3858                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
3859                 if (!tr) {
3860                         continue;
3861                 }
3862                 
3863                 boost::shared_ptr<Playlist> pl = tr->playlist ();
3864                 if (!pl) {
3865                         continue;
3866                 }
3867                 
3868                 if (pl->has_region_at (p)) {
3869                         rl->push_back (*i);
3870                 }
3871         }
3872
3873         return rl;
3874 }
3875
3876 void
3877 Session::goto_end ()
3878 {
3879         if (_session_range_location) {
3880                 request_locate (_session_range_location->end(), false);
3881         } else {
3882                 request_locate (0, false);
3883         }
3884 }
3885
3886 void
3887 Session::goto_start ()
3888 {
3889         if (_session_range_location) {
3890                 request_locate (_session_range_location->start(), false);
3891         } else {
3892                 request_locate (0, false);
3893         }
3894 }
3895
3896 void
3897 Session::set_session_start (nframes_t start)
3898 {
3899         if (_session_range_location) {
3900                 _session_range_location->set_start (start);
3901         } else {
3902                 add_session_range_location (start, start);
3903         }
3904 }
3905               
3906 void
3907 Session::set_session_end (nframes_t end)
3908 {
3909         if (_session_range_location) {
3910                 _session_range_location->set_end (end);
3911         } else {
3912                 add_session_range_location (end, end);
3913         }
3914 }
3915
3916 nframes_t
3917 Session::current_start_frame () const
3918 {
3919         return _session_range_location ? _session_range_location->start() : 0;
3920 }
3921
3922 nframes_t
3923 Session::current_end_frame () const
3924 {
3925         return _session_range_location ? _session_range_location->end() : 0;
3926 }
3927
3928 void
3929 Session::add_session_range_location (nframes_t start, nframes_t end)
3930 {
3931         _session_range_location = new Location (start, end, _("session"), Location::IsSessionRange);
3932         _locations.add (_session_range_location);
3933 }
3934
3935 /** Called when one of our routes' order keys has changed */
3936 void
3937 Session::route_order_key_changed ()
3938 {
3939         RouteOrderKeyChanged (); /* EMIT SIGNAL */
3940 }
3941
3942 void
3943 Session::step_edit_status_change (bool yn)
3944 {
3945         bool send = false;
3946
3947         bool val = false;
3948         if (yn) {
3949                 send = (_step_editors == 0);
3950                 val = true;
3951
3952                 _step_editors++;
3953         } else {
3954                 send = (_step_editors == 1);
3955                 val = false;
3956
3957                 if (_step_editors > 0) {
3958                         _step_editors--;
3959                 }
3960         }
3961
3962         if (send) {
3963                 StepEditStatusChange (val);
3964         }
3965 }