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