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