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