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