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