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