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