Revert completely mystifying stupidity in a previous patch of mine, and (properly...
[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         /* if the route had internal sends sending to it, remove them */
2386         if (route->internal_return()) {
2387
2388                 boost::shared_ptr<RouteList> r = routes.reader ();
2389                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2390                         boost::shared_ptr<Send> s = (*i)->internal_send_for (route);
2391                         if (s) {
2392                                 (*i)->remove_processor (s);
2393                         }
2394                 }
2395         }       
2396
2397         update_latency_compensation (false, false);
2398         set_dirty();
2399
2400         /* get rid of it from the dead wood collection in the route list manager */
2401
2402         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2403
2404         routes.flush ();
2405
2406         /* try to cause everyone to drop their references */
2407
2408         route->drop_references ();
2409
2410         sync_order_keys (N_("session"));
2411
2412         /* save the new state of the world */
2413
2414         if (save_state (_current_snapshot_name)) {
2415                 save_history (_current_snapshot_name);
2416         }
2417 }
2418
2419 void
2420 Session::route_mute_changed (void* /*src*/)
2421 {
2422         set_dirty ();
2423 }
2424
2425 void
2426 Session::route_listen_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2427 {
2428         boost::shared_ptr<Route> route = wpr.lock();
2429         if (!route) {
2430                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2431                 return;
2432         }
2433
2434         if (route->listening()) {
2435                 _listen_cnt++;
2436         } else if (_listen_cnt > 0) {
2437                 _listen_cnt--;
2438         }
2439 }
2440
2441 void
2442 Session::route_solo_changed (void* /*src*/, boost::weak_ptr<Route> wpr)
2443 {
2444         if (solo_update_disabled) {
2445                 // We know already
2446                 return;
2447         }
2448
2449         boost::shared_ptr<Route> route = wpr.lock ();
2450
2451         if (!route) {
2452                 /* should not happen */
2453                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2454                 return;
2455         }
2456
2457         shared_ptr<RouteList> r = routes.reader ();
2458         int32_t delta;
2459
2460         if (route->self_soloed()) {
2461                 delta = 1;
2462         } else {
2463                 delta = -1;
2464         }
2465
2466         /* now mod the solo level of all other routes except master & control outs
2467            so that they will be silent if appropriate.
2468         */
2469
2470         solo_update_disabled = true;
2471
2472         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2473                 bool via_sends_only;
2474
2475
2476                 if ((*i) == route || !(*i)->solo_isolated() || !(*i)->is_master() || !(*i)->is_control() || (*i)->is_hidden()) {
2477                         continue;
2478                 } else if ((*i)->feeds (route, &via_sends_only)) {
2479                         if (!via_sends_only) {
2480                                 (*i)->mod_solo_by_others (delta);
2481                         }
2482                 } 
2483         }
2484
2485         /* make sure master is never muted by solo */
2486
2487         if (_master_out && route != _master_out && _master_out->soloed_by_others() == 0 && !_master_out->soloed()) {
2488                 _master_out->mod_solo_by_others (1);
2489         }
2490  
2491         /* ditto for control outs make sure master is never muted by solo */
2492
2493         if (_control_out && route != _control_out && _control_out && _control_out->soloed_by_others() == 0) {
2494                 _control_out->mod_solo_by_others (1);
2495         }
2496
2497         solo_update_disabled = false;
2498         update_route_solo_state (r);
2499         SoloChanged (); /* EMIT SIGNAL */
2500         set_dirty();
2501 }
2502
2503 void
2504 Session::update_route_solo_state (boost::shared_ptr<RouteList> r)
2505 {
2506         /* now figure out if anything that matters is soloed */
2507
2508         bool something_soloed = false;
2509
2510         if (!r) {
2511                 r = routes.reader();
2512         }
2513
2514         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2515                 if (!(*i)->is_master() && !(*i)->is_control() && !(*i)->is_hidden() && (*i)->self_soloed()) {
2516                         something_soloed = true;
2517                         break;
2518                 }
2519         }
2520
2521         if (something_soloed != _non_soloed_outs_muted) {
2522                 _non_soloed_outs_muted = something_soloed;
2523                 SoloActive (_non_soloed_outs_muted); /* EMIT SIGNAL */
2524         }
2525 }
2526
2527 boost::shared_ptr<RouteList> 
2528 Session::get_routes_with_internal_returns() const
2529 {
2530         shared_ptr<RouteList> r = routes.reader ();
2531         boost::shared_ptr<RouteList> rl (new RouteList);
2532
2533         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2534                 if ((*i)->internal_return ()) {
2535                         rl->push_back (*i);
2536                 }
2537         }
2538         return rl;
2539 }
2540
2541 shared_ptr<Route>
2542 Session::route_by_name (string name)
2543 {
2544         shared_ptr<RouteList> r = routes.reader ();
2545
2546         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2547                 if ((*i)->name() == name) {
2548                         return *i;
2549                 }
2550         }
2551
2552         return shared_ptr<Route> ((Route*) 0);
2553 }
2554
2555 shared_ptr<Route>
2556 Session::route_by_id (PBD::ID id)
2557 {
2558         shared_ptr<RouteList> r = routes.reader ();
2559
2560         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2561                 if ((*i)->id() == id) {
2562                         return *i;
2563                 }
2564         }
2565
2566         return shared_ptr<Route> ((Route*) 0);
2567 }
2568
2569 shared_ptr<Route>
2570 Session::route_by_remote_id (uint32_t id)
2571 {
2572         shared_ptr<RouteList> r = routes.reader ();
2573
2574         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2575                 if ((*i)->remote_control_id() == id) {
2576                         return *i;
2577                 }
2578         }
2579
2580         return shared_ptr<Route> ((Route*) 0);
2581 }
2582
2583 void
2584 Session::find_current_end ()
2585 {
2586         if (_state_of_the_state & Loading) {
2587                 return;
2588         }
2589
2590         nframes_t max = get_maximum_extent ();
2591
2592         if (max > end_location->end()) {
2593                 end_location->set_end (max);
2594                 set_dirty();
2595                 DurationChanged(); /* EMIT SIGNAL */
2596         }
2597 }
2598
2599 nframes_t
2600 Session::get_maximum_extent () const
2601 {
2602         nframes_t max = 0;
2603         nframes_t me;
2604
2605         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2606
2607         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2608                 if ((*i)->destructive())  //ignore tape tracks when getting max extents
2609                         continue;
2610                 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2611                 if ((me = pl->get_maximum_extent()) > max) {
2612                         max = me;
2613                 }
2614         }
2615
2616         return max;
2617 }
2618
2619 boost::shared_ptr<Diskstream>
2620 Session::diskstream_by_name (string name)
2621 {
2622         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2623
2624         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2625                 if ((*i)->name() == name) {
2626                         return *i;
2627                 }
2628         }
2629
2630         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2631 }
2632
2633 boost::shared_ptr<Diskstream>
2634 Session::diskstream_by_id (const PBD::ID& id)
2635 {
2636         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2637
2638         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2639                 if ((*i)->id() == id) {
2640                         return *i;
2641                 }
2642         }
2643
2644         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2645 }
2646
2647 /* Region management */
2648
2649 string
2650 Session::new_region_name (string old)
2651 {
2652         string::size_type last_period;
2653         uint32_t number;
2654         string::size_type len = old.length() + 64;
2655         char buf[len];
2656
2657         if ((last_period = old.find_last_of ('.')) == string::npos) {
2658
2659                 /* no period present - add one explicitly */
2660
2661                 old += '.';
2662                 last_period = old.length() - 1;
2663                 number = 0;
2664
2665         } else {
2666
2667                 number = atoi (old.substr (last_period+1).c_str());
2668
2669         }
2670
2671         while (number < (UINT_MAX-1)) {
2672
2673                 RegionList::const_iterator i;
2674                 string sbuf;
2675
2676                 number++;
2677
2678                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2679                 sbuf = buf;
2680
2681                 for (i = regions.begin(); i != regions.end(); ++i) {
2682                         if (i->second->name() == sbuf) {
2683                                 break;
2684                         }
2685                 }
2686
2687                 if (i == regions.end()) {
2688                         break;
2689                 }
2690         }
2691
2692         if (number != (UINT_MAX-1)) {
2693                 return buf;
2694         }
2695
2696         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2697         return old;
2698 }
2699
2700 int
2701 Session::region_name (string& result, string base, bool newlevel)
2702 {
2703         char buf[16];
2704         string subbase;
2705
2706         if (base.find("/") != string::npos) {
2707                 base = base.substr(base.find_last_of("/") + 1);
2708         }
2709
2710         if (base == "") {
2711
2712                 Glib::Mutex::Lock lm (region_lock);
2713
2714                 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2715                 result = "region.";
2716                 result += buf;
2717
2718         } else {
2719
2720                 if (newlevel) {
2721                         subbase = base;
2722                 } else {
2723                         string::size_type pos;
2724
2725                         pos = base.find_last_of ('.');
2726
2727                         /* pos may be npos, but then we just use entire base */
2728
2729                         subbase = base.substr (0, pos);
2730
2731                 }
2732
2733                 {
2734                         Glib::Mutex::Lock lm (region_lock);
2735
2736                         map<string,uint32_t>::iterator x;
2737
2738                         result = subbase;
2739
2740                         if ((x = region_name_map.find (subbase)) == region_name_map.end()) {
2741                                 result += ".1";
2742                                 region_name_map[subbase] = 1;
2743                         } else {
2744                                 x->second++;
2745                                 snprintf (buf, sizeof (buf), ".%d", x->second);
2746
2747                                 result += buf;
2748                         }
2749                 }
2750         }
2751
2752         return 0;
2753 }
2754
2755 void
2756 Session::add_region (boost::shared_ptr<Region> region)
2757 {
2758         vector<boost::shared_ptr<Region> > v;
2759         v.push_back (region);
2760         add_regions (v);
2761 }
2762
2763 void
2764 Session::add_regions (vector<boost::shared_ptr<Region> >& new_regions)
2765 {
2766         bool added = false;
2767
2768         {
2769                 Glib::Mutex::Lock lm (region_lock);
2770
2771                 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2772
2773                         boost::shared_ptr<Region> region = *ii;
2774
2775                         if (region == 0) {
2776
2777                                 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2778
2779                         } else {
2780
2781                                 RegionList::iterator x;
2782
2783                                 for (x = regions.begin(); x != regions.end(); ++x) {
2784
2785                                         if (region->region_list_equivalent (x->second)) {
2786                                                 break;
2787                                         }
2788                                 }
2789
2790                                 if (x == regions.end()) {
2791
2792                                         pair<RegionList::key_type,RegionList::mapped_type> entry;
2793
2794                                         entry.first = region->id();
2795                                         entry.second = region;
2796
2797                                         pair<RegionList::iterator,bool> x = regions.insert (entry);
2798
2799                                         if (!x.second) {
2800                                                 return;
2801                                         }
2802
2803                                         added = true;
2804                                 }
2805                         }
2806                 }
2807         }
2808
2809         /* mark dirty because something has changed even if we didn't
2810            add the region to the region list.
2811         */
2812
2813         set_dirty ();
2814
2815         if (added) {
2816
2817                 vector<boost::weak_ptr<Region> > v;
2818                 boost::shared_ptr<Region> first_r;
2819
2820                 for (vector<boost::shared_ptr<Region> >::iterator ii = new_regions.begin(); ii != new_regions.end(); ++ii) {
2821
2822                         boost::shared_ptr<Region> region = *ii;
2823
2824                         if (region == 0) {
2825
2826                                 error << _("Session::add_region() ignored a null region. Warning: you might have lost a region.") << endmsg;
2827
2828                         } else {
2829                                 v.push_back (region);
2830
2831                                 if (!first_r) {
2832                                         first_r = region;
2833                                 }
2834                         }
2835
2836                         region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2837                         region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2838
2839                         update_region_name_map (region);
2840                 }
2841
2842                 if (!v.empty()) {
2843                         RegionsAdded (v); /* EMIT SIGNAL */
2844                 }
2845         }
2846 }
2847
2848 void
2849 Session::update_region_name_map (boost::shared_ptr<Region> region)
2850 {
2851         string::size_type last_period = region->name().find_last_of ('.');
2852
2853         if (last_period != string::npos && last_period < region->name().length() - 1) {
2854
2855                 string base = region->name().substr (0, last_period);
2856                 string number = region->name().substr (last_period+1);
2857                 map<string,uint32_t>::iterator x;
2858
2859                 /* note that if there is no number, we get zero from atoi,
2860                    which is just fine
2861                 */
2862
2863                 region_name_map[base] = atoi (number);
2864         }
2865 }
2866
2867 void
2868 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2869 {
2870         boost::shared_ptr<Region> region (weak_region.lock ());
2871
2872         if (!region) {
2873                 return;
2874         }
2875
2876         if (what_changed & Region::HiddenChanged) {
2877                 /* relay hidden changes */
2878                 RegionHiddenChange (region);
2879         }
2880
2881         if (what_changed & NameChanged) {
2882                 update_region_name_map (region);
2883         }
2884 }
2885
2886 void
2887 Session::remove_region (boost::weak_ptr<Region> weak_region)
2888 {
2889         RegionList::iterator i;
2890         boost::shared_ptr<Region> region (weak_region.lock ());
2891
2892         if (!region) {
2893                 return;
2894         }
2895
2896         bool removed = false;
2897
2898         {
2899                 Glib::Mutex::Lock lm (region_lock);
2900
2901                 if ((i = regions.find (region->id())) != regions.end()) {
2902                         regions.erase (i);
2903                         removed = true;
2904                 }
2905         }
2906
2907         /* mark dirty because something has changed even if we didn't
2908            remove the region from the region list.
2909         */
2910
2911         set_dirty();
2912
2913         if (removed) {
2914                  RegionRemoved(region); /* EMIT SIGNAL */
2915         }
2916 }
2917
2918 boost::shared_ptr<Region>
2919 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2920 {
2921         RegionList::iterator i;
2922         boost::shared_ptr<Region> region;
2923
2924         Glib::Mutex::Lock lm (region_lock);
2925
2926         for (i = regions.begin(); i != regions.end(); ++i) {
2927
2928                 region = i->second;
2929
2930                 if (region->whole_file()) {
2931
2932                         if (child->source_equivalent (region)) {
2933                                 return region;
2934                         }
2935                 }
2936         }
2937
2938         return boost::shared_ptr<Region> ();
2939 }
2940
2941 void
2942 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2943 {
2944         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2945                 (*i)->get_region_list_equivalent_regions (region, result);
2946 }
2947
2948 int
2949 Session::destroy_region (boost::shared_ptr<Region> region)
2950 {
2951         vector<boost::shared_ptr<Source> > srcs;
2952
2953         {
2954                 if (region->playlist()) {
2955                         region->playlist()->destroy_region (region);
2956                 }
2957
2958                 for (uint32_t n = 0; n < region->n_channels(); ++n) {
2959                         srcs.push_back (region->source (n));
2960                 }
2961         }
2962
2963         region->drop_references ();
2964
2965         for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2966
2967                         (*i)->mark_for_remove ();
2968                         (*i)->drop_references ();
2969
2970                         cerr << "source was not used by any playlist\n";
2971         }
2972
2973         return 0;
2974 }
2975
2976 int
2977 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2978 {
2979         for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2980                 destroy_region (*i);
2981         }
2982         return 0;
2983 }
2984
2985 int
2986 Session::remove_last_capture ()
2987 {
2988         list<boost::shared_ptr<Region> > r;
2989
2990         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2991
2992         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2993                 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2994
2995                 if (!l.empty()) {
2996                         r.insert (r.end(), l.begin(), l.end());
2997                         l.clear ();
2998                 }
2999         }
3000
3001         destroy_regions (r);
3002
3003         save_state (_current_snapshot_name);
3004
3005         return 0;
3006 }
3007
3008 int
3009 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
3010 {
3011         remove_region (r);
3012         return 0;
3013 }
3014
3015 /* Source Management */
3016
3017 void
3018 Session::add_source (boost::shared_ptr<Source> source)
3019 {
3020         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
3021         pair<SourceMap::iterator,bool> result;
3022
3023         entry.first = source->id();
3024         entry.second = source;
3025
3026         {
3027                 Glib::Mutex::Lock lm (source_lock);
3028                 result = sources.insert (entry);
3029         }
3030
3031         if (result.second) {
3032                 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
3033                 set_dirty();
3034         }
3035
3036         boost::shared_ptr<AudioFileSource> afs;
3037
3038         if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
3039                 if (Config->get_auto_analyse_audio()) {
3040                         Analyser::queue_source_for_analysis (source, false);
3041                 }
3042         }
3043 }
3044
3045 void
3046 Session::remove_source (boost::weak_ptr<Source> src)
3047 {
3048         SourceMap::iterator i;
3049         boost::shared_ptr<Source> source = src.lock();
3050
3051         if (!source) {
3052                 return;
3053         }
3054
3055         {
3056                 Glib::Mutex::Lock lm (source_lock);
3057
3058                 if ((i = sources.find (source->id())) != sources.end()) {
3059                         sources.erase (i);
3060                 }
3061         }
3062
3063         if (!_state_of_the_state & InCleanup) {
3064
3065                 /* save state so we don't end up with a session file
3066                    referring to non-existent sources.
3067                 */
3068
3069                 save_state (_current_snapshot_name);
3070         }
3071 }
3072
3073 /** Return the number of playlists (not regions) that contain @a src */
3074 uint32_t
3075 Session::source_use_count (boost::shared_ptr<const Source> src) const
3076 {
3077         uint32_t count = 0;
3078         for (PlaylistList::const_iterator p = playlists.begin(); p != playlists.end(); ++p) {
3079                 for (Playlist::RegionList::const_iterator r = (*p)->region_list().begin();
3080                                 r != (*p)->region_list().end(); ++r) {
3081                         if ((*r)->uses_source(src)) {
3082                                 ++count;
3083                                 break;
3084                         }
3085                 }
3086         }
3087         return count;
3088 }
3089
3090 boost::shared_ptr<Source>
3091 Session::source_by_id (const PBD::ID& id)
3092 {
3093         Glib::Mutex::Lock lm (source_lock);
3094         SourceMap::iterator i;
3095         boost::shared_ptr<Source> source;
3096
3097         if ((i = sources.find (id)) != sources.end()) {
3098                 source = i->second;
3099         }
3100
3101         return source;
3102 }
3103
3104 boost::shared_ptr<Source>
3105 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
3106 {
3107         Glib::Mutex::Lock lm (source_lock);
3108
3109         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
3110                 cerr << "comparing " << path << " with " << i->second->name() << endl;
3111                 boost::shared_ptr<AudioFileSource> afs
3112                         = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
3113
3114                 if (afs && afs->path() == path && chn == afs->channel()) {
3115                         return afs;
3116                 }
3117         }
3118         return boost::shared_ptr<Source>();
3119 }
3120
3121
3122 string
3123 Session::change_source_path_by_name (string path, string oldname, string newname, bool destructive)
3124 {
3125         string look_for;
3126         string old_basename = PBD::basename_nosuffix (oldname);
3127         string new_legalized = legalize_for_path (newname);
3128
3129         /* note: we know (or assume) the old path is already valid */
3130
3131         if (destructive) {
3132
3133                 /* destructive file sources have a name of the form:
3134
3135                     /path/to/Tnnnn-NAME(%[LR])?.wav
3136
3137                     the task here is to replace NAME with the new name.
3138                 */
3139
3140                 /* find last slash */
3141
3142                 string dir;
3143                 string prefix;
3144                 string::size_type slash;
3145                 string::size_type dash;
3146
3147                 if ((slash = path.find_last_of ('/')) == string::npos) {
3148                         return "";
3149                 }
3150
3151                 dir = path.substr (0, slash+1);
3152
3153                 /* '-' is not a legal character for the NAME part of the path */
3154
3155                 if ((dash = path.find_last_of ('-')) == string::npos) {
3156                         return "";
3157                 }
3158
3159                 prefix = path.substr (slash+1, dash-(slash+1));
3160
3161                 path = dir;
3162                 path += prefix;
3163                 path += '-';
3164                 path += new_legalized;
3165                 path += ".wav";  /* XXX gag me with a spoon */
3166
3167         } else {
3168
3169                 /* non-destructive file sources have a name of the form:
3170
3171                     /path/to/NAME-nnnnn(%[LR])?.ext
3172
3173                     the task here is to replace NAME with the new name.
3174                 */
3175
3176                 string dir;
3177                 string suffix;
3178                 string::size_type slash;
3179                 string::size_type dash;
3180                 string::size_type postfix;
3181
3182                 /* find last slash */
3183
3184                 if ((slash = path.find_last_of ('/')) == string::npos) {
3185                         return "";
3186                 }
3187
3188                 dir = path.substr (0, slash+1);
3189
3190                 /* '-' is not a legal character for the NAME part of the path */
3191
3192                 if ((dash = path.find_last_of ('-')) == string::npos) {
3193                         return "";
3194                 }
3195
3196                 suffix = path.substr (dash+1);
3197
3198                 // Suffix is now everything after the dash. Now we need to eliminate
3199                 // the nnnnn part, which is done by either finding a '%' or a '.'
3200
3201                 postfix = suffix.find_last_of ("%");
3202                 if (postfix == string::npos) {
3203                         postfix = suffix.find_last_of ('.');
3204                 }
3205
3206                 if (postfix != string::npos) {
3207                         suffix = suffix.substr (postfix);
3208                 } else {
3209                         error << "Logic error in Session::change_source_path_by_name(), please report" << endl;
3210                         return "";
3211                 }
3212
3213                 const uint32_t limit = 10000;
3214                 char buf[PATH_MAX+1];
3215
3216                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3217
3218                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3219
3220                         if (access (buf, F_OK) != 0) {
3221                                 path = buf;
3222                                 break;
3223                         }
3224                         path = "";
3225                 }
3226
3227                 if (path == "") {
3228                         error << "FATAL ERROR! Could not find a " << endl;
3229                 }
3230
3231         }
3232
3233         return path;
3234 }
3235
3236 /** Return the full path (in some session directory) for a new within-session source.
3237  * \a name must be a session-unique name that does not contain slashes
3238  *         (e.g. as returned by new_*_source_name)
3239  */
3240 string
3241 Session::new_source_path_from_name (DataType type, const string& name)
3242 {
3243         assert(name.find("/") == string::npos);
3244
3245         SessionDirectory sdir(get_best_session_directory_for_new_source());
3246
3247         sys::path p;
3248         if (type == DataType::AUDIO) {
3249                 p = sdir.sound_path();
3250         } else if (type == DataType::MIDI) {
3251                 p = sdir.midi_path();
3252         } else {
3253                 error << "Unknown source type, unable to create file path" << endmsg;
3254                 return "";
3255         }
3256
3257         p /= name;
3258         return p.to_string();
3259 }
3260
3261 Glib::ustring
3262 Session::peak_path (Glib::ustring base) const
3263 {
3264         sys::path peakfile_path(_session_dir->peak_path());
3265         peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
3266         return peakfile_path.to_string();
3267 }
3268
3269 /** Return a unique name based on \a base for a new internal audio source */
3270 string
3271 Session::new_audio_source_name (const string& base, uint32_t nchan, uint32_t chan, bool destructive)
3272 {
3273         string spath;
3274         uint32_t cnt;
3275         char buf[PATH_MAX+1];
3276         const uint32_t limit = 10000;
3277         string legalized;
3278
3279         buf[0] = '\0';
3280         legalized = legalize_for_path (base);
3281
3282         // Find a "version" of the base name that doesn't exist in any of the possible directories.
3283         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
3284
3285                 vector<space_and_path>::iterator i;
3286                 uint32_t existing = 0;
3287
3288                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3289
3290                         SessionDirectory sdir((*i).path);
3291
3292                         spath = sdir.sound_path().to_string();
3293
3294                         if (destructive) {
3295
3296                                 if (nchan < 2) {
3297                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
3298                                                         spath.c_str(), cnt, legalized.c_str());
3299                                 } else if (nchan == 2) {
3300                                         if (chan == 0) {
3301                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav",
3302                                                                 spath.c_str(), cnt, legalized.c_str());
3303                                         } else {
3304                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav",
3305                                                                 spath.c_str(), cnt, legalized.c_str());
3306                                         }
3307                                 } else if (nchan < 26) {
3308                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav",
3309                                                         spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3310                                 } else {
3311                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav",
3312                                                         spath.c_str(), cnt, legalized.c_str());
3313                                 }
3314
3315                         } else {
3316
3317                                 spath += '/';
3318                                 spath += legalized;
3319
3320                                 if (nchan < 2) {
3321                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3322                                 } else if (nchan == 2) {
3323                                         if (chan == 0) {
3324                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3325                                         } else {
3326                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3327                                         }
3328                                 } else if (nchan < 26) {
3329                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3330                                 } else {
3331                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3332                                 }
3333                         }
3334
3335                         if (sys::exists(buf)) {
3336                                 existing++;
3337                         }
3338
3339                 }
3340
3341                 if (existing == 0) {
3342                         break;
3343                 }
3344
3345                 if (cnt > limit) {
3346                         error << string_compose(
3347                                         _("There are already %1 recordings for %2, which I consider too many."),
3348                                         limit, base) << endmsg;
3349                         destroy ();
3350                         throw failed_constructor();
3351                 }
3352         }
3353
3354         return Glib::path_get_basename(buf);
3355 }
3356
3357 /** Create a new within-session audio source */
3358 boost::shared_ptr<AudioFileSource>
3359 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3360 {
3361         const size_t n_chans = ds.n_channels().n_audio();
3362         const string name    = new_audio_source_name (ds.name(), n_chans, chan, destructive);
3363         const string path    = new_source_path_from_name(DataType::AUDIO, name);
3364
3365         return boost::dynamic_pointer_cast<AudioFileSource> (
3366                 SourceFactory::createWritable (DataType::AUDIO, *this, path, destructive, frame_rate()));
3367 }
3368
3369 /** Return a unique name based on \a base for a new internal MIDI source */
3370 string
3371 Session::new_midi_source_name (const string& base)
3372 {
3373         uint32_t cnt;
3374         char buf[PATH_MAX+1];
3375         const uint32_t limit = 10000;
3376         string legalized;
3377
3378         buf[0] = '\0';
3379         legalized = legalize_for_path (base);
3380
3381         // Find a "version" of the file name that doesn't exist in any of the possible directories.
3382         for (cnt = 1; cnt <= limit; ++cnt) {
3383
3384                 vector<space_and_path>::iterator i;
3385                 uint32_t existing = 0;
3386
3387                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3388
3389                         SessionDirectory sdir((*i).path);
3390
3391                         sys::path p = sdir.midi_path();
3392                         p /= legalized;
3393
3394                         snprintf (buf, sizeof(buf), "%s-%u.mid", p.to_string().c_str(), cnt);
3395
3396                         if (sys::exists (buf)) {
3397                                 existing++;
3398                         }
3399                 }
3400
3401                 if (existing == 0) {
3402                         break;
3403                 }
3404
3405                 if (cnt > limit) {
3406                         error << string_compose(
3407                                         _("There are already %1 recordings for %2, which I consider too many."),
3408                                         limit, base) << endmsg;
3409                         destroy ();
3410                         throw failed_constructor();
3411                 }
3412         }
3413
3414         return Glib::path_get_basename(buf);
3415 }
3416
3417
3418 /** Create a new within-session MIDI source */
3419 boost::shared_ptr<MidiSource>
3420 Session::create_midi_source_for_session (MidiDiskstream& ds)
3421 {
3422         const string name = new_midi_source_name (ds.name());
3423         const string path = new_source_path_from_name (DataType::MIDI, name);
3424
3425         return boost::dynamic_pointer_cast<SMFSource> (
3426                         SourceFactory::createWritable (
3427                                         DataType::MIDI, *this, path, false, frame_rate()));
3428 }
3429
3430
3431 /* Playlist management */
3432
3433 boost::shared_ptr<Playlist>
3434 Session::playlist_by_name (string name)
3435 {
3436         Glib::Mutex::Lock lm (playlist_lock);
3437         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3438                 if ((*i)->name() == name) {
3439                         return* i;
3440                 }
3441         }
3442         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3443                 if ((*i)->name() == name) {
3444                         return* i;
3445                 }
3446         }
3447
3448         return boost::shared_ptr<Playlist>();
3449 }
3450
3451 void
3452 Session::unassigned_playlists (std::list<boost::shared_ptr<Playlist> > & list)
3453 {
3454         Glib::Mutex::Lock lm (playlist_lock);
3455         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3456                 if (!(*i)->get_orig_diskstream_id().to_s().compare ("0")) {
3457                         list.push_back (*i);
3458                 }
3459         }
3460         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3461                 if (!(*i)->get_orig_diskstream_id().to_s().compare ("0")) {
3462                         list.push_back (*i);
3463                 }
3464         }
3465 }
3466
3467 void
3468 Session::add_playlist (boost::shared_ptr<Playlist> playlist, bool unused)
3469 {
3470         if (playlist->hidden()) {
3471                 return;
3472         }
3473
3474         {
3475                 Glib::Mutex::Lock lm (playlist_lock);
3476                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3477                         playlists.insert (playlists.begin(), playlist);
3478                         playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3479                         playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3480                 }
3481         }
3482
3483         if (unused) {
3484                 playlist->release();
3485         }
3486
3487         set_dirty();
3488
3489         PlaylistAdded (playlist); /* EMIT SIGNAL */
3490 }
3491
3492 void
3493 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3494 {
3495         {
3496                 Glib::Mutex::Lock lm (playlist_lock);
3497                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3498                         s.push_back (*i);
3499                 }
3500                 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3501                         s.push_back (*i);
3502                 }
3503         }
3504 }
3505
3506 void
3507 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3508 {
3509         boost::shared_ptr<Playlist> pl(wpl.lock());
3510
3511         if (!pl) {
3512                 return;
3513         }
3514
3515         PlaylistList::iterator x;
3516
3517         if (pl->hidden()) {
3518                 /* its not supposed to be visible */
3519                 return;
3520         }
3521
3522         {
3523                 Glib::Mutex::Lock lm (playlist_lock);
3524
3525                 if (!inuse) {
3526
3527                         unused_playlists.insert (pl);
3528
3529                         if ((x = playlists.find (pl)) != playlists.end()) {
3530                                 playlists.erase (x);
3531                         }
3532
3533
3534                 } else {
3535
3536                         playlists.insert (pl);
3537
3538                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3539                                 unused_playlists.erase (x);
3540                         }
3541                 }
3542         }
3543 }
3544
3545 void
3546 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3547 {
3548         if (_state_of_the_state & Deletion) {
3549                 return;
3550         }
3551
3552         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3553
3554         if (!playlist) {
3555                 return;
3556         }
3557
3558         {
3559                 Glib::Mutex::Lock lm (playlist_lock);
3560
3561                 PlaylistList::iterator i;
3562
3563                 i = find (playlists.begin(), playlists.end(), playlist);
3564                 if (i != playlists.end()) {
3565                         playlists.erase (i);
3566                 }
3567
3568                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3569                 if (i != unused_playlists.end()) {
3570                         unused_playlists.erase (i);
3571                 }
3572
3573         }
3574
3575         set_dirty();
3576
3577         PlaylistRemoved (playlist); /* EMIT SIGNAL */
3578 }
3579
3580 void
3581 Session::set_audition (boost::shared_ptr<Region> r)
3582 {
3583         pending_audition_region = r;
3584         add_post_transport_work (PostTransportAudition);
3585         _butler->schedule_transport_work ();
3586 }
3587
3588 void
3589 Session::audition_playlist ()
3590 {
3591         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3592         ev->region.reset ();
3593         queue_event (ev);
3594 }
3595
3596 void
3597 Session::non_realtime_set_audition ()
3598 {
3599         if (!pending_audition_region) {
3600                 auditioner->audition_current_playlist ();
3601         } else {
3602                 auditioner->audition_region (pending_audition_region);
3603                 pending_audition_region.reset ();
3604         }
3605         AuditionActive (true); /* EMIT SIGNAL */
3606 }
3607
3608 void
3609 Session::audition_region (boost::shared_ptr<Region> r)
3610 {
3611         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3612         ev->region = r;
3613         queue_event (ev);
3614 }
3615
3616 void
3617 Session::cancel_audition ()
3618 {
3619         if (auditioner->active()) {
3620                 auditioner->cancel_audition ();
3621                 AuditionActive (false); /* EMIT SIGNAL */
3622         }
3623 }
3624
3625 bool
3626 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3627 {
3628         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3629 }
3630
3631 void
3632 Session::remove_empty_sounds ()
3633 {
3634         vector<string> audio_filenames;
3635
3636         get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3637
3638         Glib::Mutex::Lock lm (source_lock);
3639
3640         TapeFileMatcher tape_file_matcher;
3641
3642         remove_if (audio_filenames.begin(), audio_filenames.end(),
3643                         sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3644
3645         for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3646
3647                 sys::path audio_file_path (_session_dir->sound_path());
3648
3649                 audio_file_path /= *i;
3650
3651                 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3652
3653                         try
3654                         {
3655                                 sys::remove (audio_file_path);
3656                                 const string peakfile = peak_path (audio_file_path.to_string());
3657                                 sys::remove (peakfile);
3658                         }
3659                         catch (const sys::filesystem_error& err)
3660                         {
3661                                 error << err.what() << endmsg;
3662                         }
3663                 }
3664         }
3665 }
3666
3667 bool
3668 Session::is_auditioning () const
3669 {
3670         /* can be called before we have an auditioner object */
3671         if (auditioner) {
3672                 return auditioner->active();
3673         } else {
3674                 return false;
3675         }
3676 }
3677
3678 void
3679 Session::set_all_solo (bool yn)
3680 {
3681         shared_ptr<RouteList> r = routes.reader ();
3682
3683         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3684                 if (!(*i)->is_hidden()) {
3685                         (*i)->set_solo (yn, this);
3686                 }
3687         }
3688
3689         set_dirty();
3690 }
3691
3692 void
3693 Session::set_all_listen (bool yn)
3694 {
3695         shared_ptr<RouteList> r = routes.reader ();
3696
3697         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3698                 if (!(*i)->is_hidden()) {
3699                         (*i)->set_listen (yn, this);
3700                 }
3701         }
3702
3703         set_dirty();
3704 }
3705
3706 void
3707 Session::set_all_mute (bool yn)
3708 {
3709         shared_ptr<RouteList> r = routes.reader ();
3710
3711         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3712                 if (!(*i)->is_hidden()) {
3713                         (*i)->set_mute (yn, this);
3714                 }
3715         }
3716
3717         set_dirty();
3718 }
3719
3720 uint32_t
3721 Session::n_diskstreams () const
3722 {
3723         uint32_t n = 0;
3724
3725         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3726
3727         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3728                 if (!(*i)->hidden()) {
3729                         n++;
3730                 }
3731         }
3732         return n;
3733 }
3734
3735 void
3736 Session::graph_reordered ()
3737 {
3738         /* don't do this stuff if we are setting up connections
3739            from a set_state() call or creating new tracks. Ditto for deletion.
3740         */
3741
3742         if (_state_of_the_state & (InitialConnecting|Deletion)) {
3743                 return;
3744         }
3745
3746         /* every track/bus asked for this to be handled but it was deferred because
3747            we were connecting. do it now.
3748         */
3749
3750         request_input_change_handling ();
3751
3752         resort_routes ();
3753
3754         /* force all diskstreams to update their capture offset values to
3755            reflect any changes in latencies within the graph.
3756         */
3757
3758         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3759
3760         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3761                 (*i)->set_capture_offset ();
3762         }
3763 }
3764
3765 void
3766 Session::record_disenable_all ()
3767 {
3768         record_enable_change_all (false);
3769 }
3770
3771 void
3772 Session::record_enable_all ()
3773 {
3774         record_enable_change_all (true);
3775 }
3776
3777 void
3778 Session::record_enable_change_all (bool yn)
3779 {
3780         shared_ptr<RouteList> r = routes.reader ();
3781
3782         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3783                 boost::shared_ptr<Track> t;
3784
3785                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
3786                         t->set_record_enable (yn, this);
3787                 }
3788         }
3789
3790         /* since we don't keep rec-enable state, don't mark session dirty */
3791 }
3792
3793 void
3794 Session::add_processor (Processor* processor)
3795 {
3796         processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3797         set_dirty();
3798 }
3799
3800 void
3801 Session::remove_processor (Processor* processor)
3802 {
3803         Send* send;
3804         Return* retrn;
3805         PortInsert* port_insert;
3806
3807         if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3808                 insert_bitset[port_insert->bit_slot()] = false;
3809         } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3810                 send_bitset[send->bit_slot()] = false;
3811         } else if ((retrn = dynamic_cast<Return *> (processor)) != 0) {
3812                 return_bitset[retrn->bit_slot()] = false;
3813         }
3814
3815         set_dirty();
3816 }
3817
3818 nframes_t
3819 Session::available_capture_duration ()
3820 {
3821         float sample_bytes_on_disk = 4.0; // keep gcc happy
3822
3823         switch (config.get_native_file_data_format()) {
3824         case FormatFloat:
3825                 sample_bytes_on_disk = 4.0;
3826                 break;
3827
3828         case FormatInt24:
3829                 sample_bytes_on_disk = 3.0;
3830                 break;
3831
3832         case FormatInt16:
3833                 sample_bytes_on_disk = 2.0;
3834                 break;
3835
3836         default:
3837                 /* impossible, but keep some gcc versions happy */
3838                 fatal << string_compose (_("programming error: %1"),
3839                                          X_("illegal native file data format"))
3840                       << endmsg;
3841                 /*NOTREACHED*/
3842         }
3843
3844         double scale = 4096.0 / sample_bytes_on_disk;
3845
3846         if (_total_free_4k_blocks * scale > (double) max_frames) {
3847                 return max_frames;
3848         }
3849
3850         return (nframes_t) floor (_total_free_4k_blocks * scale);
3851 }
3852
3853 void
3854 Session::add_bundle (shared_ptr<Bundle> bundle)
3855 {
3856         {
3857                 RCUWriter<BundleList> writer (_bundles);
3858                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3859                 b->push_back (bundle);
3860         }
3861
3862         BundleAdded (bundle); /* EMIT SIGNAL */
3863
3864         set_dirty();
3865 }
3866
3867 void
3868 Session::remove_bundle (shared_ptr<Bundle> bundle)
3869 {
3870         bool removed = false;
3871
3872         {
3873                 RCUWriter<BundleList> writer (_bundles);
3874                 boost::shared_ptr<BundleList> b = writer.get_copy ();
3875                 BundleList::iterator i = find (b->begin(), b->end(), bundle);
3876
3877                 if (i != b->end()) {
3878                         b->erase (i);
3879                         removed = true;
3880                 }
3881         }
3882
3883         if (removed) {
3884                  BundleRemoved (bundle); /* EMIT SIGNAL */
3885         }
3886
3887         set_dirty();
3888 }
3889
3890 shared_ptr<Bundle>
3891 Session::bundle_by_name (string name) const
3892 {
3893         boost::shared_ptr<BundleList> b = _bundles.reader ();
3894
3895         for (BundleList::const_iterator i = b->begin(); i != b->end(); ++i) {
3896                 if ((*i)->name() == name) {
3897                         return* i;
3898                 }
3899         }
3900
3901         return boost::shared_ptr<Bundle> ();
3902 }
3903
3904 void
3905 Session::tempo_map_changed (Change)
3906 {
3907         clear_clicks ();
3908
3909         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3910                 (*i)->update_after_tempo_map_change ();
3911         }
3912
3913         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3914                 (*i)->update_after_tempo_map_change ();
3915         }
3916
3917         set_dirty ();
3918 }
3919
3920 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3921  * the given count with the current block size.
3922  */
3923 void
3924 Session::ensure_buffers (ChanCount howmany)
3925 {
3926         if (current_block_size == 0) {
3927                 return; // too early? (is this ok?)
3928         }
3929
3930         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3931                 size_t count = std::max(_scratch_buffers->available().get(*t), howmany.get(*t));
3932                 _scratch_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3933                 _mix_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3934                 _silent_buffers->ensure_buffers (*t, count, _engine.raw_buffer_size(*t));
3935         }
3936
3937         allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3938 }
3939
3940 void
3941 Session::ensure_buffer_set(BufferSet& buffers, const ChanCount& count)
3942 {
3943         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
3944                 buffers.ensure_buffers(*t, count.get(*t), _engine.raw_buffer_size(*t));
3945         }
3946 }
3947
3948 uint32_t
3949 Session::next_insert_id ()
3950 {
3951         /* this doesn't really loop forever. just think about it */
3952
3953         while (true) {
3954                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3955                         if (!insert_bitset[n]) {
3956                                 insert_bitset[n] = true;
3957                                 return n;
3958
3959                         }
3960                 }
3961
3962                 /* none available, so resize and try again */
3963
3964                 insert_bitset.resize (insert_bitset.size() + 16, false);
3965         }
3966 }
3967
3968 uint32_t
3969 Session::next_send_id ()
3970 {
3971         /* this doesn't really loop forever. just think about it */
3972
3973         while (true) {
3974                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3975                         if (!send_bitset[n]) {
3976                                 send_bitset[n] = true;
3977                                 return n;
3978
3979                         }
3980                 }
3981
3982                 /* none available, so resize and try again */
3983
3984                 send_bitset.resize (send_bitset.size() + 16, false);
3985         }
3986 }
3987
3988 uint32_t
3989 Session::next_return_id ()
3990 {
3991         /* this doesn't really loop forever. just think about it */
3992
3993         while (true) {
3994                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < return_bitset.size(); ++n) {
3995                         if (!return_bitset[n]) {
3996                                 return_bitset[n] = true;
3997                                 return n;
3998
3999                         }
4000                 }
4001
4002                 /* none available, so resize and try again */
4003
4004                 return_bitset.resize (return_bitset.size() + 16, false);
4005         }
4006 }
4007
4008 void
4009 Session::mark_send_id (uint32_t id)
4010 {
4011         if (id >= send_bitset.size()) {
4012                 send_bitset.resize (id+16, false);
4013         }
4014         if (send_bitset[id]) {
4015                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
4016         }
4017         send_bitset[id] = true;
4018 }
4019
4020 void
4021 Session::mark_return_id (uint32_t id)
4022 {
4023         if (id >= return_bitset.size()) {
4024                 return_bitset.resize (id+16, false);
4025         }
4026         if (return_bitset[id]) {
4027                 warning << string_compose (_("return ID %1 appears to be in use already"), id) << endmsg;
4028         }
4029         return_bitset[id] = true;
4030 }
4031
4032 void
4033 Session::mark_insert_id (uint32_t id)
4034 {
4035         if (id >= insert_bitset.size()) {
4036                 insert_bitset.resize (id+16, false);
4037         }
4038         if (insert_bitset[id]) {
4039                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
4040         }
4041         insert_bitset[id] = true;
4042 }
4043
4044 /* Named Selection management */
4045
4046 NamedSelection *
4047 Session::named_selection_by_name (string name)
4048 {
4049         Glib::Mutex::Lock lm (named_selection_lock);
4050         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
4051                 if ((*i)->name == name) {
4052                         return* i;
4053                 }
4054         }
4055         return 0;
4056 }
4057
4058 void
4059 Session::add_named_selection (NamedSelection* named_selection)
4060 {
4061         {
4062                 Glib::Mutex::Lock lm (named_selection_lock);
4063                 named_selections.insert (named_selections.begin(), named_selection);
4064         }
4065
4066         for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
4067                 add_playlist (*i);
4068         }
4069
4070         set_dirty();
4071
4072         NamedSelectionAdded (); /* EMIT SIGNAL */
4073 }
4074
4075 void
4076 Session::remove_named_selection (NamedSelection* named_selection)
4077 {
4078         bool removed = false;
4079
4080         {
4081                 Glib::Mutex::Lock lm (named_selection_lock);
4082
4083                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
4084
4085                 if (i != named_selections.end()) {
4086                         delete (*i);
4087                         named_selections.erase (i);
4088                         set_dirty();
4089                         removed = true;
4090                 }
4091         }
4092
4093         if (removed) {
4094                  NamedSelectionRemoved (); /* EMIT SIGNAL */
4095         }
4096 }
4097
4098 void
4099 Session::reset_native_file_format ()
4100 {
4101         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
4102
4103         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
4104                 (*i)->reset_write_sources (false);
4105         }
4106 }
4107
4108 bool
4109 Session::route_name_unique (string n) const
4110 {
4111         shared_ptr<RouteList> r = routes.reader ();
4112
4113         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4114                 if ((*i)->name() == n) {
4115                         return false;
4116                 }
4117         }
4118
4119         return true;
4120 }
4121
4122 bool
4123 Session::route_name_internal (string n) const
4124 {
4125         if (auditioner && auditioner->name() == n) {
4126                 return true;
4127         }
4128
4129         if (_click_io && _click_io->name() == n) {
4130                 return true;
4131         }
4132
4133         return false;
4134 }
4135
4136 uint32_t
4137 Session::n_playlists () const
4138 {
4139         Glib::Mutex::Lock lm (playlist_lock);
4140         return playlists.size();
4141 }
4142
4143 void
4144 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
4145 {
4146         if (!force && howmany <= _npan_buffers) {
4147                 return;
4148         }
4149
4150         if (_pan_automation_buffer) {
4151
4152                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
4153                         delete [] _pan_automation_buffer[i];
4154                 }
4155
4156                 delete [] _pan_automation_buffer;
4157         }
4158
4159         _pan_automation_buffer = new pan_t*[howmany];
4160
4161         for (uint32_t i = 0; i < howmany; ++i) {
4162                 _pan_automation_buffer[i] = new pan_t[nframes];
4163         }
4164
4165         _npan_buffers = howmany;
4166 }
4167
4168 int
4169 Session::freeze (InterThreadInfo& itt)
4170 {
4171         shared_ptr<RouteList> r = routes.reader ();
4172
4173         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4174
4175                 boost::shared_ptr<Track> t;
4176
4177                 if ((t = boost::dynamic_pointer_cast<Track>(*i)) != 0) {
4178                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
4179                            of every track.
4180                         */
4181                         t->freeze (itt);
4182                 }
4183         }
4184
4185         return 0;
4186 }
4187
4188 boost::shared_ptr<Region>
4189 Session::write_one_track (AudioTrack& track, nframes_t start, nframes_t end,
4190                           bool /*overwrite*/, vector<boost::shared_ptr<Source> >& srcs,
4191                           InterThreadInfo& itt, bool enable_processing)
4192 {
4193         boost::shared_ptr<Region> result;
4194         boost::shared_ptr<Playlist> playlist;
4195         boost::shared_ptr<AudioFileSource> fsource;
4196         uint32_t x;
4197         char buf[PATH_MAX+1];
4198         ChanCount nchans(track.audio_diskstream()->n_channels());
4199         nframes_t position;
4200         nframes_t this_chunk;
4201         nframes_t to_do;
4202         BufferSet buffers;
4203         SessionDirectory sdir(get_best_session_directory_for_new_source ());
4204         const string sound_dir = sdir.sound_path().to_string();
4205         nframes_t len = end - start;
4206
4207         if (end <= start) {
4208                 error << string_compose (_("Cannot write a range where end <= start (e.g. %1 <= %2)"),
4209                                          end, start) << endmsg;
4210                 return result;
4211         }
4212
4213         // any bigger than this seems to cause stack overflows in called functions
4214         const nframes_t chunk_size = (128 * 1024)/4;
4215
4216         // block all process callback handling
4217
4218         block_processing ();
4219
4220         /* call tree *MUST* hold route_lock */
4221
4222         if ((playlist = track.diskstream()->playlist()) == 0) {
4223                 goto out;
4224         }
4225
4226         /* external redirects will be a problem */
4227
4228         if (track.has_external_redirects()) {
4229                 goto out;
4230         }
4231
4232         for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4233
4234                 for (x = 0; x < 99999; ++x) {
4235                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4236                         if (access (buf, F_OK) != 0) {
4237                                 break;
4238                         }
4239                 }
4240
4241                 if (x == 99999) {
4242                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4243                         goto out;
4244                 }
4245
4246                 try {
4247                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4248                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4249                 }
4250
4251                 catch (failed_constructor& err) {
4252                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4253                         goto out;
4254                 }
4255
4256                 srcs.push_back (fsource);
4257         }
4258
4259         /* XXX need to flush all redirects */
4260
4261         position = start;
4262         to_do = len;
4263
4264         /* create a set of reasonably-sized buffers */
4265         buffers.ensure_buffers(DataType::AUDIO, nchans.n_audio(), chunk_size);
4266         buffers.set_count(nchans);
4267
4268         for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4269                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4270                 if (afs)
4271                         afs->prepare_for_peakfile_writes ();
4272         }
4273
4274         while (to_do && !itt.cancel) {
4275
4276                 this_chunk = min (to_do, chunk_size);
4277
4278                 if (track.export_stuff (buffers, start, this_chunk, enable_processing)) {
4279                         goto out;
4280                 }
4281
4282                 uint32_t n = 0;
4283                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4284                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4285
4286                         if (afs) {
4287                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4288                                         goto out;
4289                                 }
4290                         }
4291                 }
4292
4293                 start += this_chunk;
4294                 to_do -= this_chunk;
4295
4296                 itt.progress = (float) (1.0 - ((double) to_do / len));
4297
4298         }
4299
4300         if (!itt.cancel) {
4301
4302                 time_t now;
4303                 struct tm* xnow;
4304                 time (&now);
4305                 xnow = localtime (&now);
4306
4307                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4308                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4309
4310                         if (afs) {
4311                                 afs->update_header (position, *xnow, now);
4312                                 afs->flush_header ();
4313                         }
4314                 }
4315
4316                 /* construct a region to represent the bounced material */
4317
4318                 result = RegionFactory::create (srcs, 0,
4319                                 srcs.front()->length(srcs.front()->timeline_position()),
4320                                 region_name_from_path (srcs.front()->name(), true));
4321         }
4322
4323   out:
4324         if (!result) {
4325                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4326                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4327
4328                         if (afs) {
4329                                 afs->mark_for_remove ();
4330                         }
4331
4332                         (*src)->drop_references ();
4333                 }
4334
4335         } else {
4336                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4337                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4338
4339                         if (afs)
4340                                 afs->done_with_peakfile_writes ();
4341                 }
4342         }
4343
4344         unblock_processing ();
4345
4346         return result;
4347 }
4348
4349 BufferSet&
4350 Session::get_silent_buffers (ChanCount count)
4351 {
4352         assert(_silent_buffers->available() >= count);
4353         _silent_buffers->set_count(count);
4354
4355         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4356                 for (size_t i= 0; i < count.get(*t); ++i) {
4357                         _silent_buffers->get(*t, i).clear();
4358                 }
4359         }
4360
4361         return *_silent_buffers;
4362 }
4363
4364 BufferSet&
4365 Session::get_scratch_buffers (ChanCount count)
4366 {
4367         if (count != ChanCount::ZERO) {
4368                 assert(_scratch_buffers->available() >= count);
4369                 _scratch_buffers->set_count(count);
4370         } else {
4371                 _scratch_buffers->set_count (_scratch_buffers->available());
4372         }
4373
4374         return *_scratch_buffers;
4375 }
4376
4377 BufferSet&
4378 Session::get_mix_buffers (ChanCount count)
4379 {
4380         assert(_mix_buffers->available() >= count);
4381         _mix_buffers->set_count(count);
4382         return *_mix_buffers;
4383 }
4384
4385 uint32_t
4386 Session::ntracks () const
4387 {
4388         uint32_t n = 0;
4389         shared_ptr<RouteList> r = routes.reader ();
4390
4391         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4392                 if (boost::dynamic_pointer_cast<Track> (*i)) {
4393                         ++n;
4394                 }
4395         }
4396
4397         return n;
4398 }
4399
4400 uint32_t
4401 Session::nbusses () const
4402 {
4403         uint32_t n = 0;
4404         shared_ptr<RouteList> r = routes.reader ();
4405
4406         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4407                 if (boost::dynamic_pointer_cast<Track>(*i) == 0) {
4408                         ++n;
4409                 }
4410         }
4411
4412         return n;
4413 }
4414
4415 void
4416 Session::add_automation_list(AutomationList *al)
4417 {
4418         automation_lists[al->id()] = al;
4419 }
4420
4421 nframes_t
4422 Session::compute_initial_length ()
4423 {
4424         return _engine.frame_rate() * 60 * 5;
4425 }
4426
4427 void
4428 Session::sync_order_keys (std::string const & base)
4429 {
4430         if (!Config->get_sync_all_route_ordering()) {
4431                 /* leave order keys as they are */
4432                 return;
4433         }
4434
4435         boost::shared_ptr<RouteList> r = routes.reader ();
4436
4437         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4438                 (*i)->sync_order_keys (base);
4439         }
4440
4441         Route::SyncOrderKeys (base); // EMIT SIGNAL
4442 }
4443
4444
4445 /** @return true if there is at least one record-enabled diskstream, otherwise false */
4446 bool
4447 Session::have_rec_enabled_diskstream () const
4448 {
4449         return g_atomic_int_get (&_have_rec_enabled_diskstream) == 1;
4450 }
4451
4452 /** Update the state of our rec-enabled diskstreams flag */
4453 void
4454 Session::update_have_rec_enabled_diskstream ()
4455 {
4456         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader ();
4457         DiskstreamList::iterator i = dsl->begin ();
4458         while (i != dsl->end () && (*i)->record_enabled () == false) {
4459                 ++i;
4460         }
4461
4462         int const old = g_atomic_int_get (&_have_rec_enabled_diskstream);
4463
4464         g_atomic_int_set (&_have_rec_enabled_diskstream, i != dsl->end () ? 1 : 0);
4465
4466         if (g_atomic_int_get (&_have_rec_enabled_diskstream) != old) {
4467                 RecordStateChanged (); /* EMIT SIGNAL */
4468         }
4469 }
4470
4471 void
4472 Session::listen_position_changed ()
4473 {
4474         Placement p;
4475
4476         switch (Config->get_listen_position()) {
4477         case AfterFaderListen:
4478                 p = PostFader;
4479                 break;
4480
4481         case PreFaderListen:
4482                 p = PreFader;
4483                 break;
4484         }
4485
4486         boost::shared_ptr<RouteList> r = routes.reader ();
4487
4488         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4489                 (*i)->put_control_outs_at (p);
4490         }
4491 }
4492
4493 void
4494 Session::solo_control_mode_changed ()
4495 {
4496         /* cancel all solo or all listen when solo control mode changes */
4497
4498         if (Config->get_solo_control_is_listen_control()) {
4499                 set_all_solo (false);
4500         } else {
4501                 set_all_listen (false);
4502         }
4503 }
4504
4505 void
4506 Session::route_group_changed ()
4507 {
4508         RouteGroupChanged (); /* EMIT SIGNAL */
4509 }
4510
4511 vector<SyncSource>
4512 Session::get_available_sync_options () const
4513 {
4514         vector<SyncSource> ret;
4515         
4516         ret.push_back (JACK);
4517
4518         if (mtc_port()) {
4519                 ret.push_back (MTC);
4520         } 
4521
4522         if (midi_clock_port()) {
4523                 ret.push_back (MIDIClock);
4524         } 
4525
4526         return ret;
4527 }
4528
4529 boost::shared_ptr<RouteList>
4530 Session::get_routes_with_regions_at (nframes64_t const p) const
4531 {
4532         shared_ptr<RouteList> r = routes.reader ();
4533         shared_ptr<RouteList> rl (new RouteList);
4534
4535         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4536                 boost::shared_ptr<Track> tr = boost::dynamic_pointer_cast<Track> (*i);
4537                 if (!tr) {
4538                         continue;
4539                 }
4540                 
4541                 boost::shared_ptr<Diskstream> ds = tr->diskstream ();
4542                 if (!ds) {
4543                         continue;
4544                 }
4545
4546                 boost::shared_ptr<Playlist> pl = ds->playlist ();
4547                 if (!pl) {
4548                         continue;
4549                 }
4550                 
4551                 if (pl->has_region_at (p)) {
4552                         rl->push_back (*i);
4553                 }
4554         }
4555
4556         return rl;
4557 }
4558
4559