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