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