- Fixed a buffer size bug when ~/.ardour2 doesn't exist (can't load configuration...
[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
1893         RouteAdded (route); /* EMIT SIGNAL */
1894 }
1895
1896 void
1897 Session::add_diskstream (Diskstream* dstream)
1898 {
1899         /* need to do this in case we're rolling at the time, to prevent false underruns */
1900         dstream->do_refill_with_alloc();
1901         
1902         { 
1903                 Glib::RWLock::WriterLock lm (diskstream_lock);
1904                 diskstreams.push_back (dstream);
1905         }
1906
1907         /* take a reference to the diskstream, preventing it from
1908            ever being deleted until the session itself goes away,
1909            or chooses to remove it for its own purposes.
1910         */
1911
1912         dstream->ref();
1913         dstream->set_block_size (current_block_size);
1914
1915         dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1916         /* this will connect to future changes, and check the current length */
1917         diskstream_playlist_changed (dstream);
1918
1919         dstream->prepare ();
1920
1921         set_dirty();
1922         save_state (_current_snapshot_name);
1923         save_history();
1924
1925         DiskstreamAdded (dstream); /* EMIT SIGNAL */
1926 }
1927
1928 void
1929 Session::remove_route (shared_ptr<Route> route)
1930 {
1931         {       
1932                 RCUWriter<RouteList> writer (routes);
1933                 shared_ptr<RouteList> rs = writer.get_copy ();
1934                 rs->remove (route);
1935                 
1936                 /* deleting the master out seems like a dumb
1937                    idea, but its more of a UI policy issue
1938                    than our concern.
1939                 */
1940
1941                 if (route == _master_out) {
1942                         _master_out = shared_ptr<Route> ((Route*) 0);
1943                 }
1944
1945                 if (route == _control_out) {
1946                         _control_out = shared_ptr<Route> ((Route*) 0);
1947
1948                         /* cancel control outs for all routes */
1949
1950                         vector<string> empty;
1951
1952                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
1953                                 (*r)->set_control_outs (empty);
1954                         }
1955                 }
1956
1957                 update_route_solo_state ();
1958                 
1959                 /* writer goes out of scope, forces route list update */
1960         }
1961
1962         // FIXME: audio specific
1963         AudioTrack* at;
1964         AudioDiskstream* ds = 0;
1965         
1966         if ((at = dynamic_cast<AudioTrack*>(route.get())) != 0) {
1967                 ds = &at->audio_diskstream();
1968         }
1969         
1970         if (ds) {
1971
1972                 {
1973                         Glib::RWLock::WriterLock lm (diskstream_lock);
1974                         diskstreams.remove (ds);
1975                 }
1976
1977                 ds->unref ();
1978         }
1979
1980         find_current_end ();
1981         
1982         update_latency_compensation (false, false);
1983         set_dirty();
1984         
1985         /* XXX should we disconnect from the Route's signals ? */
1986
1987         save_state (_current_snapshot_name);
1988
1989         /* all shared ptrs to route should go out of scope here */
1990 }       
1991
1992 void
1993 Session::route_mute_changed (void* src)
1994 {
1995         set_dirty ();
1996 }
1997
1998 void
1999 Session::route_solo_changed (void* src, shared_ptr<Route> route)
2000 {      
2001         if (solo_update_disabled) {
2002                 // We know already
2003                 return;
2004         }
2005         
2006         bool is_track;
2007         
2008         is_track = (dynamic_cast<AudioTrack*>(route.get()) != 0);
2009         
2010         shared_ptr<RouteList> r = routes.reader ();
2011
2012         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2013                 
2014                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2015                 
2016                 if (is_track) {
2017                         
2018                         /* don't mess with busses */
2019                         
2020                         if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
2021                                 continue;
2022                         }
2023                         
2024                 } else {
2025                         
2026                         /* don't mess with tracks */
2027                         
2028                         if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
2029                                 continue;
2030                         }
2031                 }
2032                 
2033                 if ((*i) != route &&
2034                     ((*i)->mix_group () == 0 ||
2035                      (*i)->mix_group () != route->mix_group () ||
2036                      !route->mix_group ()->is_active())) {
2037                         
2038                         if ((*i)->soloed()) {
2039                                 
2040                                 /* if its already soloed, and solo latching is enabled,
2041                                    then leave it as it is.
2042                                 */
2043                                 
2044                                 if (_solo_latched) {
2045                                         continue;
2046                                 } 
2047                         }
2048                         
2049                         /* do it */
2050
2051                         solo_update_disabled = true;
2052                         (*i)->set_solo (false, src);
2053                         solo_update_disabled = false;
2054                 }
2055         }
2056         
2057         bool something_soloed = false;
2058         bool same_thing_soloed = false;
2059         bool signal = false;
2060
2061         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2062                 if ((*i)->soloed()) {
2063                         something_soloed = true;
2064                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2065                                 if (is_track) {
2066                                         same_thing_soloed = true;
2067                                         break;
2068                                 }
2069                         } else {
2070                                 if (!is_track) {
2071                                         same_thing_soloed = true;
2072                                         break;
2073                                 }
2074                         }
2075                         break;
2076                 }
2077         }
2078         
2079         if (something_soloed != currently_soloing) {
2080                 signal = true;
2081                 currently_soloing = something_soloed;
2082         }
2083         
2084         modify_solo_mute (is_track, same_thing_soloed);
2085
2086         if (signal) {
2087                 SoloActive (currently_soloing);
2088         }
2089
2090         set_dirty();
2091 }
2092
2093 void
2094 Session::set_solo_latched (bool yn)
2095 {
2096         if (yn != _solo_latched) {
2097                 _solo_latched = yn;
2098                 set_dirty ();
2099                 ControlChanged (SoloLatch);
2100         }
2101 }
2102
2103 void
2104 Session::update_route_solo_state ()
2105 {
2106         bool mute = false;
2107         bool is_track = false;
2108         bool signal = false;
2109
2110         /* caller must hold RouteLock */
2111
2112         /* this is where we actually implement solo by changing
2113            the solo mute setting of each track.
2114         */
2115         
2116         shared_ptr<RouteList> r = routes.reader ();
2117
2118         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2119                 if ((*i)->soloed()) {
2120                         mute = true;
2121                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2122                                 is_track = true;
2123                         }
2124                         break;
2125                 }
2126         }
2127
2128         if (mute != currently_soloing) {
2129                 signal = true;
2130                 currently_soloing = mute;
2131         }
2132
2133         if (!is_track && !mute) {
2134
2135                 /* nothing is soloed */
2136
2137                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2138                         (*i)->set_solo_mute (false);
2139                 }
2140                 
2141                 if (signal) {
2142                         SoloActive (false);
2143                 }
2144
2145                 return;
2146         }
2147
2148         modify_solo_mute (is_track, mute);
2149
2150         if (signal) {
2151                 SoloActive (currently_soloing);
2152         }
2153 }
2154
2155 void
2156 Session::modify_solo_mute (bool is_track, bool mute)
2157 {
2158         shared_ptr<RouteList> r = routes.reader ();
2159
2160         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2161                 
2162                 if (is_track) {
2163                         
2164                         /* only alter track solo mute */
2165                         
2166                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2167                                 if ((*i)->soloed()) {
2168                                         (*i)->set_solo_mute (!mute);
2169                                 } else {
2170                                         (*i)->set_solo_mute (mute);
2171                                 }
2172                         }
2173
2174                 } else {
2175
2176                         /* only alter bus solo mute */
2177
2178                         if (!dynamic_cast<AudioTrack*>((*i).get())) {
2179
2180                                 if ((*i)->soloed()) {
2181
2182                                         (*i)->set_solo_mute (false);
2183
2184                                 } else {
2185
2186                                         /* don't mute master or control outs
2187                                            in response to another bus solo
2188                                         */
2189                                         
2190                                         if ((*i) != _master_out &&
2191                                             (*i) != _control_out) {
2192                                                 (*i)->set_solo_mute (mute);
2193                                         }
2194                                 }
2195                         }
2196
2197                 }
2198         }
2199 }       
2200
2201
2202 void
2203 Session::catch_up_on_solo ()
2204 {
2205         /* this is called after set_state() to catch the full solo
2206            state, which can't be correctly determined on a per-route
2207            basis, but needs the global overview that only the session
2208            has.
2209         */
2210         update_route_solo_state();
2211 }       
2212                 
2213 shared_ptr<Route>
2214 Session::route_by_name (string name)
2215 {
2216         shared_ptr<RouteList> r = routes.reader ();
2217
2218         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2219                 if ((*i)->name() == name) {
2220                         return *i;
2221                 }
2222         }
2223
2224         return shared_ptr<Route> ((Route*) 0);
2225 }
2226
2227 shared_ptr<Route>
2228 Session::route_by_remote_id (uint32_t id)
2229 {
2230         shared_ptr<RouteList> r = routes.reader ();
2231
2232         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2233                 if ((*i)->remote_control_id() == id) {
2234                         return *i;
2235                 }
2236         }
2237
2238         return shared_ptr<Route> ((Route*) 0);
2239 }
2240
2241 void
2242 Session::find_current_end ()
2243 {
2244         if (_state_of_the_state & Loading) {
2245                 return;
2246         }
2247
2248         jack_nframes_t max = get_maximum_extent ();
2249
2250         if (max > end_location->end()) {
2251                 end_location->set_end (max);
2252                 set_dirty();
2253                 DurationChanged(); /* EMIT SIGNAL */
2254         }
2255 }
2256
2257 jack_nframes_t
2258 Session::get_maximum_extent () const
2259 {
2260         jack_nframes_t max = 0;
2261         jack_nframes_t me; 
2262
2263         /* Don't take the diskstream lock. Caller must have other ways to
2264            ensure atomicity.
2265         */
2266
2267         for (DiskstreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2268                 Playlist* pl = (*i)->playlist();
2269                 if ((me = pl->get_maximum_extent()) > max) {
2270                         max = me;
2271                 }
2272         }
2273
2274         return max;
2275 }
2276
2277 Diskstream *
2278 Session::diskstream_by_name (string name)
2279 {
2280         Glib::RWLock::ReaderLock lm (diskstream_lock);
2281
2282         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2283                 if ((*i)->name() == name) {
2284                         return* i;
2285                 }
2286         }
2287
2288         return 0;
2289 }
2290
2291 Diskstream *
2292 Session::diskstream_by_id (const PBD::ID& id)
2293 {
2294         Glib::RWLock::ReaderLock lm (diskstream_lock);
2295
2296         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2297                 if ((*i)->id() == id) {
2298                         return *i;
2299                 }
2300         }
2301
2302         return 0;
2303 }
2304
2305 /* AudioRegion management */
2306
2307 string
2308 Session::new_region_name (string old)
2309 {
2310         string::size_type last_period;
2311         uint32_t number;
2312         string::size_type len = old.length() + 64;
2313         char buf[len];
2314
2315         if ((last_period = old.find_last_of ('.')) == string::npos) {
2316                 
2317                 /* no period present - add one explicitly */
2318
2319                 old += '.';
2320                 last_period = old.length() - 1;
2321                 number = 0;
2322
2323         } else {
2324
2325                 number = atoi (old.substr (last_period+1).c_str());
2326
2327         }
2328
2329         while (number < (UINT_MAX-1)) {
2330
2331                 AudioRegionList::const_iterator i;
2332                 string sbuf;
2333
2334                 number++;
2335
2336                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2337                 sbuf = buf;
2338
2339                 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2340                         if (i->second->name() == sbuf) {
2341                                 break;
2342                         }
2343                 }
2344                 
2345                 if (i == audio_regions.end()) {
2346                         break;
2347                 }
2348         }
2349
2350         if (number != (UINT_MAX-1)) {
2351                 return buf;
2352         } 
2353
2354         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2355         return old;
2356 }
2357
2358 int
2359 Session::region_name (string& result, string base, bool newlevel) const
2360 {
2361         char buf[16];
2362         string subbase;
2363
2364         if (base == "") {
2365                 
2366                 Glib::Mutex::Lock lm (region_lock);
2367
2368                 snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
2369
2370                 
2371                 result = "region.";
2372                 result += buf;
2373
2374         } else {
2375
2376                 /* XXX this is going to be slow. optimize me later */
2377                 
2378                 if (newlevel) {
2379                         subbase = base;
2380                 } else {
2381                         string::size_type pos;
2382
2383                         pos = base.find_last_of ('.');
2384
2385                         /* pos may be npos, but then we just use entire base */
2386
2387                         subbase = base.substr (0, pos);
2388
2389                 }
2390
2391                 bool name_taken = true;
2392                 
2393                 {
2394                         Glib::Mutex::Lock lm (region_lock);
2395                         
2396                         for (int n = 1; n < 5000; ++n) {
2397                                 
2398                                 result = subbase;
2399                                 snprintf (buf, sizeof (buf), ".%d", n);
2400                                 result += buf;
2401                                 
2402                                 name_taken = false;
2403                                 
2404                                 for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2405                                         if (i->second->name() == result) {
2406                                                 name_taken = true;
2407                                                 break;
2408                                         }
2409                                 }
2410                                 
2411                                 if (!name_taken) {
2412                                         break;
2413                                 }
2414                         }
2415                 }
2416                         
2417                 if (name_taken) {
2418                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2419                         /*NOTREACHED*/
2420                 }
2421         }
2422         return 0;
2423 }       
2424
2425 void
2426 Session::add_region (Region* region)
2427 {
2428         AudioRegion* ar = 0;
2429         AudioRegion* oar = 0;
2430         bool added = false;
2431
2432         { 
2433                 Glib::Mutex::Lock lm (region_lock);
2434
2435                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2436
2437                         AudioRegionList::iterator x;
2438
2439                         for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
2440
2441                                 oar = dynamic_cast<AudioRegion*> (x->second);
2442
2443                                 if (ar->region_list_equivalent (*oar)) {
2444                                         break;
2445                                 }
2446                         }
2447
2448                         if (x == audio_regions.end()) {
2449
2450                                 pair<AudioRegionList::key_type,AudioRegionList::mapped_type> entry;
2451
2452                                 entry.first = region->id();
2453                                 entry.second = ar;
2454
2455                                 pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
2456                                 
2457                                 if (!x.second) {
2458                                         return;
2459                                 }
2460
2461                                 added = true;
2462                         } 
2463
2464                 } else {
2465
2466                         fatal << _("programming error: ")
2467                               << X_("unknown region type passed to Session::add_region()")
2468                               << endmsg;
2469                         /*NOTREACHED*/
2470
2471                 }
2472         }
2473
2474         /* mark dirty because something has changed even if we didn't
2475            add the region to the region list.
2476         */
2477         
2478         set_dirty();
2479         
2480         if (added) {
2481                 region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
2482                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
2483                 AudioRegionAdded (ar); /* EMIT SIGNAL */
2484         }
2485 }
2486
2487 void
2488 Session::region_changed (Change what_changed, Region* region)
2489 {
2490         if (what_changed & Region::HiddenChanged) {
2491                 /* relay hidden changes */
2492                 RegionHiddenChange (region);
2493         }
2494 }
2495
2496 void
2497 Session::region_renamed (Region* region)
2498 {
2499         add_region (region);
2500 }
2501
2502 void
2503 Session::remove_region (Region* region)
2504 {
2505         AudioRegionList::iterator i;
2506         AudioRegion* ar = 0;
2507         bool removed = false;
2508         
2509         { 
2510                 Glib::Mutex::Lock lm (region_lock);
2511
2512                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2513                         if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
2514                                 audio_regions.erase (i);
2515                                 removed = true;
2516                         }
2517
2518                 } else {
2519
2520                         fatal << _("programming error: ") 
2521                               << X_("unknown region type passed to Session::remove_region()")
2522                               << endmsg;
2523                         /*NOTREACHED*/
2524                 }
2525         }
2526
2527         /* mark dirty because something has changed even if we didn't
2528            remove the region from the region list.
2529         */
2530
2531         set_dirty();
2532
2533         if (removed) {
2534                  AudioRegionRemoved(ar); /* EMIT SIGNAL */
2535         }
2536 }
2537
2538 AudioRegion*
2539 Session::find_whole_file_parent (AudioRegion& child)
2540 {
2541         AudioRegionList::iterator i;
2542         AudioRegion* region;
2543         Glib::Mutex::Lock lm (region_lock);
2544
2545         for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2546
2547                 region = i->second;
2548
2549                 if (region->whole_file()) {
2550
2551                         if (child.source_equivalent (*region)) {
2552                                 return region;
2553                         }
2554                 }
2555         } 
2556
2557         return 0;
2558 }       
2559
2560 void
2561 Session::find_equivalent_playlist_regions (Region& region, vector<Region*>& result)
2562 {
2563         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2564                 (*i)->get_region_list_equivalent_regions (region, result);
2565 }
2566
2567 int
2568 Session::destroy_region (Region* region)
2569 {
2570         AudioRegion* aregion;
2571
2572         if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
2573                 return 0;
2574         }
2575
2576         if (aregion->playlist()) {
2577                 aregion->playlist()->destroy_region (region);
2578         }
2579
2580         vector<Source*> srcs;
2581         
2582         for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2583                 srcs.push_back (&aregion->source (n));
2584         }
2585
2586         for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2587                 
2588                 if ((*i)->use_cnt() == 0) {
2589                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*i);
2590                         if (afs) {
2591                                 (afs)->mark_for_remove ();
2592                         }
2593                         delete *i;
2594                 }
2595         }
2596
2597         return 0;
2598 }
2599
2600 int
2601 Session::destroy_regions (list<Region*> regions)
2602 {
2603         for (list<Region*>::iterator i = regions.begin(); i != regions.end(); ++i) {
2604                 destroy_region (*i);
2605         }
2606         return 0;
2607 }
2608
2609 int
2610 Session::remove_last_capture ()
2611 {
2612         list<Region*> r;
2613
2614         Glib::RWLock::ReaderLock lm (diskstream_lock);
2615         
2616         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2617                 list<Region*>& l = (*i)->last_capture_regions();
2618                 
2619                 if (!l.empty()) {
2620                         r.insert (r.end(), l.begin(), l.end());
2621                         l.clear ();
2622                 }
2623         }
2624
2625         destroy_regions (r);
2626         return 0;
2627 }
2628
2629 int
2630 Session::remove_region_from_region_list (Region& r)
2631 {
2632         remove_region (&r);
2633         return 0;
2634 }
2635
2636 /* Source Management */
2637
2638 void
2639 Session::add_audio_source (AudioSource* source)
2640 {
2641         pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
2642
2643         {
2644                 Glib::Mutex::Lock lm (audio_source_lock);
2645                 entry.first = source->id();
2646                 entry.second = source;
2647                 audio_sources.insert (entry);
2648         }
2649         
2650         source->GoingAway.connect (mem_fun (this, &Session::remove_source));
2651         set_dirty();
2652         
2653         SourceAdded (source); /* EMIT SIGNAL */
2654 }
2655
2656 void
2657 Session::remove_source (Source* source)
2658 {
2659         AudioSourceList::iterator i;
2660
2661         { 
2662                 Glib::Mutex::Lock lm (audio_source_lock);
2663
2664                 if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
2665                         audio_sources.erase (i);
2666                 } 
2667         }
2668
2669         if (!_state_of_the_state & InCleanup) {
2670
2671                 /* save state so we don't end up with a session file
2672                    referring to non-existent sources.
2673                 */
2674                 
2675                 save_state (_current_snapshot_name);
2676                 save_history();
2677         }
2678
2679         SourceRemoved(source); /* EMIT SIGNAL */
2680 }
2681
2682 Source *
2683 Session::source_by_id (const PBD::ID& id)
2684 {
2685         Glib::Mutex::Lock lm (audio_source_lock);
2686         AudioSourceList::iterator i;
2687         Source* source = 0;
2688
2689         if ((i = audio_sources.find (id)) != audio_sources.end()) {
2690                 source = i->second;
2691         }
2692
2693         /* XXX search MIDI or other searches here */
2694         
2695         return source;
2696 }
2697
2698 string
2699 Session::peak_path_from_audio_path (string audio_path)
2700 {
2701         /* XXX hardly bombproof! fix me */
2702
2703         string res;
2704
2705         res = Glib::path_get_dirname (audio_path);
2706         res = Glib::path_get_dirname (res);
2707         res += '/';
2708         res += peak_dir_name;
2709         res += '/';
2710         res += PBD::basename_nosuffix (audio_path);
2711         res += ".peak";
2712
2713         return res;
2714 }
2715
2716 string
2717 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2718 {
2719         string look_for;
2720         string old_basename = PBD::basename_nosuffix (oldname);
2721         string new_legalized = legalize_for_path (newname);
2722
2723         /* note: we know (or assume) the old path is already valid */
2724
2725         if (destructive) {
2726                 
2727                 /* destructive file sources have a name of the form:
2728
2729                     /path/to/Tnnnn-NAME(%[LR])?.wav
2730                   
2731                     the task here is to replace NAME with the new name.
2732                 */
2733                 
2734                 /* find last slash */
2735
2736                 string dir;
2737                 string prefix;
2738                 string::size_type slash;
2739                 string::size_type dash;
2740
2741                 if ((slash = path.find_last_of ('/')) == string::npos) {
2742                         return "";
2743                 }
2744
2745                 dir = path.substr (0, slash+1);
2746
2747                 /* '-' is not a legal character for the NAME part of the path */
2748
2749                 if ((dash = path.find_last_of ('-')) == string::npos) {
2750                         return "";
2751                 }
2752
2753                 prefix = path.substr (slash+1, dash-(slash+1));
2754
2755                 path = dir;
2756                 path += prefix;
2757                 path += '-';
2758                 path += new_legalized;
2759                 path += ".wav";  /* XXX gag me with a spoon */
2760                 
2761         } else {
2762                 
2763                 /* non-destructive file sources have a name of the form:
2764
2765                     /path/to/NAME-nnnnn(%[LR])?.wav
2766                   
2767                     the task here is to replace NAME with the new name.
2768                 */
2769                 
2770                 string dir;
2771                 string suffix;
2772                 string::size_type slash;
2773                 string::size_type dash;
2774                 string::size_type postfix;
2775
2776                 /* find last slash */
2777
2778                 if ((slash = path.find_last_of ('/')) == string::npos) {
2779                         return "";
2780                 }
2781
2782                 dir = path.substr (0, slash+1);
2783
2784                 /* '-' is not a legal character for the NAME part of the path */
2785
2786                 if ((dash = path.find_last_of ('-')) == string::npos) {
2787                         return "";
2788                 }
2789
2790                 suffix = path.substr (dash+1);
2791                 
2792                 // Suffix is now everything after the dash. Now we need to eliminate
2793                 // the nnnnn part, which is done by either finding a '%' or a '.'
2794
2795                 postfix = suffix.find_last_of ("%");
2796                 if (postfix == string::npos) {
2797                         postfix = suffix.find_last_of ('.');
2798                 }
2799
2800                 if (postfix != string::npos) {
2801                         suffix = suffix.substr (postfix);
2802                 } else {
2803                         error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2804                         return "";
2805                 }
2806
2807                 const uint32_t limit = 10000;
2808                 char buf[PATH_MAX+1];
2809
2810                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2811
2812                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2813
2814                         if (access (buf, F_OK) != 0) {
2815                                 path = buf;
2816                                 break;
2817                         }
2818                         path = "";
2819                 }
2820
2821                 if (path == "") {
2822                         error << "FATAL ERROR! Could not find a " << endl;
2823                 }
2824
2825         }
2826
2827         return path;
2828 }
2829
2830 string
2831 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2832 {
2833         string spath;
2834         uint32_t cnt;
2835         char buf[PATH_MAX+1];
2836         const uint32_t limit = 10000;
2837         string legalized;
2838
2839         buf[0] = '\0';
2840         legalized = legalize_for_path (name);
2841
2842         /* find a "version" of the file name that doesn't exist in
2843            any of the possible directories.
2844         */
2845
2846         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2847
2848                 vector<space_and_path>::iterator i;
2849                 uint32_t existing = 0;
2850
2851                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2852
2853                         spath = (*i).path;
2854
2855                         if (destructive) {
2856                                 spath += tape_dir_name;
2857                         } else {
2858                                 spath += sound_dir_name;
2859                         }
2860
2861                         if (destructive) {
2862                                 if (nchan < 2) {
2863                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2864                                 } else if (nchan == 2) {
2865                                         if (chan == 0) {
2866                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
2867                                         } else {
2868                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
2869                                         }
2870                                 } else if (nchan < 26) {
2871                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2872                                 } else {
2873                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2874                                 }
2875                         } else {
2876
2877                                 spath += '/';
2878                                 spath += legalized;
2879
2880                                 if (nchan < 2) {
2881                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2882                                 } else if (nchan == 2) {
2883                                         if (chan == 0) {
2884                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2885                                         } else {
2886                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2887                                         }
2888                                 } else if (nchan < 26) {
2889                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2890                                 } else {
2891                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2892                                 }
2893                         }
2894
2895                         if (access (buf, F_OK) == 0) {
2896                                 existing++;
2897                         }
2898                 }
2899
2900                 if (existing == 0) {
2901                         break;
2902                 }
2903
2904                 if (cnt > limit) {
2905                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
2906                         throw failed_constructor();
2907                 }
2908         }
2909
2910         /* we now have a unique name for the file, but figure out where to
2911            actually put it.
2912         */
2913
2914         string foo = buf;
2915
2916         if (destructive) {
2917                 spath = tape_dir ();
2918         } else {
2919                 spath = discover_best_sound_dir ();
2920         }
2921
2922         string::size_type pos = foo.find_last_of ('/');
2923         
2924         if (pos == string::npos) {
2925                 spath += foo;
2926         } else {
2927                 spath += foo.substr (pos + 1);
2928         }
2929
2930         return spath;
2931 }
2932
2933 AudioFileSource *
2934 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
2935 {
2936         string spath = audio_path_from_name (ds.name(), ds.n_channels(), chan, destructive);
2937
2938         /* this might throw failed_constructor(), which is OK */
2939         
2940         if (destructive) {
2941                 return new DestructiveFileSource (spath,
2942                                                   Config->get_native_file_data_format(),
2943                                                   Config->get_native_file_header_format(),
2944                                                   frame_rate());
2945         } else {
2946                 return new SndFileSource (spath, 
2947                                           Config->get_native_file_data_format(),
2948                                           Config->get_native_file_header_format(),
2949                                           frame_rate());
2950         }
2951 }
2952
2953 /* Playlist management */
2954
2955 Playlist *
2956 Session::playlist_by_name (string name)
2957 {
2958         Glib::Mutex::Lock lm (playlist_lock);
2959         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2960                 if ((*i)->name() == name) {
2961                         return* i;
2962                 }
2963         }
2964         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
2965                 if ((*i)->name() == name) {
2966                         return* i;
2967                 }
2968         }
2969         return 0;
2970 }
2971
2972 void
2973 Session::add_playlist (Playlist* playlist)
2974 {
2975         if (playlist->hidden()) {
2976                 return;
2977         }
2978
2979         { 
2980                 Glib::Mutex::Lock lm (playlist_lock);
2981                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
2982                         playlists.insert (playlists.begin(), playlist);
2983                         // playlist->ref();
2984                         playlist->InUse.connect (mem_fun (*this, &Session::track_playlist));
2985                         playlist->GoingAway.connect (mem_fun (*this, &Session::remove_playlist));
2986                 }
2987         }
2988
2989         set_dirty();
2990
2991         PlaylistAdded (playlist); /* EMIT SIGNAL */
2992 }
2993
2994 void
2995 Session::track_playlist (Playlist* pl, bool inuse)
2996 {
2997         PlaylistList::iterator x;
2998
2999         { 
3000                 Glib::Mutex::Lock lm (playlist_lock);
3001
3002                 if (!inuse) {
3003                         //cerr << "shifting playlist to unused: " << pl->name() << endl;
3004
3005                         unused_playlists.insert (pl);
3006                         
3007                         if ((x = playlists.find (pl)) != playlists.end()) {
3008                                 playlists.erase (x);
3009                         }
3010
3011                         
3012                 } else {
3013                         //cerr << "shifting playlist to used: " << pl->name() << endl;
3014                         
3015                         playlists.insert (pl);
3016                         
3017                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3018                                 unused_playlists.erase (x);
3019                         }
3020                 }
3021         }
3022 }
3023
3024 void
3025 Session::remove_playlist (Playlist* playlist)
3026 {
3027         if (_state_of_the_state & Deletion) {
3028                 return;
3029         }
3030
3031         { 
3032                 Glib::Mutex::Lock lm (playlist_lock);
3033                 // cerr << "removing playlist: " << playlist->name() << endl;
3034
3035                 PlaylistList::iterator i;
3036
3037                 i = find (playlists.begin(), playlists.end(), playlist);
3038
3039                 if (i != playlists.end()) {
3040                         playlists.erase (i);
3041                 }
3042
3043                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3044                 if (i != unused_playlists.end()) {
3045                         unused_playlists.erase (i);
3046                 }
3047                 
3048         }
3049
3050         set_dirty();
3051
3052         PlaylistRemoved (playlist); /* EMIT SIGNAL */
3053 }
3054
3055 void 
3056 Session::set_audition (AudioRegion* r)
3057 {
3058         pending_audition_region = r;
3059         post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3060         schedule_butler_transport_work ();
3061 }
3062
3063 void
3064 Session::non_realtime_set_audition ()
3065 {
3066         if (pending_audition_region == (AudioRegion*) 0xfeedface) {
3067                 auditioner->audition_current_playlist ();
3068         } else if (pending_audition_region) {
3069                 auditioner->audition_region (*pending_audition_region);
3070         }
3071         pending_audition_region = 0;
3072         AuditionActive (true); /* EMIT SIGNAL */
3073 }
3074
3075 void
3076 Session::audition_playlist ()
3077 {
3078         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3079         ev->set_ptr ((void*) 0xfeedface);
3080         queue_event (ev);
3081 }
3082
3083 void
3084 Session::audition_region (Region& r)
3085 {
3086         AudioRegion* ar = dynamic_cast<AudioRegion*>(&r);
3087         if (ar) {
3088                 Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3089                 ev->set_ptr (ar);
3090                 queue_event (ev);
3091         }
3092 }
3093
3094 void
3095 Session::cancel_audition ()
3096 {
3097         if (auditioner->active()) {
3098                 auditioner->cancel_audition ();
3099                  AuditionActive (false); /* EMIT SIGNAL */
3100         }
3101 }
3102
3103 bool
3104 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3105 {
3106         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3107 }
3108
3109 void
3110 Session::remove_empty_sounds ()
3111 {
3112
3113         PathScanner scanner;
3114         string dir;
3115
3116         dir = sound_dir ();
3117
3118         vector<string *>* possible_audiofiles = scanner (dir, "\\.wav$", false, true);
3119         
3120         for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
3121
3122                 if (AudioFileSource::is_empty (*(*i))) {
3123
3124                         unlink ((*i)->c_str());
3125                         
3126                         string peak_path = peak_path_from_audio_path (**i);
3127                         unlink (peak_path.c_str());
3128                 }
3129
3130                 delete* i;
3131         }
3132
3133         delete possible_audiofiles;
3134 }
3135
3136 bool
3137 Session::is_auditioning () const
3138 {
3139         /* can be called before we have an auditioner object */
3140         if (auditioner) {
3141                 return auditioner->active();
3142         } else {
3143                 return false;
3144         }
3145 }
3146
3147 void
3148 Session::set_all_solo (bool yn)
3149 {
3150         shared_ptr<RouteList> r = routes.reader ();
3151         
3152         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3153                 if (!(*i)->hidden()) {
3154                         (*i)->set_solo (yn, this);
3155                 }
3156         }
3157
3158         set_dirty();
3159 }
3160                 
3161 void
3162 Session::set_all_mute (bool yn)
3163 {
3164         shared_ptr<RouteList> r = routes.reader ();
3165         
3166         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3167                 if (!(*i)->hidden()) {
3168                         (*i)->set_mute (yn, this);
3169                 }
3170         }
3171
3172         set_dirty();
3173 }
3174                 
3175 uint32_t
3176 Session::n_diskstreams () const
3177 {
3178         Glib::RWLock::ReaderLock lm (diskstream_lock);
3179         uint32_t n = 0;
3180
3181         for (DiskstreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3182                 if (!(*i)->hidden()) {
3183                         n++;
3184                 }
3185         }
3186         return n;
3187 }
3188
3189 void
3190 Session::graph_reordered ()
3191 {
3192         /* don't do this stuff if we are setting up connections
3193            from a set_state() call.
3194         */
3195
3196         if (_state_of_the_state & InitialConnecting) {
3197                 return;
3198         }
3199
3200         Glib::RWLock::ReaderLock lm2 (diskstream_lock);
3201
3202         resort_routes ();
3203
3204         /* force all diskstreams to update their capture offset values to 
3205            reflect any changes in latencies within the graph.
3206         */
3207         
3208         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3209                 (*i)->set_capture_offset ();
3210         }
3211 }
3212
3213 void
3214 Session::record_disenable_all ()
3215 {
3216         record_enable_change_all (false);
3217 }
3218
3219 void
3220 Session::record_enable_all ()
3221 {
3222         record_enable_change_all (true);
3223 }
3224
3225 void
3226 Session::record_enable_change_all (bool yn)
3227 {
3228         shared_ptr<RouteList> r = routes.reader ();
3229         
3230         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3231                 AudioTrack* at;
3232
3233                 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
3234                         at->set_record_enable (yn, this);
3235                 }
3236         }
3237         
3238         /* since we don't keep rec-enable state, don't mark session dirty */
3239 }
3240
3241 void
3242 Session::add_redirect (Redirect* redirect)
3243 {
3244         Send* send;
3245         Insert* insert;
3246         PortInsert* port_insert;
3247         PluginInsert* plugin_insert;
3248
3249         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3250                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3251                         _port_inserts.insert (_port_inserts.begin(), port_insert);
3252                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3253                         _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3254                 } else {
3255                         fatal << _("programming error: unknown type of Insert created!") << endmsg;
3256                         /*NOTREACHED*/
3257                 }
3258         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3259                 _sends.insert (_sends.begin(), send);
3260         } else {
3261                 fatal << _("programming error: unknown type of Redirect created!") << endmsg;
3262                 /*NOTREACHED*/
3263         }
3264
3265         redirect->GoingAway.connect (mem_fun (*this, &Session::remove_redirect));
3266
3267         set_dirty();
3268 }
3269
3270 void
3271 Session::remove_redirect (Redirect* redirect)
3272 {
3273         Send* send;
3274         Insert* insert;
3275         PortInsert* port_insert;
3276         PluginInsert* plugin_insert;
3277
3278         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
3279                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
3280                         _port_inserts.remove (port_insert);
3281                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
3282                         _plugin_inserts.remove (plugin_insert);
3283                 } else {
3284                         fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3285                         /*NOTREACHED*/
3286                 }
3287         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
3288                 _sends.remove (send);
3289         } else {
3290                 fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
3291                 /*NOTREACHED*/
3292         }
3293
3294         set_dirty();
3295 }
3296
3297 jack_nframes_t
3298 Session::available_capture_duration ()
3299 {
3300         const double scale = 4096.0 / sizeof (Sample);
3301         
3302         if (_total_free_4k_blocks * scale > (double) max_frames) {
3303                 return max_frames;
3304         }
3305         
3306         return (jack_nframes_t) floor (_total_free_4k_blocks * scale);
3307 }
3308
3309 void
3310 Session::add_connection (ARDOUR::Connection* connection)
3311 {
3312         {
3313                 Glib::Mutex::Lock guard (connection_lock);
3314                 _connections.push_back (connection);
3315         }
3316         
3317         ConnectionAdded (connection); /* EMIT SIGNAL */
3318
3319         set_dirty();
3320 }
3321
3322 void
3323 Session::remove_connection (ARDOUR::Connection* connection)
3324 {
3325         bool removed = false;
3326
3327         {
3328                 Glib::Mutex::Lock guard (connection_lock);
3329                 ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
3330                 
3331                 if (i != _connections.end()) {
3332                         _connections.erase (i);
3333                         removed = true;
3334                 }
3335         }
3336
3337         if (removed) {
3338                  ConnectionRemoved (connection); /* EMIT SIGNAL */
3339         }
3340
3341         set_dirty();
3342 }
3343
3344 ARDOUR::Connection *
3345 Session::connection_by_name (string name) const
3346 {
3347         Glib::Mutex::Lock lm (connection_lock);
3348
3349         for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
3350                 if ((*i)->name() == name) {
3351                         return* i;
3352                 }
3353         }
3354
3355         return 0;
3356 }
3357
3358 void
3359 Session::set_edit_mode (EditMode mode)
3360 {
3361         _edit_mode = mode;
3362         
3363         { 
3364                 Glib::Mutex::Lock lm (playlist_lock);
3365                 
3366                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3367                         (*i)->set_edit_mode (mode);
3368                 }
3369         }
3370
3371         set_dirty ();
3372         ControlChanged (EditingMode); /* EMIT SIGNAL */
3373 }
3374
3375 void
3376 Session::tempo_map_changed (Change ignored)
3377 {
3378         clear_clicks ();
3379         set_dirty ();
3380 }
3381
3382 void
3383 Session::ensure_passthru_buffers (uint32_t howmany)
3384 {
3385         while (howmany > _passthru_buffers.size()) {
3386                 Sample *p;
3387 #ifdef NO_POSIX_MEMALIGN
3388                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3389 #else
3390                 posix_memalign((void **)&p,16,current_block_size * 4);
3391 #endif                  
3392                 _passthru_buffers.push_back (p);
3393
3394                 *p = 0;
3395                 
3396 #ifdef NO_POSIX_MEMALIGN
3397                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3398 #else
3399                 posix_memalign((void **)&p,16,current_block_size * 4);
3400 #endif                  
3401                 memset (p, 0, sizeof (Sample) * current_block_size);
3402                 _silent_buffers.push_back (p);
3403
3404                 *p = 0;
3405                 
3406 #ifdef NO_POSIX_MEMALIGN
3407                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3408 #else
3409                 posix_memalign((void **)&p,16,current_block_size * 4);
3410 #endif                  
3411                 memset (p, 0, sizeof (Sample) * current_block_size);
3412                 _send_buffers.push_back (p);
3413                 
3414         }
3415         allocate_pan_automation_buffers (current_block_size, howmany, false);
3416 }
3417
3418 string
3419 Session::next_send_name ()
3420 {
3421         char buf[32];
3422         snprintf (buf, sizeof (buf), "send %" PRIu32, ++send_cnt);
3423         return buf;
3424 }
3425
3426 string
3427 Session::next_insert_name ()
3428 {
3429         char buf[32];
3430         snprintf (buf, sizeof (buf), "insert %" PRIu32, ++insert_cnt);
3431         return buf;
3432 }
3433
3434 /* Named Selection management */
3435
3436 NamedSelection *
3437 Session::named_selection_by_name (string name)
3438 {
3439         Glib::Mutex::Lock lm (named_selection_lock);
3440         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3441                 if ((*i)->name == name) {
3442                         return* i;
3443                 }
3444         }
3445         return 0;
3446 }
3447
3448 void
3449 Session::add_named_selection (NamedSelection* named_selection)
3450 {
3451         { 
3452                 Glib::Mutex::Lock lm (named_selection_lock);
3453                 named_selections.insert (named_selections.begin(), named_selection);
3454         }
3455
3456         set_dirty();
3457
3458          NamedSelectionAdded (); /* EMIT SIGNAL */
3459 }
3460
3461 void
3462 Session::remove_named_selection (NamedSelection* named_selection)
3463 {
3464         bool removed = false;
3465
3466         { 
3467                 Glib::Mutex::Lock lm (named_selection_lock);
3468
3469                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3470
3471                 if (i != named_selections.end()) {
3472                         delete (*i);
3473                         named_selections.erase (i);
3474                         set_dirty();
3475                         removed = true;
3476                 }
3477         }
3478
3479         if (removed) {
3480                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3481         }
3482 }
3483
3484 void
3485 Session::reset_native_file_format ()
3486 {
3487         // jlc - WHY take routelock?
3488         //RWLockMonitor lm1 (route_lock, true, __LINE__, __FILE__);
3489         Glib::RWLock::ReaderLock lm2 (diskstream_lock);
3490
3491         for (DiskstreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3492                 (*i)->reset_write_sources (false);
3493         }
3494 }
3495
3496 bool
3497 Session::route_name_unique (string n) const
3498 {
3499         shared_ptr<RouteList> r = routes.reader ();
3500         
3501         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3502                 if ((*i)->name() == n) {
3503                         return false;
3504                 }
3505         }
3506         
3507         return true;
3508 }
3509
3510 int
3511 Session::cleanup_audio_file_source (AudioFileSource& fs)
3512 {
3513         return fs.move_to_trash (dead_sound_dir_name);
3514 }
3515
3516 uint32_t
3517 Session::n_playlists () const
3518 {
3519         Glib::Mutex::Lock lm (playlist_lock);
3520         return playlists.size();
3521 }
3522
3523 void
3524 Session::set_solo_model (SoloModel sm)
3525 {
3526         if (sm != _solo_model) {
3527                 _solo_model = sm;
3528                 ControlChanged (SoloingModel);
3529                 set_dirty ();
3530         }
3531 }
3532
3533 void
3534 Session::allocate_pan_automation_buffers (jack_nframes_t nframes, uint32_t howmany, bool force)
3535 {
3536         if (!force && howmany <= _npan_buffers) {
3537                 return;
3538         }
3539
3540         if (_pan_automation_buffer) {
3541
3542                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3543                         delete [] _pan_automation_buffer[i];
3544                 }
3545
3546                 delete [] _pan_automation_buffer;
3547         }
3548
3549         _pan_automation_buffer = new pan_t*[howmany];
3550         
3551         for (uint32_t i = 0; i < howmany; ++i) {
3552                 _pan_automation_buffer[i] = new pan_t[nframes];
3553         }
3554
3555         _npan_buffers = howmany;
3556 }
3557
3558 int
3559 Session::freeze (InterThreadInfo& itt)
3560 {
3561         shared_ptr<RouteList> r = routes.reader ();
3562
3563         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3564
3565                 AudioTrack *at;
3566
3567                 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
3568                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3569                            of every track.
3570                         */
3571                         at->freeze (itt);
3572                 }
3573         }
3574
3575         return 0;
3576 }
3577
3578 int
3579 Session::write_one_audio_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,    
3580                                bool overwrite, vector<AudioSource*>& srcs, InterThreadInfo& itt)
3581 {
3582         int ret = -1;
3583         Playlist* playlist;
3584         AudioFileSource* fsource;
3585         uint32_t x;
3586         char buf[PATH_MAX+1];
3587         string dir;
3588         uint32_t nchans;
3589         jack_nframes_t position;
3590         jack_nframes_t this_chunk;
3591         jack_nframes_t to_do;
3592         vector<Sample*> buffers;
3593
3594         // any bigger than this seems to cause stack overflows in called functions
3595         const jack_nframes_t chunk_size = (128 * 1024)/4;
3596
3597         g_atomic_int_set (&processing_prohibited, 1);
3598         
3599         /* call tree *MUST* hold route_lock */
3600         
3601         if ((playlist = track.diskstream().playlist()) == 0) {
3602                 goto out;
3603         }
3604
3605         /* external redirects will be a problem */
3606
3607         if (track.has_external_redirects()) {
3608                 goto out;
3609         }
3610
3611         nchans = track.audio_diskstream().n_channels();
3612         
3613         dir = discover_best_sound_dir ();
3614
3615         for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
3616
3617                 for (x = 0; x < 99999; ++x) {
3618                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3619                         if (access (buf, F_OK) != 0) {
3620                                 break;
3621                         }
3622                 }
3623                 
3624                 if (x == 99999) {
3625                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3626                         goto out;
3627                 }
3628                 
3629                 try {
3630                         fsource =  new SndFileSource (buf, 
3631                                                       Config->get_native_file_data_format(),
3632                                                       Config->get_native_file_header_format(),
3633                                                       frame_rate());
3634                                                             
3635                 }
3636                 
3637                 catch (failed_constructor& err) {
3638                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3639                         goto out;
3640                 }
3641
3642                 srcs.push_back(fsource);
3643         }
3644
3645         /* XXX need to flush all redirects */
3646         
3647         position = start;
3648         to_do = len;
3649
3650         /* create a set of reasonably-sized buffers */
3651
3652         for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
3653                 Sample* b;
3654 #ifdef NO_POSIX_MEMALIGN
3655                 b =  (Sample *) malloc(chunk_size * sizeof(Sample));
3656 #else
3657                 posix_memalign((void **)&b,16,chunk_size * 4);
3658 #endif                  
3659                 buffers.push_back (b);
3660         }
3661
3662         while (to_do && !itt.cancel) {
3663                 
3664                 this_chunk = min (to_do, chunk_size);
3665                 
3666                 if (track.export_stuff (buffers, nchans, start, this_chunk)) {
3667                         goto out;
3668                 }
3669
3670                 uint32_t n = 0;
3671                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3672                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3673
3674                         if (afs) {
3675                                 if (afs->write (buffers[n], this_chunk) != this_chunk) {
3676                                         goto out;
3677                                 }
3678                         }
3679                 }
3680                 
3681                 start += this_chunk;
3682                 to_do -= this_chunk;
3683                 
3684                 itt.progress = (float) (1.0 - ((double) to_do / len));
3685
3686         }
3687
3688         if (!itt.cancel) {
3689                 
3690                 time_t now;
3691                 struct tm* xnow;
3692                 time (&now);
3693                 xnow = localtime (&now);
3694                 
3695                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3696                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3697                         if (afs) {
3698                                 afs->update_header (position, *xnow, now);
3699                         }
3700                 }
3701                 
3702                 /* build peakfile for new source */
3703                 
3704                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3705                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3706                         if (afs) {
3707                                 afs->build_peaks ();
3708                         }
3709                 }
3710                 
3711                 ret = 0;
3712         }
3713                 
3714   out:
3715         if (ret) {
3716                 for (vector<AudioSource*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3717                         AudioFileSource* afs = dynamic_cast<AudioFileSource*>(*src);
3718                         if (afs) {
3719                                 afs->mark_for_remove ();
3720                         }
3721                         delete *src;
3722                 }
3723         }
3724
3725         for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
3726                 free(*i);
3727         }
3728
3729         g_atomic_int_set (&processing_prohibited, 0);
3730
3731         itt.done = true;
3732
3733         return ret;
3734 }
3735
3736 vector<Sample*>&
3737 Session::get_silent_buffers (uint32_t howmany)
3738 {
3739         for (uint32_t i = 0; i < howmany; ++i) {
3740                 memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
3741         }
3742         return _silent_buffers;
3743 }
3744
3745 uint32_t 
3746 Session::ntracks () const
3747 {
3748         uint32_t n = 0;
3749         shared_ptr<RouteList> r = routes.reader ();
3750
3751         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3752                 if (dynamic_cast<AudioTrack*> ((*i).get())) {
3753                         ++n;
3754                 }
3755         }
3756
3757         return n;
3758 }
3759
3760 uint32_t 
3761 Session::nbusses () const
3762 {
3763         uint32_t n = 0;
3764         shared_ptr<RouteList> r = routes.reader ();
3765
3766         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3767                 if (dynamic_cast<AudioTrack*> ((*i).get()) == 0) {
3768                         ++n;
3769                 }
3770         }
3771
3772         return n;
3773 }
3774
3775 void
3776 Session::set_layer_model (LayerModel lm)
3777 {
3778         if (lm != layer_model) {
3779                 layer_model = lm;
3780                 set_dirty ();
3781                 ControlChanged (LayeringModel);
3782         }
3783 }
3784
3785 void
3786 Session::set_xfade_model (CrossfadeModel xm)
3787 {
3788         if (xm != xfade_model) {
3789                 xfade_model = xm;
3790                 set_dirty ();
3791                 ControlChanged (CrossfadingModel);
3792         }
3793 }
3794