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