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