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