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