34807e798b25c2c0582f4f68dc93e1862fb1bd08
[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 sigc::signal<void> Session::SendFeedback;
94
95
96 int
97 Session::find_session (string str, string& path, string& snapshot, bool& isnew)
98 {
99         struct stat statbuf;
100         char buf[PATH_MAX+1];
101
102         isnew = false;
103
104         if (!realpath (str.c_str(), buf) && (errno != ENOENT && errno != ENOTDIR)) {
105                 error << string_compose (_("Could not resolve path: %1 (%2)"), buf, strerror(errno)) << endmsg;
106                 return -1;
107         }
108
109         str = buf;
110         
111         /* check to see if it exists, and what it is */
112
113         if (stat (str.c_str(), &statbuf)) {
114                 if (errno == ENOENT) {
115                         isnew = true;
116                 } else {
117                         error << string_compose (_("cannot check session path %1 (%2)"), str, strerror (errno))
118                               << endmsg;
119                         return -1;
120                 }
121         }
122
123         if (!isnew) {
124
125                 /* it exists, so it must either be the name
126                    of the directory, or the name of the statefile
127                    within it.
128                 */
129
130                 if (S_ISDIR (statbuf.st_mode)) {
131
132                         string::size_type slash = str.find_last_of ('/');
133                 
134                         if (slash == string::npos) {
135                                 
136                                 /* a subdirectory of cwd, so statefile should be ... */
137
138                                 string tmp;
139                                 tmp = str;
140                                 tmp += '/';
141                                 tmp += str;
142                                 tmp += _statefile_suffix;
143
144                                 /* is it there ? */
145                                 
146                                 if (stat (tmp.c_str(), &statbuf)) {
147                                         error << string_compose (_("cannot check statefile %1 (%2)"), tmp, strerror (errno))
148                                               << endmsg;
149                                         return -1;
150                                 }
151
152                                 path = str;
153                                 snapshot = str;
154
155                         } else {
156
157                                 /* some directory someplace in the filesystem.
158                                    the snapshot name is the directory name
159                                    itself.
160                                 */
161
162                                 path = str;
163                                 snapshot = str.substr (slash+1);
164                                         
165                         }
166
167                 } else if (S_ISREG (statbuf.st_mode)) {
168                         
169                         string::size_type slash = str.find_last_of ('/');
170                         string::size_type suffix;
171
172                         /* remove the suffix */
173                         
174                         if (slash != string::npos) {
175                                 snapshot = str.substr (slash+1);
176                         } else {
177                                 snapshot = str;
178                         }
179
180                         suffix = snapshot.find (_statefile_suffix);
181                         
182                         if (suffix == string::npos) {
183                                 error << string_compose (_("%1 is not an Ardour snapshot file"), str) << endmsg;
184                                 return -1;
185                         }
186
187                         /* remove suffix */
188
189                         snapshot = snapshot.substr (0, suffix);
190                         
191                         if (slash == string::npos) {
192                                 
193                                 /* we must be in the directory where the 
194                                    statefile lives. get it using cwd().
195                                 */
196
197                                 char cwd[PATH_MAX+1];
198
199                                 if (getcwd (cwd, sizeof (cwd)) == 0) {
200                                         error << string_compose (_("cannot determine current working directory (%1)"), strerror (errno))
201                                               << endmsg;
202                                         return -1;
203                                 }
204
205                                 path = cwd;
206
207                         } else {
208
209                                 /* full path to the statefile */
210
211                                 path = str.substr (0, slash);
212                         }
213                                 
214                 } else {
215
216                         /* what type of file is it? */
217                         error << string_compose (_("unknown file type for session %1"), str) << endmsg;
218                         return -1;
219                 }
220
221         } else {
222
223                 /* its the name of a new directory. get the name
224                    as "dirname" does.
225                 */
226
227                 string::size_type slash = str.find_last_of ('/');
228
229                 if (slash == string::npos) {
230                         
231                         /* no slash, just use the name, but clean it up */
232                         
233                         path = legalize_for_path (str);
234                         snapshot = path;
235                         
236                 } else {
237                         
238                         path = str;
239                         snapshot = str.substr (slash+1);
240                 }
241         }
242
243         return 0;
244 }
245
246 Session::Session (AudioEngine &eng,
247                   string fullpath,
248                   string snapshot_name,
249                   string* mix_template)
250
251         : _engine (eng),
252           _mmc_port (default_mmc_port),
253           _mtc_port (default_mtc_port),
254           _midi_port (default_midi_port),
255           pending_events (2048),
256           midi_requests (128), // the size of this should match the midi request pool size
257           main_outs (0)
258 {
259         bool new_session;
260
261         cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << endl;
262
263         n_physical_outputs = _engine.n_physical_outputs();
264         n_physical_inputs =  _engine.n_physical_inputs();
265
266         first_stage_init (fullpath, snapshot_name);
267         
268         if (create (new_session, mix_template, _engine.frame_rate() * 60 * 5)) {
269                 throw failed_constructor ();
270         }
271         
272         if (second_stage_init (new_session)) {
273                 throw failed_constructor ();
274         }
275         
276         store_recent_sessions(_name, _path);
277         
278         bool was_dirty = dirty();
279
280         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
281
282         if (was_dirty) {
283                 DirtyChanged (); /* EMIT SIGNAL */
284         }
285 }
286
287 Session::Session (AudioEngine &eng,
288                   string fullpath,
289                   string snapshot_name,
290                   AutoConnectOption input_ac,
291                   AutoConnectOption output_ac,
292                   uint32_t control_out_channels,
293                   uint32_t master_out_channels,
294                   uint32_t requested_physical_in,
295                   uint32_t requested_physical_out,
296                   jack_nframes_t initial_length)
297
298         : _engine (eng),
299           _mmc_port (default_mmc_port),
300           _mtc_port (default_mtc_port),
301           _midi_port (default_midi_port),
302           pending_events (2048),
303           midi_requests (16),
304           main_outs (0)
305
306 {
307         bool new_session;
308
309         cerr << "Loading session " << fullpath << " using snapshot " << snapshot_name << endl;
310
311         n_physical_outputs = max (requested_physical_out, _engine.n_physical_outputs());
312         n_physical_inputs = max (requested_physical_in, _engine.n_physical_inputs());
313
314         first_stage_init (fullpath, snapshot_name);
315         
316         if (create (new_session, 0, initial_length)) {
317                 throw failed_constructor ();
318         }
319
320         if (control_out_channels) {
321                 Route* r;
322                 r = new Route (*this, _("monitor"), -1, control_out_channels, -1, control_out_channels, Route::ControlOut);
323                 add_route (r);
324                 _control_out = r;
325         }
326
327         if (master_out_channels) {
328                 Route* r;
329                 r = new Route (*this, _("master"), -1, master_out_channels, -1, master_out_channels, Route::MasterOut);
330                 add_route (r);
331                 _master_out = r;
332         } else {
333                 /* prohibit auto-connect to master, because there isn't one */
334                 output_ac = AutoConnectOption (output_ac & ~AutoConnectMaster);
335         }
336
337         input_auto_connect = input_ac;
338         output_auto_connect = output_ac;
339
340         if (second_stage_init (new_session)) {
341                 throw failed_constructor ();
342         }
343         
344         store_recent_sessions(_name, _path);
345         
346         bool was_dirty = dirty ();
347
348         _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
349
350         if (was_dirty) {
351                 DirtyChanged (); /* EMIT SIGNAL */
352         }
353 }
354
355 Session::~Session ()
356 {
357         /* if we got to here, leaving pending capture state around
358            is a mistake.
359         */
360
361         remove_pending_capture_state ();
362
363         _state_of_the_state = StateOfTheState (CannotSave|Deletion);
364         _engine.remove_session ();
365         
366         going_away (); /* EMIT SIGNAL */
367         
368         terminate_butler_thread ();
369         terminate_midi_thread ();
370         
371         if (click_data && click_data != default_click) {
372                 delete [] click_data;
373         }
374
375         if (click_emphasis_data && click_emphasis_data != default_click_emphasis) {
376                 delete [] click_emphasis_data;
377         }
378
379         clear_clicks ();
380
381         if (_click_io) {
382                 delete _click_io;
383         }
384
385
386         if (auditioner) {
387                 delete auditioner;
388         }
389
390         for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
391                 free(*i);
392         }
393
394         for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
395                 free(*i);
396         }
397
398         for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
399                 free(*i);
400         }
401
402         for (map<RunContext,char*>::iterator i = _conversion_buffers.begin(); i != _conversion_buffers.end(); ++i) {
403                 delete [] (i->second);
404         }
405         
406 #undef TRACK_DESTRUCTION
407 #ifdef TRACK_DESTRUCTION
408         cerr << "delete named selections\n";
409 #endif /* TRACK_DESTRUCTION */
410         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ) {
411                 NamedSelectionList::iterator tmp;
412
413                 tmp = i;
414                 ++tmp;
415
416                 delete *i;
417                 i = tmp;
418         }
419
420 #ifdef TRACK_DESTRUCTION
421         cerr << "delete playlists\n";
422 #endif /* TRACK_DESTRUCTION */
423         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ) {
424                 PlaylistList::iterator tmp;
425
426                 tmp = i;
427                 ++tmp;
428
429                 delete *i;
430                 
431                 i = tmp;
432         }
433
434 #ifdef TRACK_DESTRUCTION
435         cerr << "delete audio regions\n";
436 #endif /* TRACK_DESTRUCTION */
437         for (AudioRegionList::iterator i = audio_regions.begin(); i != audio_regions.end(); ) {
438                 AudioRegionList::iterator tmp;
439
440                 tmp =i;
441                 ++tmp;
442
443                 delete i->second;
444
445                 i = tmp;
446         }
447         
448 #ifdef TRACK_DESTRUCTION
449         cerr << "delete routes\n";
450 #endif /* TRACK_DESTRUCTION */
451         for (RouteList::iterator i = routes.begin(); i != routes.end(); ) {
452                 RouteList::iterator tmp;
453                 tmp = i;
454                 ++tmp;
455                 delete *i;
456                 i = tmp;
457         }
458
459 #ifdef TRACK_DESTRUCTION
460         cerr << "delete audio_diskstreams\n";
461 #endif /* TRACK_DESTRUCTION */
462         for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ) {
463                 AudioDiskstreamList::iterator tmp;
464
465                 tmp = i;
466                 ++tmp;
467
468                 delete *i;
469
470                 i = tmp;
471         }
472
473 #ifdef TRACK_DESTRUCTION
474         cerr << "delete audio sources\n";
475 #endif /* TRACK_DESTRUCTION */
476         for (AudioSourceList::iterator i = audio_sources.begin(); i != audio_sources.end(); ) {
477                 AudioSourceList::iterator tmp;
478
479                 tmp = i;
480                 ++tmp;
481
482                 delete i->second;
483
484                 i = tmp;
485         }
486
487 #ifdef TRACK_DESTRUCTION
488         cerr << "delete mix groups\n";
489 #endif /* TRACK_DESTRUCTION */
490         for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ) {
491                 list<RouteGroup*>::iterator tmp;
492
493                 tmp = i;
494                 ++tmp;
495
496                 delete *i;
497
498                 i = tmp;
499         }
500
501 #ifdef TRACK_DESTRUCTION
502         cerr << "delete edit groups\n";
503 #endif /* TRACK_DESTRUCTION */
504         for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ) {
505                 list<RouteGroup*>::iterator tmp;
506                 
507                 tmp = i;
508                 ++tmp;
509
510                 delete *i;
511
512                 i = tmp;
513         }
514         
515 #ifdef TRACK_DESTRUCTION
516         cerr << "delete connections\n";
517 #endif /* TRACK_DESTRUCTION */
518         for (ConnectionList::iterator i = _connections.begin(); i != _connections.end(); ) {
519                 ConnectionList::iterator tmp;
520
521                 tmp = i;
522                 ++tmp;
523
524                 delete *i;
525
526                 i = tmp;
527         }
528
529         if (butler_mixdown_buffer) {
530                 delete [] butler_mixdown_buffer;
531         }
532
533         if (butler_gain_buffer) {
534                 delete [] butler_gain_buffer;
535         }
536
537         Crossfade::set_buffer_size (0);
538
539         if (mmc) {
540                 delete mmc;
541         }
542
543         if (state_tree) {
544                 delete state_tree;
545         }
546 }
547
548 void
549 Session::set_worst_io_latencies (bool take_lock)
550 {
551         _worst_output_latency = 0;
552         _worst_input_latency = 0;
553
554         if (!_engine.connected()) {
555                 return;
556         }
557
558         if (take_lock) {
559                 route_lock.reader_lock ();
560         }
561         
562         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
563                 _worst_output_latency = max (_worst_output_latency, (*i)->output_latency());
564                 _worst_input_latency = max (_worst_input_latency, (*i)->input_latency());
565         }
566
567         if (take_lock) {
568                 route_lock.reader_unlock ();
569         }
570 }
571
572 void
573 Session::when_engine_running ()
574 {
575         string first_physical_output;
576
577         /* we don't want to run execute this again */
578
579         first_time_running.disconnect ();
580
581         set_block_size (_engine.frames_per_cycle());
582         set_frame_rate (_engine.frame_rate());
583
584         /* every time we reconnect, recompute worst case output latencies */
585
586         _engine.Running.connect (sigc::bind (mem_fun (*this, &Session::set_worst_io_latencies), true));
587
588         if (synced_to_jack()) {
589                 _engine.transport_stop ();
590         }
591
592         if (Config->get_jack_time_master()) {
593                 _engine.transport_locate (_transport_frame);
594         }
595
596         _clicking = false;
597
598         try {
599                 XMLNode* child = 0;
600                 
601                 _click_io = new ClickIO (*this, "click", 0, 0, -1, -1);
602
603                 if (state_tree && (child = find_named_node (*state_tree->root(), "Click")) != 0) {
604
605                         /* existing state for Click */
606                         
607                         if (_click_io->set_state (*child->children().front()) == 0) {
608                                 
609                                 _clicking = click_requested;
610
611                         } else {
612
613                                 error << _("could not setup Click I/O") << endmsg;
614                                 _clicking = false;
615                         }
616
617                 } else {
618                         
619                         /* default state for Click */
620
621                         first_physical_output = _engine.get_nth_physical_output (0);
622                         
623                         if (first_physical_output.length()) {
624                                 if (_click_io->add_output_port (first_physical_output, this)) {
625                                         // relax, even though its an error
626                                 } else {
627                                         _clicking = click_requested;
628                                 }
629                         }
630                 }
631         }
632
633         catch (failed_constructor& err) {
634                 error << _("cannot setup Click I/O") << endmsg;
635         }
636
637         set_worst_io_latencies (true);
638
639         if (_clicking) {
640                  ControlChanged (Clicking); /* EMIT SIGNAL */
641         }
642
643         if (auditioner == 0) {
644
645                 /* we delay creating the auditioner till now because
646                    it makes its own connections to ports named
647                    in the ARDOUR_RC config file. the engine has
648                    to be running for this to work.
649                 */
650
651                 try {
652                         auditioner = new Auditioner (*this);
653                 }
654
655                 catch (failed_constructor& err) {
656                         warning << _("cannot create Auditioner: no auditioning of regions possible") << endmsg;
657                 }
658         }
659
660         /* Create a set of Connection objects that map
661            to the physical outputs currently available
662         */
663
664         /* ONE: MONO */
665
666         for (uint32_t np = 0; np < n_physical_outputs; ++np) {
667                 char buf[32];
668                 snprintf (buf, sizeof (buf), _("out %" PRIu32), np+1);
669
670                 Connection* c = new OutputConnection (buf, true);
671
672                 c->add_port ();
673                 c->add_connection (0, _engine.get_nth_physical_output (np));
674
675                 add_connection (c);
676         }
677
678         for (uint32_t np = 0; np < n_physical_inputs; ++np) {
679                 char buf[32];
680                 snprintf (buf, sizeof (buf), _("in %" PRIu32), np+1);
681
682                 Connection* c = new InputConnection (buf, true);
683
684                 c->add_port ();
685                 c->add_connection (0, _engine.get_nth_physical_input (np));
686
687                 add_connection (c);
688         }
689
690         /* TWO: STEREO */
691
692         for (uint32_t np = 0; np < n_physical_outputs; np +=2) {
693                 char buf[32];
694                 snprintf (buf, sizeof (buf), _("out %" PRIu32 "+%" PRIu32), np+1, np+2);
695
696                 Connection* c = new OutputConnection (buf, true);
697
698                 c->add_port ();
699                 c->add_port ();
700                 c->add_connection (0, _engine.get_nth_physical_output (np));
701                 c->add_connection (1, _engine.get_nth_physical_output (np+1));
702
703                 add_connection (c);
704         }
705
706         for (uint32_t np = 0; np < n_physical_inputs; np +=2) {
707                 char buf[32];
708                 snprintf (buf, sizeof (buf), _("in %" PRIu32 "+%" PRIu32), np+1, np+2);
709
710                 Connection* c = new InputConnection (buf, true);
711
712                 c->add_port ();
713                 c->add_port ();
714                 c->add_connection (0, _engine.get_nth_physical_input (np));
715                 c->add_connection (1, _engine.get_nth_physical_input (np+1));
716
717                 add_connection (c);
718         }
719
720         /* THREE MASTER */
721
722         if (_master_out) {
723
724                 /* create master/control ports */
725                 
726                 if (_master_out) {
727                         uint32_t n;
728
729                         /* force the master to ignore any later call to this */
730                         
731                         if (_master_out->pending_state_node) {
732                                 _master_out->ports_became_legal();
733                         }
734
735                         /* no panner resets till we are through */
736                         
737                         _master_out->defer_pan_reset ();
738                         
739                         while ((int) _master_out->n_inputs() < _master_out->input_maximum()) {
740                                 if (_master_out->add_input_port ("", this)) {
741                                         error << _("cannot setup master inputs") 
742                                               << endmsg;
743                                         break;
744                                 }
745                         }
746                         n = 0;
747                         while ((int) _master_out->n_outputs() < _master_out->output_maximum()) {
748                                 if (_master_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
749                                         error << _("cannot setup master outputs")
750                                               << endmsg;
751                                         break;
752                                 }
753                                 n++;
754                         }
755
756                         _master_out->allow_pan_reset ();
757                         
758                 }
759
760                 Connection* c = new OutputConnection (_("Master Out"), true);
761
762                 for (uint32_t n = 0; n < _master_out->n_inputs (); ++n) {
763                         c->add_port ();
764                         c->add_connection ((int) n, _master_out->input(n)->name());
765                 }
766                 add_connection (c);
767         } 
768
769         hookup_io ();
770
771         /* catch up on send+insert cnts */
772
773         insert_cnt = 0;
774         
775         for (list<PortInsert*>::iterator i = _port_inserts.begin(); i != _port_inserts.end(); ++i) {
776                 uint32_t id;
777
778                 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
779                         if (id > insert_cnt) {
780                                 insert_cnt = id;
781                         }
782                 }
783         }
784
785         send_cnt = 0;
786
787         for (list<Send*>::iterator i = _sends.begin(); i != _sends.end(); ++i) {
788                 uint32_t id;
789                 
790                 if (sscanf ((*i)->name().c_str(), "%*s %u", &id) == 1) {
791                         if (id > send_cnt) {
792                                 send_cnt = id;
793                         }
794                 }
795         }
796
797         _state_of_the_state = StateOfTheState (_state_of_the_state & ~(CannotSave|Dirty));
798
799         /* hook us up to the engine */
800
801         _engine.set_session (this);
802
803 #ifdef HAVE_LIBLO
804         /* and to OSC */
805
806         osc->set_session (*this);
807 #endif
808     
809         _state_of_the_state = Clean;
810
811         DirtyChanged (); /* EMIT SIGNAL */
812 }
813
814 void
815 Session::hookup_io ()
816 {
817         /* stop graph reordering notifications from
818            causing resorts, etc.
819         */
820
821         _state_of_the_state = StateOfTheState (_state_of_the_state | InitialConnecting);
822
823         /* Tell all IO objects to create their ports */
824
825         IO::enable_ports ();
826
827         if (_control_out) {
828                 uint32_t n;
829
830                 while ((int) _control_out->n_inputs() < _control_out->input_maximum()) {
831                         if (_control_out->add_input_port ("", this)) {
832                                 error << _("cannot setup control inputs")
833                                       << endmsg;
834                                 break;
835                         }
836                 }
837                 n = 0;
838                 while ((int) _control_out->n_outputs() < _control_out->output_maximum()) {
839                         if (_control_out->add_output_port (_engine.get_nth_physical_output (n), this)) {
840                                 error << _("cannot set up master outputs")
841                                       << endmsg;
842                                 break;
843                         }
844                         n++;
845                 }
846         }
847
848         /* Tell all IO objects to connect themselves together */
849
850         IO::enable_connecting ();
851
852         /* Now reset all panners */
853
854         IO::reset_panners ();
855
856         /* Anyone who cares about input state, wake up and do something */
857
858         IOConnectionsComplete (); /* EMIT SIGNAL */
859
860         _state_of_the_state = StateOfTheState (_state_of_the_state & ~InitialConnecting);
861
862         /* now handle the whole enchilada as if it was one
863            graph reorder event.
864         */
865
866         graph_reordered ();
867
868         /* update mixer solo state */
869
870         catch_up_on_solo();
871 }
872
873 void
874 Session::playlist_length_changed (Playlist* pl)
875 {
876         /* we can't just increase end_location->end() if pl->get_maximum_extent() 
877            if larger. if the playlist used to be the longest playlist,
878            and its now shorter, we have to decrease end_location->end(). hence,
879            we have to iterate over all diskstreams and check the 
880            playlists currently in use.
881         */
882         find_current_end ();
883 }
884
885 void
886 Session::diskstream_playlist_changed (AudioDiskstream* dstream)
887 {
888         Playlist *playlist;
889
890         if ((playlist = dstream->playlist()) != 0) {
891           playlist->LengthChanged.connect (sigc::bind (mem_fun (this, &Session::playlist_length_changed), playlist));
892         }
893         
894         /* see comment in playlist_length_changed () */
895         find_current_end ();
896 }
897
898 bool
899 Session::record_enabling_legal () const
900 {
901         /* this used to be in here, but survey says.... we don't need to restrict it */
902         // if (record_status() == Recording) {
903         //      return false;
904         // }
905
906         if (all_safe) {
907                 return false;
908         }
909         return true;
910 }
911
912 void
913 Session::set_auto_play (bool yn)
914 {
915         if (auto_play != yn) {
916                 auto_play = yn; 
917                 set_dirty ();
918                 ControlChanged (AutoPlay);
919         }
920 }
921
922 void
923 Session::set_auto_return (bool yn)
924 {
925         if (auto_return != yn) {
926                 auto_return = yn; 
927                 set_dirty ();
928                 ControlChanged (AutoReturn);
929         }
930 }
931
932 void
933 Session::set_crossfades_active (bool yn)
934 {
935         if (crossfades_active != yn) {
936                 crossfades_active = yn; 
937                 set_dirty ();
938                 ControlChanged (CrossFadesActive);
939         }
940 }
941
942 void
943 Session::set_do_not_record_plugins (bool yn)
944 {
945         if (do_not_record_plugins != yn) {
946                 do_not_record_plugins = yn; 
947                 set_dirty ();
948                 ControlChanged (RecordingPlugins); 
949         }
950 }
951
952 void
953 Session::set_auto_input (bool yn)
954 {
955         if (auto_input != yn) {
956                 auto_input = yn;
957                 
958                 if (Config->get_use_hardware_monitoring() && transport_rolling()) {
959                         /* auto-input only makes a difference if we're rolling */
960
961                         /* Even though this can called from RT context we are using
962                            a non-tentative rwlock here,  because the action must occur.
963                            The rarity and short potential lock duration makes this "OK"
964                         */
965                         Glib::RWLock::ReaderLock dsm (diskstream_lock);
966                         for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
967                                 if ((*i)->record_enabled ()) {
968                                         //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
969                                         (*i)->monitor_input (!auto_input);   
970                                 }
971                         }
972                 }
973
974                 set_dirty();
975                 ControlChanged (AutoInput);
976         }
977 }
978
979 void
980 Session::reset_input_monitor_state ()
981 {
982         if (transport_rolling()) {
983                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
984                 for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
985                         if ((*i)->record_enabled ()) {
986                                 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
987                                 (*i)->monitor_input (Config->get_use_hardware_monitoring() && !auto_input);
988                         }
989                 }
990         } else {
991                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
992                 for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
993                         if ((*i)->record_enabled ()) {
994                                 //cerr << "switching to input = " << !auto_input << __FILE__ << __LINE__ << endl << endl;
995                                 (*i)->monitor_input (Config->get_use_hardware_monitoring());
996                         }
997                 }
998         }
999 }
1000
1001
1002 void
1003 Session::set_input_auto_connect (bool yn)
1004 {
1005         if (yn) {
1006                 input_auto_connect = AutoConnectOption (input_auto_connect|AutoConnectPhysical);
1007         } else {
1008                 input_auto_connect = AutoConnectOption (input_auto_connect|~AutoConnectPhysical);
1009         }
1010         set_dirty ();
1011 }
1012
1013 bool
1014 Session::get_input_auto_connect () const
1015 {
1016         return (input_auto_connect & AutoConnectPhysical);
1017 }
1018
1019 void
1020 Session::set_output_auto_connect (AutoConnectOption aco)
1021 {
1022         output_auto_connect = aco;
1023         set_dirty ();
1024 }
1025
1026 void
1027 Session::auto_punch_start_changed (Location* location)
1028 {
1029         replace_event (Event::PunchIn, location->start());
1030
1031         if (get_record_enabled() && get_punch_in()) {
1032                 /* capture start has been changed, so save new pending state */
1033                 save_state ("", true);
1034         }
1035 }       
1036
1037 void
1038 Session::auto_punch_end_changed (Location* location)
1039 {
1040         jack_nframes_t when_to_stop = location->end();
1041         // when_to_stop += _worst_output_latency + _worst_input_latency;
1042         replace_event (Event::PunchOut, when_to_stop);
1043 }       
1044
1045 void
1046 Session::auto_punch_changed (Location* location)
1047 {
1048         jack_nframes_t when_to_stop = location->end();
1049
1050         replace_event (Event::PunchIn, location->start());
1051         //when_to_stop += _worst_output_latency + _worst_input_latency;
1052         replace_event (Event::PunchOut, when_to_stop);
1053 }       
1054
1055 void
1056 Session::auto_loop_changed (Location* location)
1057 {
1058         replace_event (Event::AutoLoop, location->end(), location->start());
1059
1060         if (transport_rolling() && get_auto_loop()) {
1061
1062                 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
1063
1064                 if (_transport_frame > location->end()) {
1065                         // relocate to beginning of loop
1066                         clear_events (Event::LocateRoll);
1067                         
1068                         request_locate (location->start(), true);
1069
1070                 }
1071                 else if (seamless_loop && !loop_changing) {
1072                         
1073                         // schedule a locate-roll to refill the audio_diskstreams at the
1074                         // previous loop end
1075                         loop_changing = true;
1076
1077                         if (location->end() > last_loopend) {
1078                                 clear_events (Event::LocateRoll);
1079                                 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
1080                                 queue_event (ev);
1081                         }
1082
1083                 }
1084         }       
1085
1086         last_loopend = location->end();
1087         
1088 }
1089
1090 void
1091 Session::set_auto_punch_location (Location* location)
1092 {
1093         Location* existing;
1094
1095         if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
1096                 auto_punch_start_changed_connection.disconnect();
1097                 auto_punch_end_changed_connection.disconnect();
1098                 auto_punch_changed_connection.disconnect();
1099                 existing->set_auto_punch (false, this);
1100                 remove_event (existing->start(), Event::PunchIn);
1101                 clear_events (Event::PunchOut);
1102                 auto_punch_location_changed (0);
1103         }
1104
1105         set_dirty();
1106
1107         if (location == 0) {
1108                 return;
1109         }
1110         
1111         if (location->end() <= location->start()) {
1112                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1113                 return;
1114         }
1115
1116         auto_punch_start_changed_connection.disconnect();
1117         auto_punch_end_changed_connection.disconnect();
1118         auto_punch_changed_connection.disconnect();
1119                 
1120         auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1121         auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1122         auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1123
1124         location->set_auto_punch (true, this);
1125         auto_punch_location_changed (location);
1126 }
1127
1128 void
1129 Session::set_punch_in (bool yn)
1130 {
1131         if (punch_in == yn) {
1132                 return;
1133         }
1134
1135         Location* location;
1136
1137         if ((location = _locations.auto_punch_location()) != 0) {
1138                 if ((punch_in = yn) == true) {
1139                         replace_event (Event::PunchIn, location->start());
1140                 } else {
1141                         remove_event (location->start(), Event::PunchIn);
1142                 }
1143         }
1144
1145         set_dirty();
1146         ControlChanged (PunchIn); /* EMIT SIGNAL */
1147 }
1148
1149 void
1150 Session::set_punch_out (bool yn)
1151 {
1152         if (punch_out == yn) {
1153                 return;
1154         }
1155
1156         Location* location;
1157
1158         if ((location = _locations.auto_punch_location()) != 0) {
1159                 if ((punch_out = yn) == true) {
1160                         replace_event (Event::PunchOut, location->end());
1161                 } else {
1162                         clear_events (Event::PunchOut);
1163                 }
1164         }
1165
1166         set_dirty();
1167         ControlChanged (PunchOut); /* EMIT SIGNAL */
1168 }
1169
1170 void
1171 Session::set_auto_loop_location (Location* location)
1172 {
1173         Location* existing;
1174
1175         if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1176                 auto_loop_start_changed_connection.disconnect();
1177                 auto_loop_end_changed_connection.disconnect();
1178                 auto_loop_changed_connection.disconnect();
1179                 existing->set_auto_loop (false, this);
1180                 remove_event (existing->end(), Event::AutoLoop);
1181                 auto_loop_location_changed (0);
1182         }
1183         
1184         set_dirty();
1185
1186         if (location == 0) {
1187                 return;
1188         }
1189
1190         if (location->end() <= location->start()) {
1191                 error << _("Session: you can't use a mark for auto loop") << endmsg;
1192                 return;
1193         }
1194
1195         last_loopend = location->end();
1196         
1197         auto_loop_start_changed_connection.disconnect();
1198         auto_loop_end_changed_connection.disconnect();
1199         auto_loop_changed_connection.disconnect();
1200         
1201         auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1202         auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1203         auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1204
1205         location->set_auto_loop (true, this);
1206         auto_loop_location_changed (location);
1207 }
1208
1209 void
1210 Session::locations_added (Location* ignored)
1211 {
1212         set_dirty ();
1213 }
1214
1215 void
1216 Session::locations_changed ()
1217 {
1218         _locations.apply (*this, &Session::handle_locations_changed);
1219 }
1220
1221 void
1222 Session::handle_locations_changed (Locations::LocationList& locations)
1223 {
1224         Locations::LocationList::iterator i;
1225         Location* location;
1226         bool set_loop = false;
1227         bool set_punch = false;
1228
1229         for (i = locations.begin(); i != locations.end(); ++i) {
1230
1231                 location =* i;
1232
1233                 if (location->is_auto_punch()) {
1234                         set_auto_punch_location (location);
1235                         set_punch = true;
1236                 }
1237                 if (location->is_auto_loop()) {
1238                         set_auto_loop_location (location);
1239                         set_loop = true;
1240                 }
1241                 
1242         }
1243
1244         if (!set_loop) {
1245                 set_auto_loop_location (0);
1246         }
1247         if (!set_punch) {
1248                 set_auto_punch_location (0);
1249         }
1250
1251         set_dirty();
1252 }                                                    
1253
1254 void
1255 Session::enable_record ()
1256 {
1257         /* XXX really atomic compare+swap here */
1258         if (g_atomic_int_get (&_record_status) != Recording) {
1259                 g_atomic_int_set (&_record_status, Recording);
1260                 _last_record_location = _transport_frame;
1261                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
1262
1263                 if (Config->get_use_hardware_monitoring() && auto_input) {
1264                         /* Even though this can be called from RT context we are using
1265                            a non-tentative rwlock here,  because the action must occur.
1266                            The rarity and short potential lock duration makes this "OK"
1267                         */
1268                         Glib::RWLock::ReaderLock dsm (diskstream_lock);
1269                         
1270                         for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
1271                                 if ((*i)->record_enabled ()) {
1272                                         (*i)->monitor_input (true);   
1273                                 }
1274                         }
1275                 }
1276
1277                 RecordStateChanged ();
1278         }
1279 }
1280
1281 void
1282 Session::disable_record (bool rt_context, bool force)
1283 {
1284         RecordState rs;
1285
1286         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1287
1288                 if (!Config->get_latched_record_enable () || force) {
1289                         g_atomic_int_set (&_record_status, Disabled);
1290                 } else {
1291                         if (rs == Recording) {
1292                                 g_atomic_int_set (&_record_status, Enabled);
1293                         }
1294                 }
1295
1296                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
1297
1298                 if (Config->get_use_hardware_monitoring() && auto_input) {
1299                         /* Even though this can be called from RT context we are using
1300                            a non-tentative rwlock here,  because the action must occur.
1301                            The rarity and short potential lock duration makes this "OK"
1302                         */
1303                         Glib::RWLock::ReaderLock dsm (diskstream_lock);
1304                         
1305                         for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
1306                                 if ((*i)->record_enabled ()) {
1307                                         (*i)->monitor_input (false);   
1308                                 }
1309                         }
1310                 }
1311                 
1312                 RecordStateChanged (); /* emit signal */
1313
1314                 if (!rt_context) {
1315                         remove_pending_capture_state ();
1316                 }
1317         }
1318 }
1319
1320 void
1321 Session::step_back_from_record ()
1322 {
1323         g_atomic_int_set (&_record_status, Enabled);
1324
1325         if (Config->get_use_hardware_monitoring()) {
1326                 /* Even though this can be called from RT context we are using
1327                    a non-tentative rwlock here,  because the action must occur.
1328                    The rarity and short potential lock duration makes this "OK"
1329                 */
1330                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
1331                 
1332                 for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
1333                         if (auto_input && (*i)->record_enabled ()) {
1334                                 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1335                                 (*i)->monitor_input (false);   
1336                         }
1337                 }
1338         }
1339 }
1340
1341 void
1342 Session::maybe_enable_record ()
1343 {
1344         g_atomic_int_set (&_record_status, Enabled);
1345
1346         /* XXX this save should really happen in another thread. its needed so that
1347            pending capture state can be recovered if we crash.
1348         */
1349
1350         save_state ("", true);
1351
1352         if (_transport_speed) {
1353                 if (!punch_in) {
1354                         enable_record ();
1355                 } 
1356         } else {
1357                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
1358                 RecordStateChanged (); /* EMIT SIGNAL */
1359         }
1360
1361         set_dirty();
1362 }
1363
1364 jack_nframes_t
1365 Session::audible_frame () const
1366 {
1367         jack_nframes_t ret;
1368         jack_nframes_t offset;
1369         jack_nframes_t tf;
1370
1371         /* the first of these two possible settings for "offset"
1372            mean that the audible frame is stationary until 
1373            audio emerges from the latency compensation
1374            "pseudo-pipeline".
1375
1376            the second means that the audible frame is stationary
1377            until audio would emerge from a physical port
1378            in the absence of any plugin latency compensation
1379         */
1380
1381         offset = _worst_output_latency;
1382
1383         if (offset > current_block_size) {
1384                 offset -= current_block_size;
1385         } else { 
1386                 /* XXX is this correct? if we have no external
1387                    physical connections and everything is internal
1388                    then surely this is zero? still, how
1389                    likely is that anyway?
1390                 */
1391                 offset = current_block_size;
1392         }
1393
1394         if (synced_to_jack()) {
1395                 tf = _engine.transport_frame();
1396         } else {
1397                 tf = _transport_frame;
1398         }
1399
1400         if (_transport_speed == 0) {
1401                 return tf;
1402         }
1403
1404         if (tf < offset) {
1405                 return 0;
1406         }
1407
1408         ret = tf;
1409
1410         if (!non_realtime_work_pending()) {
1411
1412                 /* MOVING */
1413
1414                 /* take latency into account */
1415                 
1416                 ret -= offset;
1417         }
1418
1419         return ret;
1420 }
1421
1422 void
1423 Session::set_frame_rate (jack_nframes_t frames_per_second)
1424 {
1425         /** \fn void Session::set_frame_size(jack_nframes_t)
1426                 the AudioEngine object that calls this guarantees 
1427                 that it will not be called while we are also in
1428                 ::process(). Its fine to do things that block
1429                 here.
1430         */
1431
1432         _current_frame_rate = frames_per_second;
1433         _frames_per_smpte_frame = (double) _current_frame_rate / (double) smpte_frames_per_second;
1434
1435         Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
1436
1437         // XXX we need some equivalent to this, somehow
1438         // DestructiveFileSource::setup_standard_crossfades (frames_per_second);
1439
1440         set_dirty();
1441
1442         /* XXX need to reset/reinstantiate all LADSPA plugins */
1443 }
1444
1445 void
1446 Session::set_block_size (jack_nframes_t nframes)
1447 {
1448         /* the AudioEngine guarantees 
1449            that it will not be called while we are also in
1450            ::process(). It is therefore fine to do things that block
1451            here.
1452         */
1453
1454         { 
1455                 Glib::RWLock::ReaderLock lm (route_lock);
1456                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
1457                 vector<Sample*>::iterator i;
1458                 uint32_t np;
1459                         
1460                 current_block_size = nframes;
1461                 
1462                 for (np = 0, i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i, ++np) {
1463                         free (*i);
1464                 }
1465
1466                 for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
1467                         free (*i);
1468                 }
1469
1470                 _passthru_buffers.clear ();
1471                 _silent_buffers.clear ();
1472
1473                 ensure_passthru_buffers (np);
1474
1475                 for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
1476                         free(*i);
1477
1478                         Sample *buf;
1479 #ifdef NO_POSIX_MEMALIGN
1480                         buf = (Sample *) malloc(current_block_size * sizeof(Sample));
1481 #else
1482                         posix_memalign((void **)&buf,16,current_block_size * 4);
1483 #endif                  
1484                         *i = buf;
1485
1486                         memset (*i, 0, sizeof (Sample) * current_block_size);
1487                 }
1488
1489                 
1490                 if (_gain_automation_buffer) {
1491                         delete [] _gain_automation_buffer;
1492                 }
1493                 _gain_automation_buffer = new gain_t[nframes];
1494
1495                 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1496
1497                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1498                         (*i)->set_block_size (nframes);
1499                 }
1500                 
1501                 for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
1502                         (*i)->set_block_size (nframes);
1503                 }
1504
1505                 set_worst_io_latencies (false);
1506         }
1507 }
1508
1509 void
1510 Session::set_default_fade (float steepness, float fade_msecs)
1511 {
1512 #if 0
1513         jack_nframes_t fade_frames;
1514         
1515         /* Don't allow fade of less 1 frame */
1516         
1517         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1518
1519                 fade_msecs = 0;
1520                 fade_frames = 0;
1521
1522         } else {
1523                 
1524                 fade_frames = (jack_nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1525                 
1526         }
1527
1528         default_fade_msecs = fade_msecs;
1529         default_fade_steepness = steepness;
1530
1531         {
1532                 // jlc, WTF is this!
1533                 Glib::RWLock::ReaderLock lm (route_lock);
1534                 AudioRegion::set_default_fade (steepness, fade_frames);
1535         }
1536
1537         set_dirty();
1538
1539         /* XXX have to do this at some point */
1540         /* foreach region using default fade, reset, then 
1541            refill_all_diskstream_buffers ();
1542         */
1543 #endif
1544 }
1545
1546 struct RouteSorter {
1547     bool operator() (Route* r1, Route* r2) {
1548             if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1549                     return false;
1550             } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1551                     return true;
1552             } else {
1553                     if (r1->fed_by.empty()) {
1554                             if (r2->fed_by.empty()) {
1555                                     /* no ardour-based connections inbound to either route. just use signal order */
1556                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1557                             } else {
1558                                     /* r2 has connections, r1 does not; run r1 early */
1559                                     return true;
1560                             }
1561                     } else {
1562                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1563                     }
1564             }
1565     }
1566 };
1567
1568 static void
1569 trace_terminal (Route* r1, Route* rbase)
1570 {
1571         Route* r2;
1572
1573         if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1574                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1575                 return;
1576         } 
1577
1578         /* make a copy of the existing list of routes that feed r1 */
1579
1580         set<Route *> existing = r1->fed_by;
1581
1582         /* for each route that feeds r1, recurse, marking it as feeding
1583            rbase as well.
1584         */
1585
1586         for (set<Route *>::iterator i = existing.begin(); i != existing.end(); ++i) {
1587                 r2 =* i;
1588
1589                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1590                    base as being fed by r2
1591                 */
1592
1593                 rbase->fed_by.insert (r2);
1594
1595                 if (r2 != rbase) {
1596
1597                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1598                            stop here.
1599                          */
1600
1601                         if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1602                                 continue;
1603                         }
1604
1605                         /* now recurse, so that we can mark base as being fed by
1606                            all routes that feed r2
1607                         */
1608
1609                         trace_terminal (r2, rbase);
1610                 }
1611
1612         }
1613 }
1614
1615 void
1616 Session::resort_routes (void* src)
1617 {
1618         /* don't do anything here with signals emitted
1619            by Routes while we are being destroyed.
1620         */
1621
1622         if (_state_of_the_state & Deletion) {
1623                 return;
1624         }
1625
1626         /* Caller MUST hold the route_lock */
1627
1628         RouteList::iterator i, j;
1629
1630         for (i = routes.begin(); i != routes.end(); ++i) {
1631
1632                 (*i)->fed_by.clear ();
1633                 
1634                 for (j = routes.begin(); j != routes.end(); ++j) {
1635
1636                         /* although routes can feed themselves, it will
1637                            cause an endless recursive descent if we
1638                            detect it. so don't bother checking for
1639                            self-feeding.
1640                         */
1641
1642                         if (*j == *i) {
1643                                 continue;
1644                         }
1645
1646                         if ((*j)->feeds (*i)) {
1647                                 (*i)->fed_by.insert (*j);
1648                         } 
1649                 }
1650         }
1651         
1652         for (i = routes.begin(); i != routes.end(); ++i) {
1653                 trace_terminal (*i, *i);
1654         }
1655
1656         RouteSorter cmp;
1657         routes.sort (cmp);
1658
1659 #if 0
1660         cerr << "finished route resort\n";
1661         
1662         for (i = routes.begin(); i != routes.end(); ++i) {
1663                 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1664         }
1665         cerr << endl;
1666 #endif
1667
1668 }
1669
1670 AudioTrack*
1671 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode)
1672 {
1673         AudioTrack *track;
1674         char track_name[32];
1675         uint32_t n = 0;
1676         uint32_t channels_used = 0;
1677         string port;
1678         uint32_t nphysical_in;
1679         uint32_t nphysical_out;
1680
1681         /* count existing audio tracks */
1682
1683         {
1684                 Glib::RWLock::ReaderLock lm (route_lock);
1685                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1686                         if (dynamic_cast<AudioTrack*>(*i) != 0) {
1687                                 if (!(*i)->hidden()) {
1688                                         n++;
1689                                         channels_used += (*i)->n_inputs();
1690                                 }
1691                         }
1692                 }
1693         }
1694
1695         /* check for duplicate route names, since we might have pre-existing
1696            routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1697            save, close,restart,add new route - first named route is now
1698            Audio2)
1699         */
1700
1701         do {
1702                 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, n+1);
1703                 if (route_by_name (track_name) == 0) {
1704                         break;
1705                 }
1706                 n++;
1707
1708         } while (n < (UINT_MAX-1));
1709
1710         if (input_auto_connect & AutoConnectPhysical) {
1711                 nphysical_in = n_physical_inputs;
1712         } else {
1713                 nphysical_in = 0;
1714         }
1715
1716         if (output_auto_connect & AutoConnectPhysical) {
1717                 nphysical_out = n_physical_outputs;
1718         } else {
1719                 nphysical_out = 0;
1720         }
1721
1722         try {
1723                 track = new AudioTrack (*this, track_name, Route::Flag (0), mode);
1724
1725                 if (track->ensure_io (input_channels, output_channels, false, this)) {
1726                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1727                                           input_channels, output_channels)
1728                               << endmsg;
1729                 }
1730
1731                 if (nphysical_in) {
1732                         for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
1733                                 
1734                                 port = "";
1735                                 
1736                                 if (input_auto_connect & AutoConnectPhysical) {
1737                                         port = _engine.get_nth_physical_input ((channels_used+x)%nphysical_in);
1738                                 } 
1739                                 
1740                                 if (port.length() && track->connect_input (track->input (x), port, this)) {
1741                                         break;
1742                                 }
1743                         }
1744                 }
1745                 
1746                 for (uint32_t x = 0; x < track->n_outputs(); ++x) {
1747                         
1748                         port = "";
1749
1750                         if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
1751                                 port = _engine.get_nth_physical_output ((channels_used+x)%nphysical_out);
1752                         } else if (output_auto_connect & AutoConnectMaster) {
1753                                 if (_master_out) {
1754                                         port = _master_out->input (x%_master_out->n_inputs())->name();
1755                                 }
1756                         }
1757
1758                         if (port.length() && track->connect_output (track->output (x), port, this)) {
1759                                 break;
1760                         }
1761                 }
1762
1763                 if (_control_out) {
1764                         vector<string> cports;
1765                         uint32_t ni = _control_out->n_inputs();
1766
1767                         for (n = 0; n < ni; ++n) {
1768                                 cports.push_back (_control_out->input(n)->name());
1769                         }
1770
1771                         track->set_control_outs (cports);
1772                 }
1773
1774                 track->diskstream_changed.connect (mem_fun (this, &Session::resort_routes));
1775
1776                 add_route (track);
1777
1778                 track->set_remote_control_id (ntracks());
1779         }
1780
1781         catch (failed_constructor &err) {
1782                 error << _("Session: could not create new audio track.") << endmsg;
1783                 return 0;
1784         }
1785
1786         return track;
1787 }
1788
1789 Route*
1790 Session::new_audio_route (int input_channels, int output_channels)
1791 {
1792         Route *bus;
1793         char bus_name[32];
1794         uint32_t n = 0;
1795         string port;
1796
1797         /* count existing audio busses */
1798
1799         {
1800                 Glib::RWLock::ReaderLock lm (route_lock);
1801                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1802                         if (dynamic_cast<AudioTrack*>(*i) == 0) {
1803                                 if (!(*i)->hidden()) {
1804                                         n++;
1805                                 }
1806                         }
1807                 }
1808         }
1809
1810         do {
1811                 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, n+1);
1812                 if (route_by_name (bus_name) == 0) {
1813                         break;
1814                 }
1815                 n++;
1816
1817         } while (n < (UINT_MAX-1));
1818
1819         try {
1820                 bus = new Route (*this, bus_name, -1, -1, -1, -1);
1821
1822                 if (bus->ensure_io (input_channels, output_channels, false, this)) {
1823                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1824                                           input_channels, output_channels)
1825                               << endmsg;
1826                 }
1827
1828                 for (uint32_t x = 0; x < bus->n_inputs(); ++x) {
1829                         
1830                         port = "";
1831
1832                         if (input_auto_connect & AutoConnectPhysical) {
1833                                 port = _engine.get_nth_physical_input ((n+x)%n_physical_inputs);
1834                         } 
1835                         
1836                         if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1837                                 break;
1838                         }
1839                 }
1840
1841                 for (uint32_t x = 0; x < bus->n_outputs(); ++x) {
1842                         
1843                         port = "";
1844
1845                         if (output_auto_connect & AutoConnectPhysical) {
1846                                 port = _engine.get_nth_physical_input ((n+x)%n_physical_outputs);
1847                         } else if (output_auto_connect & AutoConnectMaster) {
1848                                 if (_master_out) {
1849                                         port = _master_out->input (x%_master_out->n_inputs())->name();
1850                                 }
1851                         }
1852
1853                         if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1854                                 break;
1855                         }
1856                 }
1857
1858                 if (_control_out) {
1859                         vector<string> cports;
1860                         uint32_t ni = _control_out->n_inputs();
1861
1862                         for (uint32_t n = 0; n < ni; ++n) {
1863                                 cports.push_back (_control_out->input(n)->name());
1864                         }
1865                         bus->set_control_outs (cports);
1866                 }
1867                 
1868                 add_route (bus);
1869         }
1870
1871         catch (failed_constructor &err) {
1872                 error << _("Session: could not create new route.") << endmsg;
1873                 return 0;
1874         }
1875
1876         return bus;
1877 }
1878
1879 void
1880 Session::add_route (Route* route)
1881 {
1882         { 
1883                 Glib::RWLock::WriterLock lm (route_lock);
1884                 routes.push_front (route);
1885                 resort_routes(0);
1886         }
1887
1888         route->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), route));
1889         route->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1890         route->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1891         route->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
1892
1893         if (route->master()) {
1894                 _master_out = route;
1895         }
1896
1897         if (route->control()) {
1898                 _control_out = route;
1899         }
1900
1901         set_dirty();
1902         save_state (_current_snapshot_name);
1903
1904         RouteAdded (route); /* EMIT SIGNAL */
1905 }
1906
1907 void
1908 Session::add_diskstream (AudioDiskstream* dstream)
1909 {
1910         /* need to do this in case we're rolling at the time, to prevent false underruns */
1911         dstream->do_refill(0, 0, 0);
1912         
1913         { 
1914                 Glib::RWLock::WriterLock lm (diskstream_lock);
1915                 audio_diskstreams.push_back (dstream);
1916         }
1917
1918         /* take a reference to the diskstream, preventing it from
1919            ever being deleted until the session itself goes away,
1920            or chooses to remove it for its own purposes.
1921         */
1922
1923         dstream->ref();
1924         dstream->set_block_size (current_block_size);
1925
1926         dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1927         /* this will connect to future changes, and check the current length */
1928         diskstream_playlist_changed (dstream);
1929
1930         dstream->prepare ();
1931
1932         set_dirty();
1933         save_state (_current_snapshot_name);
1934
1935         AudioDiskstreamAdded (dstream); /* EMIT SIGNAL */
1936 }
1937
1938 void
1939 Session::remove_route (Route& route)
1940 {
1941         {       
1942                 Glib::RWLock::WriterLock lm (route_lock);
1943                 routes.remove (&route);
1944                 
1945                 /* deleting the master out seems like a dumb
1946                    idea, but its more of a UI policy issue
1947                    than our concern.
1948                 */
1949
1950                 if (&route == _master_out) {
1951                         _master_out = 0;
1952                 }
1953
1954                 if (&route == _control_out) {
1955                         _control_out = 0;
1956
1957                         /* cancel control outs for all routes */
1958
1959                         vector<string> empty;
1960
1961                         for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1962                                 (*r)->set_control_outs (empty);
1963                         }
1964                 }
1965
1966                 update_route_solo_state ();
1967         }
1968
1969         AudioTrack* at;
1970         AudioDiskstream* ds = 0;
1971         
1972         if ((at = dynamic_cast<AudioTrack*>(&route)) != 0) {
1973                 ds = &at->disk_stream();
1974         }
1975         
1976         if (ds) {
1977
1978                 {
1979                         Glib::RWLock::WriterLock lm (diskstream_lock);
1980                         audio_diskstreams.remove (ds);
1981                 }
1982
1983                 ds->unref ();
1984         }
1985
1986         find_current_end ();
1987         
1988         update_latency_compensation (false, false);
1989         set_dirty();
1990         
1991         /* XXX should we disconnect from the Route's signals ? */
1992
1993         save_state (_current_snapshot_name);
1994
1995         delete &route;
1996 }       
1997
1998 void
1999 Session::route_mute_changed (void* src)
2000 {
2001         set_dirty ();
2002 }
2003
2004 void
2005 Session::route_solo_changed (void* src, Route* route)
2006 {      
2007         if (solo_update_disabled) {
2008                 // We know already
2009                 return;
2010         }
2011         
2012         Glib::RWLock::ReaderLock lm (route_lock);
2013         bool is_track;
2014         
2015         is_track = (dynamic_cast<AudioTrack*>(route) != 0);
2016         
2017         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2018                 
2019                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2020                 
2021                 if (is_track) {
2022                         
2023                         /* don't mess with busses */
2024                         
2025                         if (dynamic_cast<AudioTrack*>(*i) == 0) {
2026                                 continue;
2027                         }
2028                         
2029                 } else {
2030                         
2031                         /* don't mess with tracks */
2032                         
2033                         if (dynamic_cast<AudioTrack*>(*i) != 0) {
2034                                 continue;
2035                         }
2036                 }
2037                 
2038                 if ((*i) != route &&
2039                     ((*i)->mix_group () == 0 ||
2040                      (*i)->mix_group () != route->mix_group () ||
2041                      !route->mix_group ()->is_active())) {
2042                         
2043                         if ((*i)->soloed()) {
2044                                 
2045                                 /* if its already soloed, and solo latching is enabled,
2046                                    then leave it as it is.
2047                                 */
2048                                 
2049                                 if (_solo_latched) {
2050                                         continue;
2051                                 } 
2052                         }
2053                         
2054                         /* do it */
2055
2056                         solo_update_disabled = true;
2057                         (*i)->set_solo (false, src);
2058                         solo_update_disabled = false;
2059                 }
2060         }
2061         
2062         bool something_soloed = false;
2063         bool same_thing_soloed = false;
2064         bool signal = false;
2065
2066         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2067                 if ((*i)->soloed()) {
2068                         something_soloed = true;
2069                         if (dynamic_cast<AudioTrack*>(*i)) {
2070                                 if (is_track) {
2071                                         same_thing_soloed = true;
2072                                         break;
2073                                 }
2074                         } else {
2075                                 if (!is_track) {
2076                                         same_thing_soloed = true;
2077                                         break;
2078                                 }
2079                         }
2080                         break;
2081                 }
2082         }
2083         
2084         if (something_soloed != currently_soloing) {
2085                 signal = true;
2086                 currently_soloing = something_soloed;
2087         }
2088         
2089         modify_solo_mute (is_track, same_thing_soloed);
2090
2091         if (signal) {
2092                 SoloActive (currently_soloing);
2093         }
2094
2095         set_dirty();
2096 }
2097
2098 void
2099 Session::set_solo_latched (bool yn)
2100 {
2101         if (yn != _solo_latched) {
2102                 _solo_latched = yn;
2103                 set_dirty ();
2104                 ControlChanged (SoloLatch);
2105         }
2106 }
2107
2108 void
2109 Session::update_route_solo_state ()
2110 {
2111         bool mute = false;
2112         bool is_track = false;
2113         bool signal = false;
2114
2115         /* caller must hold RouteLock */
2116
2117         /* this is where we actually implement solo by changing
2118            the solo mute setting of each track.
2119         */
2120                 
2121         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2122                 if ((*i)->soloed()) {
2123                         mute = true;
2124                         if (dynamic_cast<AudioTrack*>(*i)) {
2125                                 is_track = true;
2126                         }
2127                         break;
2128                 }
2129         }
2130
2131         if (mute != currently_soloing) {
2132                 signal = true;
2133                 currently_soloing = mute;
2134         }
2135
2136         if (!is_track && !mute) {
2137
2138                 /* nothing is soloed */
2139
2140                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2141                         (*i)->set_solo_mute (false);
2142                 }
2143                 
2144                 if (signal) {
2145                         SoloActive (false);
2146                 }
2147
2148                 return;
2149         }
2150
2151         modify_solo_mute (is_track, mute);
2152
2153         if (signal) {
2154                 SoloActive (currently_soloing);
2155         }
2156 }
2157
2158 void
2159 Session::modify_solo_mute (bool is_track, bool mute)
2160 {
2161         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2162                 
2163                 if (is_track) {
2164                         
2165                         /* only alter track solo mute */
2166                         
2167                         if (dynamic_cast<AudioTrack*>(*i)) {
2168                                 if ((*i)->soloed()) {
2169                                         (*i)->set_solo_mute (!mute);
2170                                 } else {
2171                                         (*i)->set_solo_mute (mute);
2172                                 }
2173                         }
2174
2175                 } else {
2176
2177                         /* only alter bus solo mute */
2178
2179                         if (!dynamic_cast<AudioTrack*>(*i)) {
2180
2181                                 if ((*i)->soloed()) {
2182
2183                                         (*i)->set_solo_mute (false);
2184
2185                                 } else {
2186
2187                                         /* don't mute master or control outs
2188                                            in response to another bus solo
2189                                         */
2190                                         
2191                                         if ((*i) != _master_out &&
2192                                             (*i) != _control_out) {
2193                                                 (*i)->set_solo_mute (mute);
2194                                         }
2195                                 }
2196                         }
2197
2198                 }
2199         }
2200 }       
2201
2202
2203 void
2204 Session::catch_up_on_solo ()
2205 {
2206         /* this is called after set_state() to catch the full solo
2207            state, which can't be correctly determined on a per-route
2208            basis, but needs the global overview that only the session
2209            has.
2210         */
2211         Glib::RWLock::ReaderLock lm (route_lock);
2212         update_route_solo_state();
2213 }       
2214                 
2215 Route *
2216 Session::route_by_name (string name)
2217 {
2218         Glib::RWLock::ReaderLock lm (route_lock);
2219
2220         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2221                 if ((*i)->name() == name) {
2222                         return* i;
2223                 }
2224         }
2225
2226         return 0;
2227 }
2228
2229 Route *
2230 Session::route_by_remote_id (uint32_t id)
2231 {
2232         Glib::RWLock::ReaderLock lm (route_lock);
2233
2234         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2235                 if ((*i)->remote_control_id() == id) {
2236                         return* i;
2237                 }
2238         }
2239
2240         return 0;
2241 }
2242
2243 void
2244 Session::find_current_end ()
2245 {
2246         if (_state_of_the_state & Loading) {
2247                 return;
2248         }
2249
2250         jack_nframes_t max = get_maximum_extent ();
2251
2252         if (max > end_location->end()) {
2253                 end_location->set_end (max);
2254                 set_dirty();
2255                 DurationChanged(); /* EMIT SIGNAL */
2256         }
2257 }
2258
2259 jack_nframes_t
2260 Session::get_maximum_extent () const
2261 {
2262         jack_nframes_t max = 0;
2263         jack_nframes_t me; 
2264
2265         /* Don't take the diskstream lock. Caller must have other ways to
2266            ensure atomicity.
2267         */
2268
2269         for (AudioDiskstreamList::const_iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
2270                 Playlist* pl = (*i)->playlist();
2271                 if ((me = pl->get_maximum_extent()) > max) {
2272                         max = me;
2273                 }
2274         }
2275
2276         return max;
2277 }
2278
2279 AudioDiskstream *
2280 Session::diskstream_by_name (string name)
2281 {
2282         Glib::RWLock::ReaderLock lm (diskstream_lock);
2283
2284         for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
2285                 if ((*i)->name() == name) {
2286                         return* i;
2287                 }
2288         }
2289
2290         return 0;
2291 }
2292
2293 AudioDiskstream *
2294 Session::diskstream_by_id (const PBD::ID& id)
2295 {
2296         Glib::RWLock::ReaderLock lm (diskstream_lock);
2297
2298         for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
2299                 if ((*i)->id() == id) {
2300                         return *i;
2301                 }
2302         }
2303
2304         return 0;
2305 }
2306
2307 /* AudioRegion management */
2308
2309 string
2310 Session::new_region_name (string old)
2311 {
2312         string::size_type last_period;
2313         uint32_t number;
2314         string::size_type len = old.length() + 64;
2315         char buf[len];
2316
2317         if ((last_period = old.find_last_of ('.')) == string::npos) {
2318                 
2319                 /* no period present - add one explicitly */
2320
2321                 old += '.';
2322                 last_period = old.length() - 1;
2323                 number = 0;
2324
2325         } else {
2326
2327                 number = atoi (old.substr (last_period+1).c_str());
2328
2329         }
2330
2331         while (number < (UINT_MAX-1)) {
2332
2333                 AudioRegionList::const_iterator i;
2334                 string sbuf;
2335
2336                 number++;
2337
2338                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2339                 sbuf = buf;
2340
2341                 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2342                         if (i->second->name() == sbuf) {
2343                                 break;
2344                         }
2345                 }
2346                 
2347                 if (i == audio_regions.end()) {
2348                         break;
2349                 }
2350         }
2351
2352         if (number != (UINT_MAX-1)) {
2353                 return buf;
2354         } 
2355
2356         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2357         return old;
2358 }
2359
2360 int
2361 Session::region_name (string& result, string base, bool newlevel) const
2362 {
2363         char buf[16];
2364         string subbase;
2365
2366         if (base == "") {
2367                 
2368                 Glib::Mutex::Lock lm (region_lock);
2369
2370                 snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
2371
2372                 
2373                 result = "region.";
2374                 result += buf;
2375
2376         } else {
2377
2378                 /* XXX this is going to be slow. optimize me later */
2379                 
2380                 if (newlevel) {
2381                         subbase = base;
2382                 } else {
2383                         string::size_type pos;
2384
2385                         pos = base.find_last_of ('.');
2386
2387                         /* pos may be npos, but then we just use entire base */
2388
2389                         subbase = base.substr (0, pos);
2390
2391                 }
2392
2393                 bool name_taken = true;
2394                 
2395                 {
2396                         Glib::Mutex::Lock lm (region_lock);
2397                         
2398                         for (int n = 1; n < 5000; ++n) {
2399                                 
2400                                 result = subbase;
2401                                 snprintf (buf, sizeof (buf), ".%d", n);
2402                                 result += buf;
2403                                 
2404                                 name_taken = false;
2405                                 
2406                                 for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2407                                         if (i->second->name() == result) {
2408                                                 name_taken = true;
2409                                                 break;
2410                                         }
2411                                 }
2412                                 
2413                                 if (!name_taken) {
2414                                         break;
2415                                 }
2416                         }
2417                 }
2418                         
2419                 if (name_taken) {
2420                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2421                         /*NOTREACHED*/
2422                 }
2423         }
2424         return 0;
2425 }       
2426
2427 void
2428 Session::add_region (Region* region)
2429 {
2430         AudioRegion* ar = 0;
2431         AudioRegion* oar = 0;
2432         bool added = false;
2433
2434         { 
2435                 Glib::Mutex::Lock lm (region_lock);
2436
2437                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2438
2439                         AudioRegionList::iterator x;
2440
2441                         for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
2442
2443                                 oar = dynamic_cast<AudioRegion*> (x->second);
2444
2445                                 if (ar->region_list_equivalent (*oar)) {
2446                                         break;
2447                                 }
2448                         }
2449
2450                         if (x == audio_regions.end()) {
2451
2452                                 pair<AudioRegionList::key_type,AudioRegionList::mapped_type> entry;
2453
2454                                 entry.first = region->id();
2455                                 entry.second = ar;
2456
2457                                 pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
2458                                 
2459                                 if (!x.second) {
2460                                         return;
2461                                 }
2462
2463                                 added = true;
2464                         } 
2465
2466                 } else {
2467
2468                         fatal << _("programming error: ")
2469                               << X_("unknown region type passed to Session::add_region()")
2470                               << endmsg;
2471                         /*NOTREACHED*/
2472
2473                 }
2474         }
2475
2476         /* mark dirty because something has changed even if we didn't
2477            add the region to the region list.
2478         */
2479         
2480         set_dirty();
2481         
2482         if (added) {
2483                 region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
2484                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
2485                 AudioRegionAdded (ar); /* EMIT SIGNAL */
2486         }
2487 }
2488
2489 void
2490 Session::region_changed (Change what_changed, Region* region)
2491 {
2492         if (what_changed & Region::HiddenChanged) {
2493                 /* relay hidden changes */
2494                 RegionHiddenChange (region);
2495         }
2496 }
2497
2498 void
2499 Session::region_renamed (Region* region)
2500 {
2501         add_region (region);
2502 }
2503
2504 void
2505 Session::remove_region (Region* region)
2506 {
2507         AudioRegionList::iterator i;
2508         AudioRegion* ar = 0;
2509         bool removed = false;
2510         
2511         { 
2512                 Glib::Mutex::Lock lm (region_lock);
2513
2514                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2515                         if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
2516                                 audio_regions.erase (i);
2517                                 removed = true;
2518                         }
2519
2520                 } else {
2521
2522                         fatal << _("programming error: ") 
2523                               << X_("unknown region type passed to Session::remove_region()")
2524                               << endmsg;
2525                         /*NOTREACHED*/
2526                 }
2527         }
2528
2529         /* mark dirty because something has changed even if we didn't
2530            remove the region from the region list.
2531         */
2532
2533         set_dirty();
2534
2535         if (removed) {
2536                  AudioRegionRemoved(ar); /* EMIT SIGNAL */
2537         }
2538 }
2539
2540 AudioRegion*
2541 Session::find_whole_file_parent (AudioRegion& child)
2542 {
2543         AudioRegionList::iterator i;
2544         AudioRegion* region;
2545         Glib::Mutex::Lock lm (region_lock);
2546
2547         for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2548
2549                 region = i->second;
2550
2551                 if (region->whole_file()) {
2552
2553                         if (child.source_equivalent (*region)) {
2554                                 return region;
2555                         }
2556                 }
2557         } 
2558
2559         return 0;
2560 }       
2561
2562 void
2563 Session::find_equivalent_playlist_regions (AudioRegion& region, vector<AudioRegion*>& result)
2564 {
2565         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2566
2567                 AudioPlaylist* pl;
2568
2569                 if ((pl = dynamic_cast<AudioPlaylist*>(*i)) == 0) {
2570                         continue;
2571                 }
2572
2573                 pl->get_region_list_equivalent_regions (region, result);
2574         }
2575 }
2576
2577 int
2578 Session::destroy_region (Region* region)
2579 {
2580         AudioRegion* aregion;
2581
2582         if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
2583                 return 0;
2584         }
2585
2586         if (aregion->playlist()) {
2587                 aregion->playlist()->destroy_region (region);
2588         }
2589
2590         vector<Source*> srcs;
2591         
2592         for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2593                 srcs.push_back (&aregion->source (n));
2594         }
2595
2596         for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2597                 
2598                 if ((*i)->use_cnt() == 0) {
2599                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*i);
2600                         if (afs) {
2601                                 (afs)->mark_for_remove ();
2602                         }
2603                         delete *i;
2604                 }
2605         }
2606
2607         return 0;
2608 }
2609
2610 int
2611 Session::destroy_regions (list<Region*> regions)
2612 {
2613         for (list<Region*>::iterator i = regions.begin(); i != regions.end(); ++i) {
2614                 destroy_region (*i);
2615         }
2616         return 0;
2617 }
2618
2619 int
2620 Session::remove_last_capture ()
2621 {
2622         list<Region*> r;
2623
2624         Glib::RWLock::ReaderLock lm (diskstream_lock);
2625         
2626         for (AudioDiskstreamList::iterator i = audio_diskstreams.begin(); i != audio_diskstreams.end(); ++i) {
2627                 list<Region*>& l = (*i)->last_capture_regions();
2628                 
2629                 if (!l.empty()) {
2630                         r.insert (r.end(), l.begin(), l.end());
2631                         l.clear ();
2632                 }
2633         }
2634
2635         destroy_regions (r);
2636         return 0;
2637 }
2638
2639 int
2640 Session::remove_region_from_region_list (Region& r)
2641 {
2642         remove_region (&r);
2643         return 0;
2644 }
2645
2646 /* Source Management */
2647
2648 void
2649 Session::add_audio_source (AudioSource* source)
2650 {
2651         pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
2652
2653         {
2654                 Glib::Mutex::Lock lm (audio_source_lock);
2655                 entry.first = source->id();
2656                 entry.second = source;
2657                 audio_sources.insert (entry);
2658         }
2659         
2660         source->GoingAway.connect (mem_fun (this, &Session::remove_source));
2661         set_dirty();
2662         
2663         SourceAdded (source); /* EMIT SIGNAL */
2664 }
2665
2666 void
2667 Session::remove_source (Source* source)
2668 {
2669         AudioSourceList::iterator i;
2670
2671         { 
2672                 Glib::Mutex::Lock lm (audio_source_lock);
2673
2674                 if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
2675                         audio_sources.erase (i);
2676                 } 
2677         }
2678
2679         if (!_state_of_the_state & InCleanup) {
2680
2681                 /* save state so we don't end up with a session file
2682                    referring to non-existent sources.
2683                 */
2684                 
2685                 save_state (_current_snapshot_name);
2686         }
2687
2688         SourceRemoved(source); /* EMIT SIGNAL */
2689 }
2690
2691 Source *
2692 Session::source_by_id (const PBD::ID& id)
2693 {
2694         Glib::Mutex::Lock lm (audio_source_lock);
2695         AudioSourceList::iterator i;
2696         Source* source = 0;
2697
2698         if ((i = audio_sources.find (id)) != audio_sources.end()) {
2699                 source = i->second;
2700         }
2701
2702         /* XXX search MIDI or other searches here */
2703         
2704         return source;
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 int
3562 Session::freeze (InterThreadInfo& itt)
3563 {
3564         Glib::RWLock::ReaderLock lm (route_lock);
3565
3566         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
3567
3568                 AudioTrack *at;
3569
3570                 if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
3571                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3572                            of every track.
3573                         */
3574                         at->freeze (itt);
3575                 }
3576         }
3577
3578         return 0;
3579 }
3580
3581 int
3582 Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,    
3583                                bool overwrite, vector<AudioSource*>& srcs, InterThreadInfo& itt)
3584 {
3585         int ret = -1;
3586         Playlist* playlist;
3587         AudioFileSource* fsource;
3588         uint32_t x;
3589         char buf[PATH_MAX+1];
3590         string dir;
3591         uint32_t nchans;
3592         jack_nframes_t position;
3593         jack_nframes_t this_chunk;
3594         jack_nframes_t to_do;
3595         vector<Sample*> buffers;
3596         char *  workbuf = 0;
3597
3598         // any bigger than this seems to cause stack overflows in called functions
3599         const jack_nframes_t chunk_size = (128 * 1024)/4;
3600
3601         g_atomic_int_set (&processing_prohibited, 1);
3602         
3603         /* call tree *MUST* hold route_lock */
3604         
3605         if ((playlist = track.disk_stream().playlist()) == 0) {
3606                 goto out;
3607         }
3608
3609         /* external redirects will be a problem */
3610
3611         if (track.has_external_redirects()) {
3612                 goto out;
3613         }
3614
3615         nchans = track.disk_stream().n_channels();
3616         
3617         dir = discover_best_sound_dir ();
3618
3619         for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
3620
3621                 for (x = 0; x < 99999; ++x) {
3622                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3623                         if (access (buf, F_OK) != 0) {
3624                                 break;
3625                         }
3626                 }
3627                 
3628                 if (x == 99999) {
3629                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3630                         goto out;
3631                 }
3632                 
3633                 try {
3634                         fsource =  new SndFileSource (buf, 
3635                                                       Config->get_native_file_data_format(),
3636                                                       Config->get_native_file_header_format(),
3637                                                       frame_rate());
3638                                                             
3639                 }
3640                 
3641                 catch (failed_constructor& err) {
3642                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3643                         goto out;
3644                 }
3645
3646                 srcs.push_back(fsource);
3647         }
3648
3649         /* XXX need to flush all redirects */
3650         
3651         position = start;
3652         to_do = len;
3653
3654         /* create a set of reasonably-sized buffers */
3655
3656         for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
3657                 Sample* b;
3658 #ifdef NO_POSIX_MEMALIGN
3659                 b =  (Sample *) malloc(chunk_size * sizeof(Sample));
3660 #else
3661                 posix_memalign((void **)&b,16,chunk_size * 4);
3662 #endif                  
3663                 buffers.push_back (b);
3664         }
3665
3666         workbuf = new char[chunk_size * 4];
3667         
3668         while (to_do && !itt.cancel) {
3669                 
3670                 this_chunk = min (to_do, chunk_size);
3671                 
3672                 if (track.export_stuff (buffers, workbuf, nchans, start, this_chunk)) {
3673                         goto out;
3674                 }
3675
3676                 uint32_t n = 0;
3677                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3678                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3679
3680                         if (afs) {
3681                                 if (afs->write (buffers[n], this_chunk, workbuf) != this_chunk) {
3682                                         goto out;
3683                                 }
3684                         }
3685                 }
3686                 
3687                 start += this_chunk;
3688                 to_do -= this_chunk;
3689                 
3690                 itt.progress = (float) (1.0 - ((double) to_do / len));
3691
3692         }
3693
3694         if (!itt.cancel) {
3695                 
3696                 time_t now;
3697                 struct tm* xnow;
3698                 time (&now);
3699                 xnow = localtime (&now);
3700                 
3701                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3702                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3703                         if (afs) {
3704                                 afs->update_header (position, *xnow, now);
3705                         }
3706                 }
3707                 
3708                 /* build peakfile for new source */
3709                 
3710                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3711                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3712                         if (afs) {
3713                                 afs->build_peaks ();
3714                         }
3715                 }
3716                 
3717                 ret = 0;
3718         }
3719                 
3720   out:
3721         if (ret) {
3722                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3723                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3724                         if (afs) {
3725                                 afs->mark_for_remove ();
3726                         }
3727                         delete *src;
3728                 }
3729         }
3730
3731         for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
3732                 free(*i);
3733         }
3734
3735         if (workbuf) {
3736                 delete [] workbuf;
3737         }
3738         
3739         g_atomic_int_set (&processing_prohibited, 0);
3740
3741         itt.done = true;
3742
3743         return ret;
3744 }
3745
3746 vector<Sample*>&
3747 Session::get_silent_buffers (uint32_t howmany)
3748 {
3749         for (uint32_t i = 0; i < howmany; ++i) {
3750                 memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
3751         }
3752         return _silent_buffers;
3753 }
3754
3755 uint32_t 
3756 Session::ntracks () const
3757 {
3758         uint32_t n = 0;
3759         Glib::RWLock::ReaderLock lm (route_lock);
3760
3761         for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3762                 if (dynamic_cast<AudioTrack*> (*i)) {
3763                         ++n;
3764                 }
3765         }
3766
3767         return n;
3768 }
3769
3770 uint32_t 
3771 Session::nbusses () const
3772 {
3773         uint32_t n = 0;
3774         Glib::RWLock::ReaderLock lm (route_lock);
3775
3776         for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3777                 if (dynamic_cast<AudioTrack*> (*i) == 0) {
3778                         ++n;
3779                 }
3780         }
3781
3782         return n;
3783 }
3784
3785 void
3786 Session::set_layer_model (LayerModel lm)
3787 {
3788         if (lm != layer_model) {
3789                 layer_model = lm;
3790                 set_dirty ();
3791                 ControlChanged (LayeringModel);
3792         }
3793 }
3794
3795 void
3796 Session::set_xfade_model (CrossfadeModel xm)
3797 {
3798         if (xm != xfade_model) {
3799                 xfade_model = xm;
3800                 set_dirty ();
3801                 ControlChanged (CrossfadingModel);
3802         }
3803 }
3804