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