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