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