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