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