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