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