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