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