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