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