r316@gandalf: fugalh | 2006-08-11 17:06:48 -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 << 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 << 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                 save_history("");
1011         }
1012 }       
1013
1014 void
1015 Session::auto_punch_end_changed (Location* location)
1016 {
1017         jack_nframes_t when_to_stop = location->end();
1018         // when_to_stop += _worst_output_latency + _worst_input_latency;
1019         replace_event (Event::PunchOut, when_to_stop);
1020 }       
1021
1022 void
1023 Session::auto_punch_changed (Location* location)
1024 {
1025         jack_nframes_t when_to_stop = location->end();
1026
1027         replace_event (Event::PunchIn, location->start());
1028         //when_to_stop += _worst_output_latency + _worst_input_latency;
1029         replace_event (Event::PunchOut, when_to_stop);
1030 }       
1031
1032 void
1033 Session::auto_loop_changed (Location* location)
1034 {
1035         replace_event (Event::AutoLoop, location->end(), location->start());
1036
1037         if (transport_rolling() && get_auto_loop()) {
1038
1039                 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
1040
1041                 if (_transport_frame > location->end()) {
1042                         // relocate to beginning of loop
1043                         clear_events (Event::LocateRoll);
1044                         
1045                         request_locate (location->start(), true);
1046
1047                 }
1048                 else if (seamless_loop && !loop_changing) {
1049                         
1050                         // schedule a locate-roll to refill the diskstreams at the
1051                         // previous loop end
1052                         loop_changing = true;
1053
1054                         if (location->end() > last_loopend) {
1055                                 clear_events (Event::LocateRoll);
1056                                 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
1057                                 queue_event (ev);
1058                         }
1059
1060                 }
1061         }       
1062
1063         last_loopend = location->end();
1064         
1065 }
1066
1067 void
1068 Session::set_auto_punch_location (Location* location)
1069 {
1070         Location* existing;
1071
1072         if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
1073                 auto_punch_start_changed_connection.disconnect();
1074                 auto_punch_end_changed_connection.disconnect();
1075                 auto_punch_changed_connection.disconnect();
1076                 existing->set_auto_punch (false, this);
1077                 remove_event (existing->start(), Event::PunchIn);
1078                 clear_events (Event::PunchOut);
1079                 auto_punch_location_changed (0);
1080         }
1081
1082         set_dirty();
1083
1084         if (location == 0) {
1085                 return;
1086         }
1087         
1088         if (location->end() <= location->start()) {
1089                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1090                 return;
1091         }
1092
1093         auto_punch_start_changed_connection.disconnect();
1094         auto_punch_end_changed_connection.disconnect();
1095         auto_punch_changed_connection.disconnect();
1096                 
1097         auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1098         auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1099         auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1100
1101         location->set_auto_punch (true, this);
1102         auto_punch_location_changed (location);
1103 }
1104
1105 void
1106 Session::set_punch_in (bool yn)
1107 {
1108         if (punch_in == yn) {
1109                 return;
1110         }
1111
1112         Location* location;
1113
1114         if ((location = _locations.auto_punch_location()) != 0) {
1115                 if ((punch_in = yn) == true) {
1116                         replace_event (Event::PunchIn, location->start());
1117                 } else {
1118                         remove_event (location->start(), Event::PunchIn);
1119                 }
1120         }
1121
1122         set_dirty();
1123         ControlChanged (PunchIn); /* EMIT SIGNAL */
1124 }
1125
1126 void
1127 Session::set_punch_out (bool yn)
1128 {
1129         if (punch_out == yn) {
1130                 return;
1131         }
1132
1133         Location* location;
1134
1135         if ((location = _locations.auto_punch_location()) != 0) {
1136                 if ((punch_out = yn) == true) {
1137                         replace_event (Event::PunchOut, location->end());
1138                 } else {
1139                         clear_events (Event::PunchOut);
1140                 }
1141         }
1142
1143         set_dirty();
1144         ControlChanged (PunchOut); /* EMIT SIGNAL */
1145 }
1146
1147 void
1148 Session::set_auto_loop_location (Location* location)
1149 {
1150         Location* existing;
1151
1152         if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1153                 auto_loop_start_changed_connection.disconnect();
1154                 auto_loop_end_changed_connection.disconnect();
1155                 auto_loop_changed_connection.disconnect();
1156                 existing->set_auto_loop (false, this);
1157                 remove_event (existing->end(), Event::AutoLoop);
1158                 auto_loop_location_changed (0);
1159         }
1160         
1161         set_dirty();
1162
1163         if (location == 0) {
1164                 return;
1165         }
1166
1167         if (location->end() <= location->start()) {
1168                 error << _("Session: you can't use a mark for auto loop") << endmsg;
1169                 return;
1170         }
1171
1172         last_loopend = location->end();
1173         
1174         auto_loop_start_changed_connection.disconnect();
1175         auto_loop_end_changed_connection.disconnect();
1176         auto_loop_changed_connection.disconnect();
1177         
1178         auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1179         auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1180         auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1181
1182         location->set_auto_loop (true, this);
1183         auto_loop_location_changed (location);
1184 }
1185
1186 void
1187 Session::locations_added (Location* ignored)
1188 {
1189         set_dirty ();
1190 }
1191
1192 void
1193 Session::locations_changed ()
1194 {
1195         _locations.apply (*this, &Session::handle_locations_changed);
1196 }
1197
1198 void
1199 Session::handle_locations_changed (Locations::LocationList& locations)
1200 {
1201         Locations::LocationList::iterator i;
1202         Location* location;
1203         bool set_loop = false;
1204         bool set_punch = false;
1205
1206         for (i = locations.begin(); i != locations.end(); ++i) {
1207
1208                 location =* i;
1209
1210                 if (location->is_auto_punch()) {
1211                         set_auto_punch_location (location);
1212                         set_punch = true;
1213                 }
1214                 if (location->is_auto_loop()) {
1215                         set_auto_loop_location (location);
1216                         set_loop = true;
1217                 }
1218                 
1219         }
1220
1221         if (!set_loop) {
1222                 set_auto_loop_location (0);
1223         }
1224         if (!set_punch) {
1225                 set_auto_punch_location (0);
1226         }
1227
1228         set_dirty();
1229 }                                                    
1230
1231 void
1232 Session::enable_record ()
1233 {
1234         /* XXX really atomic compare+swap here */
1235         if (g_atomic_int_get (&_record_status) != Recording) {
1236                 g_atomic_int_set (&_record_status, Recording);
1237                 _last_record_location = _transport_frame;
1238                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
1239
1240                 if (Config->get_use_hardware_monitoring() && auto_input) {
1241                         /* Even though this can be called from RT context we are using
1242                            a non-tentative rwlock here,  because the action must occur.
1243                            The rarity and short potential lock duration makes this "OK"
1244                         */
1245                         Glib::RWLock::ReaderLock dsm (diskstream_lock);
1246                         
1247                         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
1248                                 if ((*i)->record_enabled ()) {
1249                                         (*i)->monitor_input (true);   
1250                                 }
1251                         }
1252                 }
1253
1254                 RecordStateChanged ();
1255         }
1256 }
1257
1258 void
1259 Session::disable_record (bool rt_context, bool force)
1260 {
1261         RecordState rs;
1262
1263         if ((rs = (RecordState) g_atomic_int_get (&_record_status)) != Disabled) {
1264
1265                 if (!Config->get_latched_record_enable () || force) {
1266                         g_atomic_int_set (&_record_status, Disabled);
1267                 } else {
1268                         if (rs == Recording) {
1269                                 g_atomic_int_set (&_record_status, Enabled);
1270                         }
1271                 }
1272
1273                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
1274
1275                 if (Config->get_use_hardware_monitoring() && auto_input) {
1276                         /* Even though this can be called from RT context we are using
1277                            a non-tentative rwlock here,  because the action must occur.
1278                            The rarity and short potential lock duration makes this "OK"
1279                         */
1280                         Glib::RWLock::ReaderLock dsm (diskstream_lock);
1281                         
1282                         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
1283                                 if ((*i)->record_enabled ()) {
1284                                         (*i)->monitor_input (false);   
1285                                 }
1286                         }
1287                 }
1288                 
1289                 RecordStateChanged (); /* emit signal */
1290
1291                 if (!rt_context) {
1292                         remove_pending_capture_state ();
1293                 }
1294         }
1295 }
1296
1297 void
1298 Session::step_back_from_record ()
1299 {
1300         g_atomic_int_set (&_record_status, Enabled);
1301
1302         if (Config->get_use_hardware_monitoring()) {
1303                 /* Even though this can be called from RT context we are using
1304                    a non-tentative rwlock here,  because the action must occur.
1305                    The rarity and short potential lock duration makes this "OK"
1306                 */
1307                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
1308                 
1309                 for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
1310                         if (auto_input && (*i)->record_enabled ()) {
1311                                 //cerr << "switching from input" << __FILE__ << __LINE__ << endl << endl;
1312                                 (*i)->monitor_input (false);   
1313                         }
1314                 }
1315         }
1316 }
1317
1318 void
1319 Session::maybe_enable_record ()
1320 {
1321         g_atomic_int_set (&_record_status, Enabled);
1322
1323         /* XXX this save should really happen in another thread. its needed so that
1324            pending capture state can be recovered if we crash.
1325         */
1326
1327         save_state ("", true);
1328         save_history ("");
1329
1330         if (_transport_speed) {
1331                 if (!punch_in) {
1332                         enable_record ();
1333                 } 
1334         } else {
1335                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
1336                 RecordStateChanged (); /* EMIT SIGNAL */
1337         }
1338
1339         set_dirty();
1340 }
1341
1342 jack_nframes_t
1343 Session::audible_frame () const
1344 {
1345         jack_nframes_t ret;
1346         jack_nframes_t offset;
1347         jack_nframes_t tf;
1348
1349         /* the first of these two possible settings for "offset"
1350            mean that the audible frame is stationary until 
1351            audio emerges from the latency compensation
1352            "pseudo-pipeline".
1353
1354            the second means that the audible frame is stationary
1355            until audio would emerge from a physical port
1356            in the absence of any plugin latency compensation
1357         */
1358
1359         offset = _worst_output_latency;
1360
1361         if (offset > current_block_size) {
1362                 offset -= current_block_size;
1363         } else { 
1364                 /* XXX is this correct? if we have no external
1365                    physical connections and everything is internal
1366                    then surely this is zero? still, how
1367                    likely is that anyway?
1368                 */
1369                 offset = current_block_size;
1370         }
1371
1372         if (synced_to_jack()) {
1373                 tf = _engine.transport_frame();
1374         } else {
1375                 tf = _transport_frame;
1376         }
1377
1378         if (_transport_speed == 0) {
1379                 return tf;
1380         }
1381
1382         if (tf < offset) {
1383                 return 0;
1384         }
1385
1386         ret = tf;
1387
1388         if (!non_realtime_work_pending()) {
1389
1390                 /* MOVING */
1391
1392                 /* take latency into account */
1393                 
1394                 ret -= offset;
1395         }
1396
1397         return ret;
1398 }
1399
1400 void
1401 Session::set_frame_rate (jack_nframes_t frames_per_second)
1402 {
1403         /** \fn void Session::set_frame_size(jack_nframes_t)
1404                 the AudioEngine object that calls this guarantees 
1405                 that it will not be called while we are also in
1406                 ::process(). Its fine to do things that block
1407                 here.
1408         */
1409
1410         _current_frame_rate = frames_per_second;
1411         _frames_per_smpte_frame = (double) _current_frame_rate / (double) smpte_frames_per_second;
1412
1413         Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
1414
1415         // XXX we need some equivalent to this, somehow
1416         // DestructiveFileSource::setup_standard_crossfades (frames_per_second);
1417
1418         set_dirty();
1419
1420         /* XXX need to reset/reinstantiate all LADSPA plugins */
1421 }
1422
1423 void
1424 Session::set_block_size (jack_nframes_t nframes)
1425 {
1426         /* the AudioEngine guarantees 
1427            that it will not be called while we are also in
1428            ::process(). It is therefore fine to do things that block
1429            here.
1430         */
1431
1432         { 
1433                 Glib::RWLock::ReaderLock dsm (diskstream_lock);
1434                 vector<Sample*>::iterator i;
1435                 uint32_t np;
1436                         
1437                 current_block_size = nframes;
1438                 
1439                 for (np = 0, i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i, ++np) {
1440                         free (*i);
1441                 }
1442
1443                 for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
1444                         free (*i);
1445                 }
1446
1447                 _passthru_buffers.clear ();
1448                 _silent_buffers.clear ();
1449
1450                 ensure_passthru_buffers (np);
1451
1452                 for (vector<Sample*>::iterator i = _send_buffers.begin(); i != _send_buffers.end(); ++i) {
1453                         free(*i);
1454
1455                         Sample *buf;
1456 #ifdef NO_POSIX_MEMALIGN
1457                         buf = (Sample *) malloc(current_block_size * sizeof(Sample));
1458 #else
1459                         posix_memalign((void **)&buf,16,current_block_size * 4);
1460 #endif                  
1461                         *i = buf;
1462
1463                         memset (*i, 0, sizeof (Sample) * current_block_size);
1464                 }
1465
1466                 
1467                 if (_gain_automation_buffer) {
1468                         delete [] _gain_automation_buffer;
1469                 }
1470                 _gain_automation_buffer = new gain_t[nframes];
1471
1472                 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1473
1474                 boost::shared_ptr<RouteList> r = routes.reader ();
1475
1476                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1477                         (*i)->set_block_size (nframes);
1478                 }
1479                 
1480                 for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
1481                         (*i)->set_block_size (nframes);
1482                 }
1483
1484                 set_worst_io_latencies ();
1485         }
1486 }
1487
1488 void
1489 Session::set_default_fade (float steepness, float fade_msecs)
1490 {
1491 #if 0
1492         jack_nframes_t fade_frames;
1493         
1494         /* Don't allow fade of less 1 frame */
1495         
1496         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1497
1498                 fade_msecs = 0;
1499                 fade_frames = 0;
1500
1501         } else {
1502                 
1503                 fade_frames = (jack_nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1504                 
1505         }
1506
1507         default_fade_msecs = fade_msecs;
1508         default_fade_steepness = steepness;
1509
1510         {
1511                 // jlc, WTF is this!
1512                 Glib::RWLock::ReaderLock lm (route_lock);
1513                 AudioRegion::set_default_fade (steepness, fade_frames);
1514         }
1515
1516         set_dirty();
1517
1518         /* XXX have to do this at some point */
1519         /* foreach region using default fade, reset, then 
1520            refill_all_diskstream_buffers ();
1521         */
1522 #endif
1523 }
1524
1525 struct RouteSorter {
1526     bool operator() (boost::shared_ptr<Route> r1, boost::shared_ptr<Route> r2) {
1527             if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1528                     return false;
1529             } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1530                     return true;
1531             } else {
1532                     if (r1->fed_by.empty()) {
1533                             if (r2->fed_by.empty()) {
1534                                     /* no ardour-based connections inbound to either route. just use signal order */
1535                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1536                             } else {
1537                                     /* r2 has connections, r1 does not; run r1 early */
1538                                     return true;
1539                             }
1540                     } else {
1541                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1542                     }
1543             }
1544     }
1545 };
1546
1547 static void
1548 trace_terminal (shared_ptr<Route> r1, shared_ptr<Route> rbase)
1549 {
1550         shared_ptr<Route> r2;
1551
1552         if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1553                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1554                 return;
1555         } 
1556
1557         /* make a copy of the existing list of routes that feed r1 */
1558
1559         set<shared_ptr<Route> > existing = r1->fed_by;
1560
1561         /* for each route that feeds r1, recurse, marking it as feeding
1562            rbase as well.
1563         */
1564
1565         for (set<shared_ptr<Route> >::iterator i = existing.begin(); i != existing.end(); ++i) {
1566                 r2 =* i;
1567
1568                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1569                    base as being fed by r2
1570                 */
1571
1572                 rbase->fed_by.insert (r2);
1573
1574                 if (r2 != rbase) {
1575
1576                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1577                            stop here.
1578                          */
1579
1580                         if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1581                                 continue;
1582                         }
1583
1584                         /* now recurse, so that we can mark base as being fed by
1585                            all routes that feed r2
1586                         */
1587
1588                         trace_terminal (r2, rbase);
1589                 }
1590
1591         }
1592 }
1593
1594 void
1595 Session::resort_routes ()
1596 {
1597         /* don't do anything here with signals emitted
1598            by Routes while we are being destroyed.
1599         */
1600
1601         if (_state_of_the_state & Deletion) {
1602                 return;
1603         }
1604
1605
1606         {
1607
1608                 RCUWriter<RouteList> writer (routes);
1609                 shared_ptr<RouteList> r = writer.get_copy ();
1610                 resort_routes_using (r);
1611                 /* writer goes out of scope and forces update */
1612         }
1613
1614 }
1615 void
1616 Session::resort_routes_using (shared_ptr<RouteList> r)
1617 {
1618         RouteList::iterator i, j;
1619         
1620         for (i = r->begin(); i != r->end(); ++i) {
1621                 
1622                 (*i)->fed_by.clear ();
1623                 
1624                 for (j = r->begin(); j != r->end(); ++j) {
1625                         
1626                         /* although routes can feed themselves, it will
1627                            cause an endless recursive descent if we
1628                            detect it. so don't bother checking for
1629                            self-feeding.
1630                         */
1631                         
1632                         if (*j == *i) {
1633                                 continue;
1634                         }
1635                         
1636                         if ((*j)->feeds (*i)) {
1637                                 (*i)->fed_by.insert (*j);
1638                         } 
1639                 }
1640         }
1641         
1642         for (i = r->begin(); i != r->end(); ++i) {
1643                 trace_terminal (*i, *i);
1644         }
1645         
1646         RouteSorter cmp;
1647         r->sort (cmp);
1648         
1649 #if 0
1650         cerr << "finished route resort\n";
1651         
1652         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1653                 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1654         }
1655         cerr << endl;
1656 #endif
1657         
1658 }
1659
1660 shared_ptr<AudioTrack>
1661 Session::new_audio_track (int input_channels, int output_channels, TrackMode mode)
1662 {
1663         char track_name[32];
1664         uint32_t n = 0;
1665         uint32_t channels_used = 0;
1666         string port;
1667         uint32_t nphysical_in;
1668         uint32_t nphysical_out;
1669
1670         /* count existing audio tracks */
1671
1672         {
1673                 shared_ptr<RouteList> r = routes.reader ();
1674
1675                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1676                         if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1677                                 if (!(*i)->hidden()) {
1678                                         n++;
1679                                         channels_used += (*i)->n_inputs();
1680                                 }
1681                         }
1682                 }
1683         }
1684
1685         /* check for duplicate route names, since we might have pre-existing
1686            routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1687            save, close,restart,add new route - first named route is now
1688            Audio2)
1689         */
1690
1691         do {
1692                 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, n+1);
1693                 if (route_by_name (track_name) == 0) {
1694                         break;
1695                 }
1696                 n++;
1697
1698         } while (n < (UINT_MAX-1));
1699
1700         if (input_auto_connect & AutoConnectPhysical) {
1701                 nphysical_in = n_physical_inputs;
1702         } else {
1703                 nphysical_in = 0;
1704         }
1705
1706         if (output_auto_connect & AutoConnectPhysical) {
1707                 nphysical_out = n_physical_outputs;
1708         } else {
1709                 nphysical_out = 0;
1710         }
1711
1712         try {
1713                 shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
1714
1715                 if (track->ensure_io (input_channels, output_channels, false, this)) {
1716                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1717                                           input_channels, output_channels)
1718                               << endmsg;
1719                 }
1720
1721                 if (nphysical_in) {
1722                         for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
1723                                 
1724                                 port = "";
1725                                 
1726                                 if (input_auto_connect & AutoConnectPhysical) {
1727                                         port = _engine.get_nth_physical_input ((channels_used+x)%nphysical_in);
1728                                 } 
1729                                 
1730                                 if (port.length() && track->connect_input (track->input (x), port, this)) {
1731                                         break;
1732                                 }
1733                         }
1734                 }
1735                 
1736                 for (uint32_t x = 0; x < track->n_outputs(); ++x) {
1737                         
1738                         port = "";
1739
1740                         if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
1741                                 port = _engine.get_nth_physical_output ((channels_used+x)%nphysical_out);
1742                         } else if (output_auto_connect & AutoConnectMaster) {
1743                                 if (_master_out) {
1744                                         port = _master_out->input (x%_master_out->n_inputs())->name();
1745                                 }
1746                         }
1747
1748                         if (port.length() && track->connect_output (track->output (x), port, this)) {
1749                                 break;
1750                         }
1751                 }
1752
1753                 if (_control_out) {
1754                         vector<string> cports;
1755                         uint32_t ni = _control_out->n_inputs();
1756
1757                         for (n = 0; n < ni; ++n) {
1758                                 cports.push_back (_control_out->input(n)->name());
1759                         }
1760
1761                         track->set_control_outs (cports);
1762                 }
1763
1764                 track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1765
1766                 add_route (track);
1767
1768                 track->set_remote_control_id (ntracks());
1769                 return track;
1770         }
1771
1772         catch (failed_constructor &err) {
1773                 error << _("Session: could not create new audio track.") << endmsg;
1774                 return shared_ptr<AudioTrack> ((AudioTrack*) 0);
1775         }
1776 }
1777
1778 shared_ptr<Route>
1779 Session::new_audio_route (int input_channels, int output_channels)
1780 {
1781         char bus_name[32];
1782         uint32_t n = 0;
1783         string port;
1784
1785         /* count existing audio busses */
1786
1787         {
1788                 shared_ptr<RouteList> r = routes.reader ();
1789
1790                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1791                         if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1792                                 if (!(*i)->hidden()) {
1793                                         n++;
1794                                 }
1795                         }
1796                 }
1797         }
1798
1799         do {
1800                 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, n+1);
1801                 if (route_by_name (bus_name) == 0) {
1802                         break;
1803                 }
1804                 n++;
1805
1806         } while (n < (UINT_MAX-1));
1807
1808         try {
1809                 shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1810
1811                 if (bus->ensure_io (input_channels, output_channels, false, this)) {
1812                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1813                                           input_channels, output_channels)
1814                               << endmsg;
1815                 }
1816
1817                 for (uint32_t x = 0; x < bus->n_inputs(); ++x) {
1818                         
1819                         port = "";
1820
1821                         if (input_auto_connect & AutoConnectPhysical) {
1822                                 port = _engine.get_nth_physical_input ((n+x)%n_physical_inputs);
1823                         } 
1824                         
1825                         if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1826                                 break;
1827                         }
1828                 }
1829
1830                 for (uint32_t x = 0; x < bus->n_outputs(); ++x) {
1831                         
1832                         port = "";
1833
1834                         if (output_auto_connect & AutoConnectPhysical) {
1835                                 port = _engine.get_nth_physical_input ((n+x)%n_physical_outputs);
1836                         } else if (output_auto_connect & AutoConnectMaster) {
1837                                 if (_master_out) {
1838                                         port = _master_out->input (x%_master_out->n_inputs())->name();
1839                                 }
1840                         }
1841
1842                         if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1843                                 break;
1844                         }
1845                 }
1846
1847                 if (_control_out) {
1848                         vector<string> cports;
1849                         uint32_t ni = _control_out->n_inputs();
1850
1851                         for (uint32_t n = 0; n < ni; ++n) {
1852                                 cports.push_back (_control_out->input(n)->name());
1853                         }
1854                         bus->set_control_outs (cports);
1855                 }
1856                 
1857                 add_route (bus);
1858                 return bus;
1859         }
1860
1861         catch (failed_constructor &err) {
1862                 error << _("Session: could not create new audio route.") << endmsg;
1863                 return shared_ptr<Route> ((Route*) 0);
1864         }
1865 }
1866
1867 void
1868 Session::add_route (shared_ptr<Route> route)
1869 {
1870         { 
1871                 RCUWriter<RouteList> writer (routes);
1872                 shared_ptr<RouteList> r = writer.get_copy ();
1873                 r->push_front (route);
1874                 resort_routes_using (r);
1875         }
1876
1877         route->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), route));
1878         route->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1879         route->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1880         route->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
1881
1882         if (route->master()) {
1883                 _master_out = route;
1884         }
1885
1886         if (route->control()) {
1887                 _control_out = route;
1888         }
1889
1890         set_dirty();
1891         save_state (_current_snapshot_name);
1892         save_history (_current_snapshot_name);
1893
1894         RouteAdded (route); /* EMIT SIGNAL */
1895 }
1896
1897 void
1898 Session::add_diskstream (Diskstream* dstream)
1899 {
1900         /* need to do this in case we're rolling at the time, to prevent false underruns */
1901         dstream->do_refill_with_alloc();
1902         
1903         { 
1904                 Glib::RWLock::WriterLock lm (diskstream_lock);
1905                 diskstreams.push_back (dstream);
1906         }
1907
1908         /* take a reference to the diskstream, preventing it from
1909            ever being deleted until the session itself goes away,
1910            or chooses to remove it for its own purposes.
1911         */
1912
1913         dstream->ref();
1914         dstream->set_block_size (current_block_size);
1915
1916         dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1917         /* this will connect to future changes, and check the current length */
1918         diskstream_playlist_changed (dstream);
1919
1920         dstream->prepare ();
1921
1922         set_dirty();
1923         save_state (_current_snapshot_name);
1924         save_history (_current_snapshot_name);
1925
1926         DiskstreamAdded (dstream); /* EMIT SIGNAL */
1927 }
1928
1929 void
1930 Session::remove_route (shared_ptr<Route> route)
1931 {
1932         {       
1933                 RCUWriter<RouteList> writer (routes);
1934                 shared_ptr<RouteList> rs = writer.get_copy ();
1935                 rs->remove (route);
1936                 
1937                 /* deleting the master out seems like a dumb
1938                    idea, but its more of a UI policy issue
1939                    than our concern.
1940                 */
1941
1942                 if (route == _master_out) {
1943                         _master_out = shared_ptr<Route> ((Route*) 0);
1944                 }
1945
1946                 if (route == _control_out) {
1947                         _control_out = shared_ptr<Route> ((Route*) 0);
1948
1949                         /* cancel control outs for all routes */
1950
1951                         vector<string> empty;
1952
1953                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
1954                                 (*r)->set_control_outs (empty);
1955                         }
1956                 }
1957
1958                 update_route_solo_state ();
1959                 
1960                 /* writer goes out of scope, forces route list update */
1961         }
1962
1963         // FIXME: audio specific
1964         AudioTrack* at;
1965         AudioDiskstream* ds = 0;
1966         
1967         if ((at = dynamic_cast<AudioTrack*>(route.get())) != 0) {
1968                 ds = &at->audio_diskstream();
1969         }
1970         
1971         if (ds) {
1972
1973                 {
1974                         Glib::RWLock::WriterLock lm (diskstream_lock);
1975                         diskstreams.remove (ds);
1976                 }
1977
1978                 ds->unref ();
1979         }
1980
1981         find_current_end ();
1982         
1983         update_latency_compensation (false, false);
1984         set_dirty();
1985         
1986         /* XXX should we disconnect from the Route's signals ? */
1987
1988         save_state (_current_snapshot_name);
1989         save_history (_current_snapshot_name);
1990
1991         /* all shared ptrs to route should go out of scope here */
1992 }       
1993
1994 void
1995 Session::route_mute_changed (void* src)
1996 {
1997         set_dirty ();
1998 }
1999
2000 void
2001 Session::route_solo_changed (void* src, shared_ptr<Route> route)
2002 {      
2003         if (solo_update_disabled) {
2004                 // We know already
2005                 return;
2006         }
2007         
2008         bool is_track;
2009         
2010         is_track = (dynamic_cast<AudioTrack*>(route.get()) != 0);
2011         
2012         shared_ptr<RouteList> r = routes.reader ();
2013
2014         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2015                 
2016                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2017                 
2018                 if (is_track) {
2019                         
2020                         /* don't mess with busses */
2021                         
2022                         if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
2023                                 continue;
2024                         }
2025                         
2026                 } else {
2027                         
2028                         /* don't mess with tracks */
2029                         
2030                         if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
2031                                 continue;
2032                         }
2033                 }
2034                 
2035                 if ((*i) != route &&
2036                     ((*i)->mix_group () == 0 ||
2037                      (*i)->mix_group () != route->mix_group () ||
2038                      !route->mix_group ()->is_active())) {
2039                         
2040                         if ((*i)->soloed()) {
2041                                 
2042                                 /* if its already soloed, and solo latching is enabled,
2043                                    then leave it as it is.
2044                                 */
2045                                 
2046                                 if (_solo_latched) {
2047                                         continue;
2048                                 } 
2049                         }
2050                         
2051                         /* do it */
2052
2053                         solo_update_disabled = true;
2054                         (*i)->set_solo (false, src);
2055                         solo_update_disabled = false;
2056                 }
2057         }
2058         
2059         bool something_soloed = false;
2060         bool same_thing_soloed = false;
2061         bool signal = false;
2062
2063         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2064                 if ((*i)->soloed()) {
2065                         something_soloed = true;
2066                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2067                                 if (is_track) {
2068                                         same_thing_soloed = true;
2069                                         break;
2070                                 }
2071                         } else {
2072                                 if (!is_track) {
2073                                         same_thing_soloed = true;
2074                                         break;
2075                                 }
2076                         }
2077                         break;
2078                 }
2079         }
2080         
2081         if (something_soloed != currently_soloing) {
2082                 signal = true;
2083                 currently_soloing = something_soloed;
2084         }
2085         
2086         modify_solo_mute (is_track, same_thing_soloed);
2087
2088         if (signal) {
2089                 SoloActive (currently_soloing);
2090         }
2091
2092         set_dirty();
2093 }
2094
2095 void
2096 Session::set_solo_latched (bool yn)
2097 {
2098         if (yn != _solo_latched) {
2099                 _solo_latched = yn;
2100                 set_dirty ();
2101                 ControlChanged (SoloLatch);
2102         }
2103 }
2104
2105 void
2106 Session::update_route_solo_state ()
2107 {
2108         bool mute = false;
2109         bool is_track = false;
2110         bool signal = false;
2111
2112         /* caller must hold RouteLock */
2113
2114         /* this is where we actually implement solo by changing
2115            the solo mute setting of each track.
2116         */
2117         
2118         shared_ptr<RouteList> r = routes.reader ();
2119
2120         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2121                 if ((*i)->soloed()) {
2122                         mute = true;
2123                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2124                                 is_track = true;
2125                         }
2126                         break;
2127                 }
2128         }
2129
2130         if (mute != currently_soloing) {
2131                 signal = true;
2132                 currently_soloing = mute;
2133         }
2134
2135         if (!is_track && !mute) {
2136
2137                 /* nothing is soloed */
2138
2139                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2140                         (*i)->set_solo_mute (false);
2141                 }
2142                 
2143                 if (signal) {
2144                         SoloActive (false);
2145                 }
2146
2147                 return;
2148         }
2149
2150         modify_solo_mute (is_track, mute);
2151
2152         if (signal) {
2153                 SoloActive (currently_soloing);
2154         }
2155 }
2156
2157 void
2158 Session::modify_solo_mute (bool is_track, bool mute)
2159 {
2160         shared_ptr<RouteList> r = routes.reader ();
2161
2162         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2163                 
2164                 if (is_track) {
2165                         
2166                         /* only alter track solo mute */
2167                         
2168                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2169                                 if ((*i)->soloed()) {
2170                                         (*i)->set_solo_mute (!mute);
2171                                 } else {
2172                                         (*i)->set_solo_mute (mute);
2173                                 }
2174                         }
2175
2176                 } else {
2177
2178                         /* only alter bus solo mute */
2179
2180                         if (!dynamic_cast<AudioTrack*>((*i).get())) {
2181
2182                                 if ((*i)->soloed()) {
2183
2184                                         (*i)->set_solo_mute (false);
2185
2186                                 } else {
2187
2188                                         /* don't mute master or control outs
2189                                            in response to another bus solo
2190                                         */
2191                                         
2192                                         if ((*i) != _master_out &&
2193                                             (*i) != _control_out) {
2194                                                 (*i)->set_solo_mute (mute);
2195                                         }
2196                                 }
2197                         }
2198
2199                 }
2200         }
2201 }       
2202
2203
2204 void
2205 Session::catch_up_on_solo ()
2206 {
2207         /* this is called after set_state() to catch the full solo
2208            state, which can't be correctly determined on a per-route
2209            basis, but needs the global overview that only the session
2210            has.
2211         */
2212         update_route_solo_state();
2213 }       
2214                 
2215 shared_ptr<Route>
2216 Session::route_by_name (string name)
2217 {
2218         shared_ptr<RouteList> r = routes.reader ();
2219
2220         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2221                 if ((*i)->name() == name) {
2222                         return *i;
2223                 }
2224         }
2225
2226         return shared_ptr<Route> ((Route*) 0);
2227 }
2228
2229 shared_ptr<Route>
2230 Session::route_by_id (PBD::ID id)
2231 {
2232         shared_ptr<RouteList> r = routes.reader ();
2233
2234         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2235                 if ((*i)->id() == id) {
2236                         return *i;
2237                 }
2238         }
2239
2240         return shared_ptr<Route> ((Route*) 0);
2241 }
2242
2243 shared_ptr<Route>
2244 Session::route_by_remote_id (uint32_t id)
2245 {
2246         shared_ptr<RouteList> r = routes.reader ();
2247
2248         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2249                 if ((*i)->remote_control_id() == id) {
2250                         return *i;
2251                 }
2252         }
2253
2254         return shared_ptr<Route> ((Route*) 0);
2255 }
2256
2257 void
2258 Session::find_current_end ()
2259 {
2260         if (_state_of_the_state & Loading) {
2261                 return;
2262         }
2263
2264         jack_nframes_t max = get_maximum_extent ();
2265
2266         if (max > end_location->end()) {
2267                 end_location->set_end (max);
2268                 set_dirty();
2269                 DurationChanged(); /* EMIT SIGNAL */
2270         }
2271 }
2272
2273 jack_nframes_t
2274 Session::get_maximum_extent () const
2275 {
2276         jack_nframes_t max = 0;
2277         jack_nframes_t me; 
2278
2279         /* Don't take the diskstream lock. Caller must have other ways to
2280            ensure atomicity.
2281         */
2282
2283         for (DiskstreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2284                 Playlist* pl = (*i)->playlist();
2285                 if ((me = pl->get_maximum_extent()) > max) {
2286                         max = me;
2287                 }
2288         }
2289
2290         return max;
2291 }
2292
2293 Diskstream *
2294 Session::diskstream_by_name (string name)
2295 {
2296         Glib::RWLock::ReaderLock lm (diskstream_lock);
2297
2298         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2299                 if ((*i)->name() == name) {
2300                         return* i;
2301                 }
2302         }
2303
2304         return 0;
2305 }
2306
2307 Diskstream *
2308 Session::diskstream_by_id (const PBD::ID& id)
2309 {
2310         Glib::RWLock::ReaderLock lm (diskstream_lock);
2311
2312         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2313                 if ((*i)->id() == id) {
2314                         return *i;
2315                 }
2316         }
2317
2318         return 0;
2319 }
2320
2321 /* AudioRegion management */
2322
2323 string
2324 Session::new_region_name (string old)
2325 {
2326         string::size_type last_period;
2327         uint32_t number;
2328         string::size_type len = old.length() + 64;
2329         char buf[len];
2330
2331         if ((last_period = old.find_last_of ('.')) == string::npos) {
2332                 
2333                 /* no period present - add one explicitly */
2334
2335                 old += '.';
2336                 last_period = old.length() - 1;
2337                 number = 0;
2338
2339         } else {
2340
2341                 number = atoi (old.substr (last_period+1).c_str());
2342
2343         }
2344
2345         while (number < (UINT_MAX-1)) {
2346
2347                 AudioRegionList::const_iterator i;
2348                 string sbuf;
2349
2350                 number++;
2351
2352                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2353                 sbuf = buf;
2354
2355                 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2356                         if (i->second->name() == sbuf) {
2357                                 break;
2358                         }
2359                 }
2360                 
2361                 if (i == audio_regions.end()) {
2362                         break;
2363                 }
2364         }
2365
2366         if (number != (UINT_MAX-1)) {
2367                 return buf;
2368         } 
2369
2370         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2371         return old;
2372 }
2373
2374 int
2375 Session::region_name (string& result, string base, bool newlevel) const
2376 {
2377         char buf[16];
2378         string subbase;
2379
2380         if (base == "") {
2381                 
2382                 Glib::Mutex::Lock lm (region_lock);
2383
2384                 snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
2385
2386                 
2387                 result = "region.";
2388                 result += buf;
2389
2390         } else {
2391
2392                 /* XXX this is going to be slow. optimize me later */
2393                 
2394                 if (newlevel) {
2395                         subbase = base;
2396                 } else {
2397                         string::size_type pos;
2398
2399                         pos = base.find_last_of ('.');
2400
2401                         /* pos may be npos, but then we just use entire base */
2402
2403                         subbase = base.substr (0, pos);
2404
2405                 }
2406
2407                 bool name_taken = true;
2408                 
2409                 {
2410                         Glib::Mutex::Lock lm (region_lock);
2411                         
2412                         for (int n = 1; n < 5000; ++n) {
2413                                 
2414                                 result = subbase;
2415                                 snprintf (buf, sizeof (buf), ".%d", n);
2416                                 result += buf;
2417                                 
2418                                 name_taken = false;
2419                                 
2420                                 for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2421                                         if (i->second->name() == result) {
2422                                                 name_taken = true;
2423                                                 break;
2424                                         }
2425                                 }
2426                                 
2427                                 if (!name_taken) {
2428                                         break;
2429                                 }
2430                         }
2431                 }
2432                         
2433                 if (name_taken) {
2434                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2435                         /*NOTREACHED*/
2436                 }
2437         }
2438         return 0;
2439 }       
2440
2441 void
2442 Session::add_region (Region* region)
2443 {
2444         AudioRegion* ar = 0;
2445         AudioRegion* oar = 0;
2446         bool added = false;
2447
2448         { 
2449                 Glib::Mutex::Lock lm (region_lock);
2450
2451                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2452
2453                         AudioRegionList::iterator x;
2454
2455                         for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
2456
2457                                 oar = dynamic_cast<AudioRegion*> (x->second);
2458
2459                                 if (ar->region_list_equivalent (*oar)) {
2460                                         break;
2461                                 }
2462                         }
2463
2464                         if (x == audio_regions.end()) {
2465
2466                                 pair<AudioRegionList::key_type,AudioRegionList::mapped_type> entry;
2467
2468                                 entry.first = region->id();
2469                                 entry.second = ar;
2470
2471                                 pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
2472                                 
2473                                 if (!x.second) {
2474                                         return;
2475                                 }
2476
2477                                 added = true;
2478                         } 
2479
2480                 } else {
2481
2482                         fatal << _("programming error: ")
2483                               << X_("unknown region type passed to Session::add_region()")
2484                               << endmsg;
2485                         /*NOTREACHED*/
2486
2487                 }
2488         }
2489
2490         /* mark dirty because something has changed even if we didn't
2491            add the region to the region list.
2492         */
2493         
2494         set_dirty();
2495         
2496         if (added) {
2497                 region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
2498                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
2499                 AudioRegionAdded (ar); /* EMIT SIGNAL */
2500         }
2501 }
2502
2503 void
2504 Session::region_changed (Change what_changed, Region* region)
2505 {
2506         if (what_changed & Region::HiddenChanged) {
2507                 /* relay hidden changes */
2508                 RegionHiddenChange (region);
2509         }
2510 }
2511
2512 void
2513 Session::region_renamed (Region* region)
2514 {
2515         add_region (region);
2516 }
2517
2518 void
2519 Session::remove_region (Region* region)
2520 {
2521         AudioRegionList::iterator i;
2522         AudioRegion* ar = 0;
2523         bool removed = false;
2524         
2525         { 
2526                 Glib::Mutex::Lock lm (region_lock);
2527
2528                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2529                         if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
2530                                 audio_regions.erase (i);
2531                                 removed = true;
2532                         }
2533
2534                 } else {
2535
2536                         fatal << _("programming error: ") 
2537                               << X_("unknown region type passed to Session::remove_region()")
2538                               << endmsg;
2539                         /*NOTREACHED*/
2540                 }
2541         }
2542
2543         /* mark dirty because something has changed even if we didn't
2544            remove the region from the region list.
2545         */
2546
2547         set_dirty();
2548
2549         if (removed) {
2550                  AudioRegionRemoved(ar); /* EMIT SIGNAL */
2551         }
2552 }
2553
2554 AudioRegion*
2555 Session::find_whole_file_parent (AudioRegion& child)
2556 {
2557         AudioRegionList::iterator i;
2558         AudioRegion* region;
2559         Glib::Mutex::Lock lm (region_lock);
2560
2561         for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2562
2563                 region = i->second;
2564
2565                 if (region->whole_file()) {
2566
2567                         if (child.source_equivalent (*region)) {
2568                                 return region;
2569                         }
2570                 }
2571         } 
2572
2573         return 0;
2574 }       
2575
2576 void
2577 Session::find_equivalent_playlist_regions (Region& region, vector<Region*>& result)
2578 {
2579         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2580                 (*i)->get_region_list_equivalent_regions (region, result);
2581 }
2582
2583 int
2584 Session::destroy_region (Region* region)
2585 {
2586         AudioRegion* aregion;
2587
2588         if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
2589                 return 0;
2590         }
2591
2592         if (aregion->playlist()) {
2593                 aregion->playlist()->destroy_region (region);
2594         }
2595
2596         vector<Source*> srcs;
2597         
2598         for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2599                 srcs.push_back (&aregion->source (n));
2600         }
2601
2602         for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2603                 
2604                 if ((*i)->use_cnt() == 0) {
2605                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*i);
2606                         if (afs) {
2607                                 (afs)->mark_for_remove ();
2608                         }
2609                         delete *i;
2610                 }
2611         }
2612
2613         return 0;
2614 }
2615
2616 int
2617 Session::destroy_regions (list<Region*> regions)
2618 {
2619         for (list<Region*>::iterator i = regions.begin(); i != regions.end(); ++i) {
2620                 destroy_region (*i);
2621         }
2622         return 0;
2623 }
2624
2625 int
2626 Session::remove_last_capture ()
2627 {
2628         list<Region*> r;
2629
2630         Glib::RWLock::ReaderLock lm (diskstream_lock);
2631         
2632         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2633                 list<Region*>& l = (*i)->last_capture_regions();
2634                 
2635                 if (!l.empty()) {
2636                         r.insert (r.end(), l.begin(), l.end());
2637                         l.clear ();
2638                 }
2639         }
2640
2641         destroy_regions (r);
2642         return 0;
2643 }
2644
2645 int
2646 Session::remove_region_from_region_list (Region& r)
2647 {
2648         remove_region (&r);
2649         return 0;
2650 }
2651
2652 /* Source Management */
2653
2654 void
2655 Session::add_audio_source (AudioSource* source)
2656 {
2657         pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
2658
2659         {
2660                 Glib::Mutex::Lock lm (audio_source_lock);
2661                 entry.first = source->id();
2662                 entry.second = source;
2663                 audio_sources.insert (entry);
2664         }
2665         
2666         source->GoingAway.connect (mem_fun (this, &Session::remove_source));
2667         set_dirty();
2668         
2669         SourceAdded (source); /* EMIT SIGNAL */
2670 }
2671
2672 void
2673 Session::remove_source (Source* source)
2674 {
2675         AudioSourceList::iterator i;
2676
2677         { 
2678                 Glib::Mutex::Lock lm (audio_source_lock);
2679
2680                 if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
2681                         audio_sources.erase (i);
2682                 } 
2683         }
2684
2685         if (!_state_of_the_state & InCleanup) {
2686
2687                 /* save state so we don't end up with a session file
2688                    referring to non-existent sources.
2689                 */
2690                 
2691                 save_state (_current_snapshot_name);
2692                 save_history (_current_snapshot_name);
2693         }
2694
2695         SourceRemoved(source); /* EMIT SIGNAL */
2696 }
2697
2698 Source *
2699 Session::source_by_id (const PBD::ID& id)
2700 {
2701         Glib::Mutex::Lock lm (audio_source_lock);
2702         AudioSourceList::iterator i;
2703         Source* source = 0;
2704
2705         if ((i = audio_sources.find (id)) != audio_sources.end()) {
2706                 source = i->second;
2707         }
2708
2709         /* XXX search MIDI or other searches here */
2710         
2711         return source;
2712 }
2713
2714 string
2715 Session::peak_path_from_audio_path (string audio_path)
2716 {
2717         /* XXX hardly bombproof! fix me */
2718
2719         string res;
2720
2721         res = Glib::path_get_dirname (audio_path);
2722         res = Glib::path_get_dirname (res);
2723         res += '/';
2724         res += peak_dir_name;
2725         res += '/';
2726         res += PBD::basename_nosuffix (audio_path);
2727         res += ".peak";
2728
2729         return res;
2730 }
2731
2732 string
2733 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2734 {
2735         string look_for;
2736         string old_basename = PBD::basename_nosuffix (oldname);
2737         string new_legalized = legalize_for_path (newname);
2738
2739         /* note: we know (or assume) the old path is already valid */
2740
2741         if (destructive) {
2742                 
2743                 /* destructive file sources have a name of the form:
2744
2745                     /path/to/Tnnnn-NAME(%[LR])?.wav
2746                   
2747                     the task here is to replace NAME with the new name.
2748                 */
2749                 
2750                 /* find last slash */
2751
2752                 string dir;
2753                 string prefix;
2754                 string::size_type slash;
2755                 string::size_type dash;
2756
2757                 if ((slash = path.find_last_of ('/')) == string::npos) {
2758                         return "";
2759                 }
2760
2761                 dir = path.substr (0, slash+1);
2762
2763                 /* '-' is not a legal character for the NAME part of the path */
2764
2765                 if ((dash = path.find_last_of ('-')) == string::npos) {
2766                         return "";
2767                 }
2768
2769                 prefix = path.substr (slash+1, dash-(slash+1));
2770
2771                 path = dir;
2772                 path += prefix;
2773                 path += '-';
2774                 path += new_legalized;
2775                 path += ".wav";  /* XXX gag me with a spoon */
2776                 
2777         } else {
2778                 
2779                 /* non-destructive file sources have a name of the form:
2780
2781                     /path/to/NAME-nnnnn(%[LR])?.wav
2782                   
2783                     the task here is to replace NAME with the new name.
2784                 */
2785                 
2786                 string dir;
2787                 string suffix;
2788                 string::size_type slash;
2789                 string::size_type dash;
2790                 string::size_type postfix;
2791
2792                 /* find last slash */
2793
2794                 if ((slash = path.find_last_of ('/')) == string::npos) {
2795                         return "";
2796                 }
2797
2798                 dir = path.substr (0, slash+1);
2799
2800                 /* '-' is not a legal character for the NAME part of the path */
2801
2802                 if ((dash = path.find_last_of ('-')) == string::npos) {
2803                         return "";
2804                 }
2805
2806                 suffix = path.substr (dash+1);
2807                 
2808                 // Suffix is now everything after the dash. Now we need to eliminate
2809                 // the nnnnn part, which is done by either finding a '%' or a '.'
2810
2811                 postfix = suffix.find_last_of ("%");
2812                 if (postfix == string::npos) {
2813                         postfix = suffix.find_last_of ('.');
2814                 }
2815
2816                 if (postfix != string::npos) {
2817                         suffix = suffix.substr (postfix);
2818                 } else {
2819                         error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2820                         return "";
2821                 }
2822
2823                 const uint32_t limit = 10000;
2824                 char buf[PATH_MAX+1];
2825
2826                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2827
2828                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2829
2830                         if (access (buf, F_OK) != 0) {
2831                                 path = buf;
2832                                 break;
2833                         }
2834                         path = "";
2835                 }
2836
2837                 if (path == "") {
2838                         error << "FATAL ERROR! Could not find a " << endl;
2839                 }
2840
2841         }
2842
2843         return path;
2844 }
2845
2846 string
2847 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2848 {
2849         string spath;
2850         uint32_t cnt;
2851         char buf[PATH_MAX+1];
2852         const uint32_t limit = 10000;
2853         string legalized;
2854
2855         buf[0] = '\0';
2856         legalized = legalize_for_path (name);
2857
2858         /* find a "version" of the file name that doesn't exist in
2859            any of the possible directories.
2860         */
2861
2862         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2863
2864                 vector<space_and_path>::iterator i;
2865                 uint32_t existing = 0;
2866
2867                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2868
2869                         spath = (*i).path;
2870
2871                         if (destructive) {
2872                                 spath += tape_dir_name;
2873                         } else {
2874                                 spath += sound_dir_name;
2875                         }
2876
2877                         if (destructive) {
2878                                 if (nchan < 2) {
2879                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2880                                 } else if (nchan == 2) {
2881                                         if (chan == 0) {
2882                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
2883                                         } else {
2884                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
2885                                         }
2886                                 } else if (nchan < 26) {
2887                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2888                                 } else {
2889                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2890                                 }
2891                         } else {
2892
2893                                 spath += '/';
2894                                 spath += legalized;
2895
2896                                 if (nchan < 2) {
2897                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2898                                 } else if (nchan == 2) {
2899                                         if (chan == 0) {
2900                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2901                                         } else {
2902                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2903                                         }
2904                                 } else if (nchan < 26) {
2905                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2906                                 } else {
2907                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2908                                 }
2909                         }
2910
2911                         if (access (buf, F_OK) == 0) {
2912                                 existing++;
2913                         }
2914                 }
2915
2916                 if (existing == 0) {
2917                         break;
2918                 }
2919
2920                 if (cnt > limit) {
2921                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
2922                         throw failed_constructor();
2923                 }
2924         }
2925
2926         /* we now have a unique name for the file, but figure out where to
2927            actually put it.
2928         */
2929
2930         string foo = buf;
2931
2932         if (destructive) {
2933                 spath = tape_dir ();
2934         } else {
2935                 spath = discover_best_sound_dir ();
2936         }
2937
2938         string::size_type pos = foo.find_last_of ('/');
2939         
2940         if (pos == string::npos) {
2941                 spath += foo;
2942         } else {
2943                 spath += foo.substr (pos + 1);
2944         }
2945
2946         return spath;
2947 }
2948
2949 AudioFileSource *
2950 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
2951 {
2952         string spath = audio_path_from_name (ds.name(), ds.n_channels(), chan, destructive);
2953
2954         /* this might throw failed_constructor(), which is OK */
2955         
2956         if (destructive) {
2957                 return new DestructiveFileSource (spath,
2958                                                   Config->get_native_file_data_format(),
2959                                                   Config->get_native_file_header_format(),
2960                                                   frame_rate());
2961         } else {
2962                 return new SndFileSource (spath, 
2963                                           Config->get_native_file_data_format(),
2964                                           Config->get_native_file_header_format(),
2965                                           frame_rate());
2966         }
2967 }
2968
2969 /* Playlist management */
2970
2971 Playlist *
2972 Session::playlist_by_name (string name)
2973 {
2974         Glib::Mutex::Lock lm (playlist_lock);
2975         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2976                 if ((*i)->name() == name) {
2977                         return* i;
2978                 }
2979         }
2980         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
2981                 if ((*i)->name() == name) {
2982                         return* i;
2983                 }
2984         }
2985         return 0;
2986 }
2987
2988 void
2989 Session::add_playlist (Playlist* playlist)
2990 {
2991         if (playlist->hidden()) {
2992                 return;
2993         }
2994
2995         { 
2996                 Glib::Mutex::Lock lm (playlist_lock);
2997                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
2998                         playlists.insert (playlists.begin(), playlist);
2999                         // playlist->ref();
3000                         playlist->InUse.connect (mem_fun (*this, &Session::track_playlist));
3001                         playlist->GoingAway.connect (mem_fun (*this, &Session::remove_playlist));
3002                 }
3003         }
3004
3005         set_dirty();
3006
3007         PlaylistAdded (playlist); /* EMIT SIGNAL */
3008 }
3009
3010 void
3011 Session::track_playlist (Playlist* pl, bool inuse)
3012 {
3013         PlaylistList::iterator x;
3014
3015         { 
3016                 Glib::Mutex::Lock lm (playlist_lock);
3017
3018                 if (!inuse) {
3019                         //cerr << "shifting playlist to unused: " << pl->name() << endl;
3020
3021                         unused_playlists.insert (pl);
3022                         
3023                         if ((x = playlists.find (pl)) != playlists.end()) {
3024                                 playlists.erase (x);
3025                         }
3026
3027                         
3028                 } else {
3029                         //cerr << "shifting playlist to used: " << pl->name() << endl;
3030                         
3031                         playlists.insert (pl);
3032                         
3033                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3034                                 unused_playlists.erase (x);
3035                         }
3036                 }
3037         }
3038 }
3039
3040 void
3041 Session::remove_playlist (Playlist* playlist)
3042 {
3043         if (_state_of_the_state & Deletion) {
3044                 return;
3045         }
3046
3047         { 
3048                 Glib::Mutex::Lock lm (playlist_lock);
3049                 // cerr << "removing playlist: " << playlist->name() << endl;
3050
3051                 PlaylistList::iterator i;
3052
3053                 i = find (playlists.begin(), playlists.end(), playlist);
3054
3055                 if (i != playlists.end()) {
3056                         playlists.erase (i);
3057                 }
3058
3059                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3060                 if (i != unused_playlists.end()) {
3061                         unused_playlists.erase (i);
3062                 }
3063                 
3064         }
3065
3066         set_dirty();
3067
3068         PlaylistRemoved (playlist); /* EMIT SIGNAL */
3069 }
3070
3071 void 
3072 Session::set_audition (AudioRegion* r)
3073 {
3074         pending_audition_region = r;
3075         post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3076         schedule_butler_transport_work ();
3077 }
3078
3079 void
3080 Session::non_realtime_set_audition ()
3081 {
3082         if (pending_audition_region == (AudioRegion*) 0xfeedface) {
3083                 auditioner->audition_current_playlist ();
3084         } else if (pending_audition_region) {
3085                 auditioner->audition_region (*pending_audition_region);
3086         }
3087         pending_audition_region = 0;
3088         AuditionActive (true); /* EMIT SIGNAL */
3089 }
3090
3091 void
3092 Session::audition_playlist ()
3093 {
3094         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3095         ev->set_ptr ((void*) 0xfeedface);
3096         queue_event (ev);
3097 }
3098
3099 void
3100 Session::audition_region (Region& r)
3101 {
3102         AudioRegion* ar = dynamic_cast<AudioRegion*>(&r);
3103         if (ar) {
3104                 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3105                 ev->set_ptr (ar);
3106                 queue_event (ev);
3107         }
3108 }
3109
3110 void
3111 Session::cancel_audition ()
3112 {
3113         if (auditioner->active()) {
3114                 auditioner->cancel_audition ();
3115                  AuditionActive (false); /* EMIT SIGNAL */
3116         }
3117 }
3118
3119 bool
3120 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3121 {
3122         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3123 }
3124
3125 void
3126 Session::remove_empty_sounds ()
3127 {
3128
3129         PathScanner scanner;
3130         string dir;
3131
3132         dir = sound_dir ();
3133
3134         vector<string *>* possible_audiofiles = scanner (dir, "\\.wav$", false, true);
3135         
3136         for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
3137
3138                 if (AudioFileSource::is_empty (*(*i))) {
3139
3140                         unlink ((*i)->c_str());
3141                         
3142                         string peak_path = peak_path_from_audio_path (**i);
3143                         unlink (peak_path.c_str());
3144                 }
3145
3146                 delete* i;
3147         }
3148
3149         delete possible_audiofiles;
3150 }
3151
3152 bool
3153 Session::is_auditioning () const
3154 {
3155         /* can be called before we have an auditioner object */
3156         if (auditioner) {
3157                 return auditioner->active();
3158         } else {
3159                 return false;
3160         }
3161 }
3162
3163 void
3164 Session::set_all_solo (bool yn)
3165 {
3166         shared_ptr<RouteList> r = routes.reader ();
3167         
3168         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3169                 if (!(*i)->hidden()) {
3170                         (*i)->set_solo (yn, this);
3171                 }
3172         }
3173
3174         set_dirty();
3175 }
3176                 
3177 void
3178 Session::set_all_mute (bool yn)
3179 {
3180         shared_ptr<RouteList> r = routes.reader ();
3181         
3182         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3183                 if (!(*i)->hidden()) {
3184                         (*i)->set_mute (yn, this);
3185                 }
3186         }
3187
3188         set_dirty();
3189 }
3190                 
3191 uint32_t
3192 Session::n_diskstreams () const
3193 {
3194         Glib::RWLock::ReaderLock lm (diskstream_lock);
3195         uint32_t n = 0;
3196
3197         for (DiskstreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3198                 if (!(*i)->hidden()) {
3199                         n++;
3200                 }
3201         }
3202         return n;
3203 }
3204
3205 void
3206 Session::graph_reordered ()
3207 {
3208         /* don't do this stuff if we are setting up connections
3209            from a set_state() call.
3210         */
3211
3212         if (_state_of_the_state & InitialConnecting) {
3213                 return;
3214         }
3215
3216         Glib::RWLock::ReaderLock lm2 (diskstream_lock);
3217
3218         resort_routes ();
3219
3220         /* force all diskstreams to update their capture offset values to 
3221            reflect any changes in latencies within the graph.
3222         */
3223         
3224         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3225                 (*i)->set_capture_offset ();
3226         }
3227 }
3228
3229 void
3230 Session::record_disenable_all ()
3231 {
3232         record_enable_change_all (false);
3233 }
3234
3235 void
3236 Session::record_enable_all ()
3237 {
3238         record_enable_change_all (true);
3239 }
3240
3241 void
3242 Session::record_enable_change_all (bool yn)
3243 {
3244         shared_ptr<RouteList> r = routes.reader ();
3245         
3246         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3247                 AudioTrack* at;
3248
3249                 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
3250                         at->set_record_enable (yn, this);
3251                 }
3252         }
3253         
3254         /* since we don't keep rec-enable state, don't mark session dirty */
3255 }
3256
3257 void
3258 Session::add_redirect (Redirect* redirect)
3259 {
3260         Send* send;
3261         Insert* insert;
3262         PortInsert* port_insert;
3263         PluginInsert* plugin_insert;
3264
3265         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3266                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3267                         _port_inserts.insert (_port_inserts.begin(), port_insert);
3268                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3269                         _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3270                 } else {
3271                         fatal << _("programming error: unknown type of Insert created!") << endmsg;
3272                         /*NOTREACHED*/
3273                 }
3274         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3275                 _sends.insert (_sends.begin(), send);
3276         } else {
3277                 fatal << _("programming error: unknown type of Redirect created!") << endmsg;
3278                 /*NOTREACHED*/
3279         }
3280
3281         redirect->GoingAway.connect (mem_fun (*this, &Session::remove_redirect));
3282
3283         set_dirty();
3284 }
3285
3286 void
3287 Session::remove_redirect (Redirect* redirect)
3288 {
3289         Send* send;
3290         Insert* insert;
3291         PortInsert* port_insert;
3292         PluginInsert* plugin_insert;
3293
3294         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3295                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3296                         _port_inserts.remove (port_insert);
3297                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3298                         _plugin_inserts.remove (plugin_insert);
3299                 } else {
3300                         fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3301                         /*NOTREACHED*/
3302                 }
3303         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3304                 _sends.remove (send);
3305         } else {
3306                 fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
3307                 /*NOTREACHED*/
3308         }
3309
3310         set_dirty();
3311 }
3312
3313 jack_nframes_t
3314 Session::available_capture_duration ()
3315 {
3316         const double scale = 4096.0 / sizeof (Sample);
3317         
3318         if (_total_free_4k_blocks * scale > (double) max_frames) {
3319                 return max_frames;
3320         }
3321         
3322         return (jack_nframes_t) floor (_total_free_4k_blocks * scale);
3323 }
3324
3325 void
3326 Session::add_connection (ARDOUR::Connection* connection)
3327 {
3328         {
3329                 Glib::Mutex::Lock guard (connection_lock);
3330                 _connections.push_back (connection);
3331         }
3332         
3333         ConnectionAdded (connection); /* EMIT SIGNAL */
3334
3335         set_dirty();
3336 }
3337
3338 void
3339 Session::remove_connection (ARDOUR::Connection* connection)
3340 {
3341         bool removed = false;
3342
3343         {
3344                 Glib::Mutex::Lock guard (connection_lock);
3345                 ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
3346                 
3347                 if (i != _connections.end()) {
3348                         _connections.erase (i);
3349                         removed = true;
3350                 }
3351         }
3352
3353         if (removed) {
3354                  ConnectionRemoved (connection); /* EMIT SIGNAL */
3355         }
3356
3357         set_dirty();
3358 }
3359
3360 ARDOUR::Connection *
3361 Session::connection_by_name (string name) const
3362 {
3363         Glib::Mutex::Lock lm (connection_lock);
3364
3365         for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
3366                 if ((*i)->name() == name) {
3367                         return* i;
3368                 }
3369         }
3370
3371         return 0;
3372 }
3373
3374 void
3375 Session::set_edit_mode (EditMode mode)
3376 {
3377         _edit_mode = mode;
3378         
3379         { 
3380                 Glib::Mutex::Lock lm (playlist_lock);
3381                 
3382                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3383                         (*i)->set_edit_mode (mode);
3384                 }
3385         }
3386
3387         set_dirty ();
3388         ControlChanged (EditingMode); /* EMIT SIGNAL */
3389 }
3390
3391 void
3392 Session::tempo_map_changed (Change ignored)
3393 {
3394         clear_clicks ();
3395         set_dirty ();
3396 }
3397
3398 void
3399 Session::ensure_passthru_buffers (uint32_t howmany)
3400 {
3401         while (howmany > _passthru_buffers.size()) {
3402                 Sample *p;
3403 #ifdef NO_POSIX_MEMALIGN
3404                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3405 #else
3406                 posix_memalign((void **)&p,16,current_block_size * 4);
3407 #endif                  
3408                 _passthru_buffers.push_back (p);
3409
3410                 *p = 0;
3411                 
3412 #ifdef NO_POSIX_MEMALIGN
3413                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3414 #else
3415                 posix_memalign((void **)&p,16,current_block_size * 4);
3416 #endif                  
3417                 memset (p, 0, sizeof (Sample) * current_block_size);
3418                 _silent_buffers.push_back (p);
3419
3420                 *p = 0;
3421                 
3422 #ifdef NO_POSIX_MEMALIGN
3423                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3424 #else
3425                 posix_memalign((void **)&p,16,current_block_size * 4);
3426 #endif                  
3427                 memset (p, 0, sizeof (Sample) * current_block_size);
3428                 _send_buffers.push_back (p);
3429                 
3430         }
3431         allocate_pan_automation_buffers (current_block_size, howmany, false);
3432 }
3433
3434 string
3435 Session::next_send_name ()
3436 {
3437         char buf[32];
3438         snprintf (buf, sizeof (buf), "send %" PRIu32, ++send_cnt);
3439         return buf;
3440 }
3441
3442 string
3443 Session::next_insert_name ()
3444 {
3445         char buf[32];
3446         snprintf (buf, sizeof (buf), "insert %" PRIu32, ++insert_cnt);
3447         return buf;
3448 }
3449
3450 /* Named Selection management */
3451
3452 NamedSelection *
3453 Session::named_selection_by_name (string name)
3454 {
3455         Glib::Mutex::Lock lm (named_selection_lock);
3456         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3457                 if ((*i)->name == name) {
3458                         return* i;
3459                 }
3460         }
3461         return 0;
3462 }
3463
3464 void
3465 Session::add_named_selection (NamedSelection* named_selection)
3466 {
3467         { 
3468                 Glib::Mutex::Lock lm (named_selection_lock);
3469                 named_selections.insert (named_selections.begin(), named_selection);
3470         }
3471
3472         set_dirty();
3473
3474          NamedSelectionAdded (); /* EMIT SIGNAL */
3475 }
3476
3477 void
3478 Session::remove_named_selection (NamedSelection* named_selection)
3479 {
3480         bool removed = false;
3481
3482         { 
3483                 Glib::Mutex::Lock lm (named_selection_lock);
3484
3485                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3486
3487                 if (i != named_selections.end()) {
3488                         delete (*i);
3489                         named_selections.erase (i);
3490                         set_dirty();
3491                         removed = true;
3492                 }
3493         }
3494
3495         if (removed) {
3496                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3497         }
3498 }
3499
3500 void
3501 Session::reset_native_file_format ()
3502 {
3503         // jlc - WHY take routelock?
3504         //RWLockMonitor lm1 (route_lock, true, __LINE__, __FILE__);
3505         Glib::RWLock::ReaderLock lm2 (diskstream_lock);
3506
3507         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3508                 (*i)->reset_write_sources (false);
3509         }
3510 }
3511
3512 bool
3513 Session::route_name_unique (string n) const
3514 {
3515         shared_ptr<RouteList> r = routes.reader ();
3516         
3517         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3518                 if ((*i)->name() == n) {
3519                         return false;
3520                 }
3521         }
3522         
3523         return true;
3524 }
3525
3526 int
3527 Session::cleanup_audio_file_source (AudioFileSource& fs)
3528 {
3529         return fs.move_to_trash (dead_sound_dir_name);
3530 }
3531
3532 uint32_t
3533 Session::n_playlists () const
3534 {
3535         Glib::Mutex::Lock lm (playlist_lock);
3536         return playlists.size();
3537 }
3538
3539 void
3540 Session::set_solo_model (SoloModel sm)
3541 {
3542         if (sm != _solo_model) {
3543                 _solo_model = sm;
3544                 ControlChanged (SoloingModel);
3545                 set_dirty ();
3546         }
3547 }
3548
3549 void
3550 Session::allocate_pan_automation_buffers (jack_nframes_t nframes, uint32_t howmany, bool force)
3551 {
3552         if (!force && howmany <= _npan_buffers) {
3553                 return;
3554         }
3555
3556         if (_pan_automation_buffer) {
3557
3558                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3559                         delete [] _pan_automation_buffer[i];
3560                 }
3561
3562                 delete [] _pan_automation_buffer;
3563         }
3564
3565         _pan_automation_buffer = new pan_t*[howmany];
3566         
3567         for (uint32_t i = 0; i < howmany; ++i) {
3568                 _pan_automation_buffer[i] = new pan_t[nframes];
3569         }
3570
3571         _npan_buffers = howmany;
3572 }
3573
3574 int
3575 Session::freeze (InterThreadInfo& itt)
3576 {
3577         shared_ptr<RouteList> r = routes.reader ();
3578
3579         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3580
3581                 AudioTrack *at;
3582
3583                 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
3584                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3585                            of every track.
3586                         */
3587                         at->freeze (itt);
3588                 }
3589         }
3590
3591         return 0;
3592 }
3593
3594 int
3595 Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,    
3596                                bool overwrite, vector<AudioSource*>& srcs, InterThreadInfo& itt)
3597 {
3598         int ret = -1;
3599         Playlist* playlist;
3600         AudioFileSource* fsource;
3601         uint32_t x;
3602         char buf[PATH_MAX+1];
3603         string dir;
3604         uint32_t nchans;
3605         jack_nframes_t position;
3606         jack_nframes_t this_chunk;
3607         jack_nframes_t to_do;
3608         vector<Sample*> buffers;
3609
3610         // any bigger than this seems to cause stack overflows in called functions
3611         const jack_nframes_t chunk_size = (128 * 1024)/4;
3612
3613         g_atomic_int_set (&processing_prohibited, 1);
3614         
3615         /* call tree *MUST* hold route_lock */
3616         
3617         if ((playlist = track.diskstream().playlist()) == 0) {
3618                 goto out;
3619         }
3620
3621         /* external redirects will be a problem */
3622
3623         if (track.has_external_redirects()) {
3624                 goto out;
3625         }
3626
3627         nchans = track.audio_diskstream().n_channels();
3628         
3629         dir = discover_best_sound_dir ();
3630
3631         for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
3632
3633                 for (x = 0; x < 99999; ++x) {
3634                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3635                         if (access (buf, F_OK) != 0) {
3636                                 break;
3637                         }
3638                 }
3639                 
3640                 if (x == 99999) {
3641                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3642                         goto out;
3643                 }
3644                 
3645                 try {
3646                         fsource =  new SndFileSource (buf, 
3647                                                       Config->get_native_file_data_format(),
3648                                                       Config->get_native_file_header_format(),
3649                                                       frame_rate());
3650                                                             
3651                 }
3652                 
3653                 catch (failed_constructor& err) {
3654                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3655                         goto out;
3656                 }
3657
3658                 srcs.push_back(fsource);
3659         }
3660
3661         /* XXX need to flush all redirects */
3662         
3663         position = start;
3664         to_do = len;
3665
3666         /* create a set of reasonably-sized buffers */
3667
3668         for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
3669                 Sample* b;
3670 #ifdef NO_POSIX_MEMALIGN
3671                 b =  (Sample *) malloc(chunk_size * sizeof(Sample));
3672 #else
3673                 posix_memalign((void **)&b,16,chunk_size * 4);
3674 #endif                  
3675                 buffers.push_back (b);
3676         }
3677
3678         while (to_do && !itt.cancel) {
3679                 
3680                 this_chunk = min (to_do, chunk_size);
3681                 
3682                 if (track.export_stuff (buffers, nchans, start, this_chunk)) {
3683                         goto out;
3684                 }
3685
3686                 uint32_t n = 0;
3687                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3688                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3689
3690                         if (afs) {
3691                                 if (afs->write (buffers[n], this_chunk) != this_chunk) {
3692                                         goto out;
3693                                 }
3694                         }
3695                 }
3696                 
3697                 start += this_chunk;
3698                 to_do -= this_chunk;
3699                 
3700                 itt.progress = (float) (1.0 - ((double) to_do / len));
3701
3702         }
3703
3704         if (!itt.cancel) {
3705                 
3706                 time_t now;
3707                 struct tm* xnow;
3708                 time (&now);
3709                 xnow = localtime (&now);
3710                 
3711                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3712                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3713                         if (afs) {
3714                                 afs->update_header (position, *xnow, now);
3715                         }
3716                 }
3717                 
3718                 /* build peakfile for new source */
3719                 
3720                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3721                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3722                         if (afs) {
3723                                 afs->build_peaks ();
3724                         }
3725                 }
3726                 
3727                 ret = 0;
3728         }
3729                 
3730   out:
3731         if (ret) {
3732                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3733                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3734                         if (afs) {
3735                                 afs->mark_for_remove ();
3736                         }
3737                         delete *src;
3738                 }
3739         }
3740
3741         for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
3742                 free(*i);
3743         }
3744
3745         g_atomic_int_set (&processing_prohibited, 0);
3746
3747         itt.done = true;
3748
3749         return ret;
3750 }
3751
3752 vector<Sample*>&
3753 Session::get_silent_buffers (uint32_t howmany)
3754 {
3755         for (uint32_t i = 0; i < howmany; ++i) {
3756                 memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
3757         }
3758         return _silent_buffers;
3759 }
3760
3761 uint32_t 
3762 Session::ntracks () const
3763 {
3764         uint32_t n = 0;
3765         shared_ptr<RouteList> r = routes.reader ();
3766
3767         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3768                 if (dynamic_cast<AudioTrack*> ((*i).get())) {
3769                         ++n;
3770                 }
3771         }
3772
3773         return n;
3774 }
3775
3776 uint32_t 
3777 Session::nbusses () const
3778 {
3779         uint32_t n = 0;
3780         shared_ptr<RouteList> r = routes.reader ();
3781
3782         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3783                 if (dynamic_cast<AudioTrack*> ((*i).get()) == 0) {
3784                         ++n;
3785                 }
3786         }
3787
3788         return n;
3789 }
3790
3791 void
3792 Session::set_layer_model (LayerModel lm)
3793 {
3794         if (lm != layer_model) {
3795                 layer_model = lm;
3796                 set_dirty ();
3797                 ControlChanged (LayeringModel);
3798         }
3799 }
3800
3801 void
3802 Session::set_xfade_model (CrossfadeModel xm)
3803 {
3804         if (xm != xfade_model) {
3805                 xfade_model = xm;
3806                 set_dirty ();
3807                 ControlChanged (CrossfadingModel);
3808         }
3809 }
3810
3811 void
3812 Session::add_curve(Curve *curve)
3813 {
3814     curves[curve->id()] = curve;
3815 }
3816
3817 void
3818 Session::add_automation_list(AutomationList *al)
3819 {
3820     automation_lists[al->id()] = al;
3821 }