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