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