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