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