ab218e48044fc2a9ac86cc29d46cdcfc964a0128
[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.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                 set_dirty();
937                 ControlChanged (AutoInput);
938         }
939 }
940
941 void
942 Session::set_input_auto_connect (bool yn)
943 {
944         if (yn) {
945                 input_auto_connect = AutoConnectOption (input_auto_connect|AutoConnectPhysical);
946         } else {
947                 input_auto_connect = AutoConnectOption (input_auto_connect|~AutoConnectPhysical);
948         }
949         set_dirty ();
950 }
951
952 void
953 Session::set_output_auto_connect (AutoConnectOption aco)
954 {
955         output_auto_connect = aco;
956         set_dirty ();
957 }
958
959 void
960 Session::auto_punch_start_changed (Location* location)
961 {
962         replace_event (Event::PunchIn, location->start());
963
964         if (get_record_enabled() && get_punch_in()) {
965                 /* capture start has been changed, so save new pending state */
966                 save_state ("", true);
967         }
968 }       
969
970 void
971 Session::auto_punch_end_changed (Location* location)
972 {
973         jack_nframes_t when_to_stop = location->end();
974         // when_to_stop += _worst_output_latency + _worst_input_latency;
975         replace_event (Event::PunchOut, when_to_stop);
976 }       
977
978 void
979 Session::auto_punch_changed (Location* location)
980 {
981         jack_nframes_t when_to_stop = location->end();
982
983         replace_event (Event::PunchIn, location->start());
984         //when_to_stop += _worst_output_latency + _worst_input_latency;
985         replace_event (Event::PunchOut, when_to_stop);
986 }       
987
988 void
989 Session::auto_loop_changed (Location* location)
990 {
991         replace_event (Event::AutoLoop, location->end(), location->start());
992
993         if (transport_rolling() && get_auto_loop()) {
994
995                 //if (_transport_frame < location->start() || _transport_frame > location->end()) {
996
997                 if (_transport_frame > location->end()) {
998                         // relocate to beginning of loop
999                         clear_events (Event::LocateRoll);
1000                         
1001                         request_locate (location->start(), true);
1002
1003                 }
1004                 else if (seamless_loop && !loop_changing) {
1005                         
1006                         // schedule a locate-roll to refill the diskstreams at the
1007                         // previous loop end
1008                         loop_changing = true;
1009
1010                         if (location->end() > last_loopend) {
1011                                 clear_events (Event::LocateRoll);
1012                                 Event *ev = new Event (Event::LocateRoll, Event::Add, last_loopend, last_loopend, 0, true);
1013                                 queue_event (ev);
1014                         }
1015
1016                 }
1017         }       
1018
1019         last_loopend = location->end();
1020         
1021 }
1022
1023 void
1024 Session::set_auto_punch_location (Location* location)
1025 {
1026         Location* existing;
1027
1028         if ((existing = _locations.auto_punch_location()) != 0 && existing != location) {
1029                 auto_punch_start_changed_connection.disconnect();
1030                 auto_punch_end_changed_connection.disconnect();
1031                 auto_punch_changed_connection.disconnect();
1032                 existing->set_auto_punch (false, this);
1033                 remove_event (existing->start(), Event::PunchIn);
1034                 clear_events (Event::PunchOut);
1035                 auto_punch_location_changed (0);
1036         }
1037
1038         set_dirty();
1039
1040         if (location == 0) {
1041                 return;
1042         }
1043         
1044         if (location->end() <= location->start()) {
1045                 error << _("Session: you can't use that location for auto punch (start <= end)") << endmsg;
1046                 return;
1047         }
1048
1049         auto_punch_start_changed_connection.disconnect();
1050         auto_punch_end_changed_connection.disconnect();
1051         auto_punch_changed_connection.disconnect();
1052                 
1053         auto_punch_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_punch_start_changed));
1054         auto_punch_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_punch_end_changed));
1055         auto_punch_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_punch_changed));
1056
1057         location->set_auto_punch (true, this);
1058         auto_punch_location_changed (location);
1059 }
1060
1061 void
1062 Session::set_punch_in (bool yn)
1063 {
1064         if (punch_in == yn) {
1065                 return;
1066         }
1067
1068         Location* location;
1069
1070         if ((location = _locations.auto_punch_location()) != 0) {
1071                 if ((punch_in = yn) == true) {
1072                         replace_event (Event::PunchIn, location->start());
1073                 } else {
1074                         remove_event (location->start(), Event::PunchIn);
1075                 }
1076         }
1077
1078         set_dirty();
1079         ControlChanged (PunchIn); /* EMIT SIGNAL */
1080 }
1081
1082 void
1083 Session::set_punch_out (bool yn)
1084 {
1085         if (punch_out == yn) {
1086                 return;
1087         }
1088
1089         Location* location;
1090
1091         if ((location = _locations.auto_punch_location()) != 0) {
1092                 if ((punch_out = yn) == true) {
1093                         replace_event (Event::PunchOut, location->end());
1094                 } else {
1095                         clear_events (Event::PunchOut);
1096                 }
1097         }
1098
1099         set_dirty();
1100         ControlChanged (PunchOut); /* EMIT SIGNAL */
1101 }
1102
1103 void
1104 Session::set_auto_loop_location (Location* location)
1105 {
1106         Location* existing;
1107
1108         if ((existing = _locations.auto_loop_location()) != 0 && existing != location) {
1109                 auto_loop_start_changed_connection.disconnect();
1110                 auto_loop_end_changed_connection.disconnect();
1111                 auto_loop_changed_connection.disconnect();
1112                 existing->set_auto_loop (false, this);
1113                 remove_event (existing->end(), Event::AutoLoop);
1114                 auto_loop_location_changed (0);
1115         }
1116         
1117         set_dirty();
1118
1119         if (location == 0) {
1120                 return;
1121         }
1122
1123         if (location->end() <= location->start()) {
1124                 error << _("Session: you can't use a mark for auto loop") << endmsg;
1125                 return;
1126         }
1127
1128         last_loopend = location->end();
1129         
1130         auto_loop_start_changed_connection.disconnect();
1131         auto_loop_end_changed_connection.disconnect();
1132         auto_loop_changed_connection.disconnect();
1133         
1134         auto_loop_start_changed_connection = location->start_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1135         auto_loop_end_changed_connection = location->end_changed.connect (mem_fun (this, &Session::auto_loop_changed));
1136         auto_loop_changed_connection = location->changed.connect (mem_fun (this, &Session::auto_loop_changed));
1137
1138         location->set_auto_loop (true, this);
1139         auto_loop_location_changed (location);
1140 }
1141
1142 void
1143 Session::locations_added (Location* ignored)
1144 {
1145         set_dirty ();
1146 }
1147
1148 void
1149 Session::locations_changed ()
1150 {
1151         _locations.apply (*this, &Session::handle_locations_changed);
1152 }
1153
1154 void
1155 Session::handle_locations_changed (Locations::LocationList& locations)
1156 {
1157         Locations::LocationList::iterator i;
1158         Location* location;
1159         bool set_loop = false;
1160         bool set_punch = false;
1161
1162         for (i = locations.begin(); i != locations.end(); ++i) {
1163
1164                 location =* i;
1165
1166                 if (location->is_auto_punch()) {
1167                         set_auto_punch_location (location);
1168                         set_punch = true;
1169                 }
1170                 if (location->is_auto_loop()) {
1171                         set_auto_loop_location (location);
1172                         set_loop = true;
1173                 }
1174                 
1175         }
1176
1177         if (!set_loop) {
1178                 set_auto_loop_location (0);
1179         }
1180         if (!set_punch) {
1181                 set_auto_punch_location (0);
1182         }
1183
1184         set_dirty();
1185 }                                                    
1186
1187 void
1188 Session::enable_record ()
1189 {
1190         /* XXX really atomic compare+swap here */
1191         if (atomic_read (&_record_status) != Recording) {
1192                 atomic_set (&_record_status, Recording);
1193                 _last_record_location = _transport_frame;
1194                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordStrobe);
1195                 RecordEnabled ();
1196         }
1197 }
1198
1199 void
1200 Session::disable_record ()
1201 {
1202         if (atomic_read (&_record_status) != Disabled) {
1203                 atomic_set (&_record_status, Disabled);
1204                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordExit);
1205                 RecordDisabled ();
1206                 remove_pending_capture_state ();
1207         }
1208 }
1209
1210 void
1211 Session::step_back_from_record ()
1212 {
1213         atomic_set (&_record_status, Enabled);
1214 }
1215
1216 void
1217 Session::maybe_enable_record ()
1218 {
1219         atomic_set (&_record_status, Enabled);
1220
1221         save_state ("", true);
1222
1223         if (_transport_speed) {
1224                 if (!punch_in) {
1225                         enable_record ();
1226                 } 
1227         } else {
1228                 send_mmc_in_another_thread (MIDI::MachineControl::cmdRecordPause);
1229                 RecordEnabled (); /* EMIT SIGNAL */
1230         }
1231
1232         set_dirty();
1233 }
1234
1235 jack_nframes_t
1236 Session::audible_frame () const
1237 {
1238         jack_nframes_t ret;
1239         jack_nframes_t offset;
1240         jack_nframes_t tf;
1241
1242         /* the first of these two possible settings for "offset"
1243            mean that the audible frame is stationary until 
1244            audio emerges from the latency compensation
1245            "pseudo-pipeline".
1246
1247            the second means that the audible frame is stationary
1248            until audio would emerge from a physical port
1249            in the absence of any plugin latency compensation
1250         */
1251
1252         offset = _worst_output_latency;
1253
1254         if (offset > current_block_size) {
1255                 offset -= current_block_size;
1256         } else { 
1257                 /* XXX is this correct? if we have no external
1258                    physical connections and everything is internal
1259                    then surely this is zero? still, how
1260                    likely is that anyway?
1261                 */
1262                 offset = current_block_size;
1263         }
1264
1265         if (synced_to_jack()) {
1266                 tf = _engine.transport_frame();
1267         } else {
1268                 tf = _transport_frame;
1269         }
1270
1271         if (_transport_speed == 0) {
1272                 return tf;
1273         }
1274
1275         if (tf < offset) {
1276                 return 0;
1277         }
1278
1279         ret = tf;
1280
1281         if (!non_realtime_work_pending()) {
1282
1283                 /* MOVING */
1284
1285                 /* take latency into account */
1286                 
1287                 ret -= offset;
1288         }
1289
1290         return ret;
1291 }
1292
1293 void
1294 Session::set_frame_rate (jack_nframes_t frames_per_second)
1295 {
1296         /** \fn void Session::set_frame_size(jack_nframes_t)
1297                 the AudioEngine object that calls this guarantees 
1298                 that it will not be called while we are also in
1299                 ::process(). Its fine to do things that block
1300                 here.
1301         */
1302
1303         _current_frame_rate = frames_per_second;
1304         _frames_per_smpte_frame = (double) _current_frame_rate / (double) smpte_frames_per_second;
1305
1306         Route::set_automation_interval ((jack_nframes_t) ceil ((double) frames_per_second * 0.25));
1307
1308         set_dirty();
1309
1310         /* XXX need to reset/reinstantiate all LADSPA plugins */
1311 }
1312
1313 void
1314 Session::set_block_size (jack_nframes_t nframes)
1315 {
1316         /* the AudioEngine guarantees 
1317            that it will not be called while we are also in
1318            ::process(). It is therefore fine to do things that block
1319            here.
1320         */
1321
1322         { 
1323                 LockMonitor lm (route_lock, __LINE__, __FILE__);
1324                 vector<Sample*>::iterator i;
1325                 uint32_t np;
1326                         
1327                 current_block_size = nframes;
1328                 
1329                 for (np = 0, i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i, ++np) {
1330                         free (*i);
1331                 }
1332
1333                 for (vector<Sample*>::iterator i = _silent_buffers.begin(); i != _silent_buffers.end(); ++i) {
1334                         free (*i);
1335                 }
1336
1337                 _passthru_buffers.clear ();
1338                 _silent_buffers.clear ();
1339
1340                 ensure_passthru_buffers (np);
1341
1342                 if (_gain_automation_buffer) {
1343                         delete [] _gain_automation_buffer;
1344                 }
1345                 _gain_automation_buffer = new gain_t[nframes];
1346
1347                 allocate_pan_automation_buffers (nframes, _npan_buffers, true);
1348
1349                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1350                         (*i)->set_block_size (nframes);
1351                 }
1352                 
1353                 for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
1354                         (*i)->set_block_size (nframes);
1355                 }
1356
1357                 set_worst_io_latencies (false);
1358         }
1359 }
1360
1361 void
1362 Session::set_default_fade (float steepness, float fade_msecs)
1363 {
1364 #if 0
1365         jack_nframes_t fade_frames;
1366         
1367         /* Don't allow fade of less 1 frame */
1368         
1369         if (fade_msecs < (1000.0 * (1.0/_current_frame_rate))) {
1370
1371                 fade_msecs = 0;
1372                 fade_frames = 0;
1373
1374         } else {
1375                 
1376                 fade_frames = (jack_nframes_t) floor (fade_msecs * _current_frame_rate * 0.001);
1377                 
1378         }
1379
1380         default_fade_msecs = fade_msecs;
1381         default_fade_steepness = steepness;
1382
1383         {
1384                 LockMonitor lm (route_lock, __LINE__, __FILE__);
1385                 AudioRegion::set_default_fade (steepness, fade_frames);
1386         }
1387
1388         set_dirty();
1389
1390         /* XXX have to do this at some point */
1391         /* foreach region using default fade, reset, then 
1392            refill_all_diskstream_buffers ();
1393         */
1394 #endif
1395 }
1396
1397 struct RouteSorter {
1398     bool operator() (Route* r1, Route* r2) {
1399             if (r1->fed_by.find (r2) != r1->fed_by.end()) {
1400                     return false;
1401             } else if (r2->fed_by.find (r1) != r2->fed_by.end()) {
1402                     return true;
1403             } else {
1404                     if (r1->fed_by.empty()) {
1405                             if (r2->fed_by.empty()) {
1406                                     /* no ardour-based connections inbound to either route. just use signal order */
1407                                     return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1408                             } else {
1409                                     /* r2 has connections, r1 does not; run r1 early */
1410                                     return true;
1411                             }
1412                     } else {
1413                             return r1->order_key(N_("signal")) < r2->order_key(N_("signal"));
1414                     }
1415             }
1416     }
1417 };
1418
1419 static void
1420 trace_terminal (Route* r1, Route* rbase)
1421 {
1422         Route* r2;
1423
1424         if ((r1->fed_by.find (rbase) != r1->fed_by.end()) && (rbase->fed_by.find (r1) != rbase->fed_by.end())) {
1425                 info << string_compose(_("feedback loop setup between %1 and %2"), r1->name(), rbase->name()) << endmsg;
1426                 return;
1427         } 
1428
1429         /* make a copy of the existing list of routes that feed r1 */
1430
1431         set<Route *> existing = r1->fed_by;
1432
1433         /* for each route that feeds r1, recurse, marking it as feeding
1434            rbase as well.
1435         */
1436
1437         for (set<Route *>::iterator i = existing.begin(); i != existing.end(); ++i) {
1438                 r2 =* i;
1439
1440                 /* r2 is a route that feeds r1 which somehow feeds base. mark
1441                    base as being fed by r2
1442                 */
1443
1444                 rbase->fed_by.insert (r2);
1445
1446                 if (r2 != rbase) {
1447
1448                         /* 2nd level feedback loop detection. if r1 feeds or is fed by r2,
1449                            stop here.
1450                          */
1451
1452                         if ((r1->fed_by.find (r2) != r1->fed_by.end()) && (r2->fed_by.find (r1) != r2->fed_by.end())) {
1453                                 continue;
1454                         }
1455
1456                         /* now recurse, so that we can mark base as being fed by
1457                            all routes that feed r2
1458                         */
1459
1460                         trace_terminal (r2, rbase);
1461                 }
1462
1463         }
1464 }
1465
1466 void
1467 Session::resort_routes (void* src)
1468 {
1469         /* don't do anything here with signals emitted
1470            by Routes while we are being destroyed.
1471         */
1472
1473         if (_state_of_the_state & Deletion) {
1474                 return;
1475         }
1476
1477         /* Caller MUST hold the route_lock */
1478
1479         RouteList::iterator i, j;
1480
1481         for (i = routes.begin(); i != routes.end(); ++i) {
1482
1483                 (*i)->fed_by.clear ();
1484                 
1485                 for (j = routes.begin(); j != routes.end(); ++j) {
1486
1487                         /* although routes can feed themselves, it will
1488                            cause an endless recursive descent if we
1489                            detect it. so don't bother checking for
1490                            self-feeding.
1491                         */
1492
1493                         if (*j == *i) {
1494                                 continue;
1495                         }
1496
1497                         if ((*j)->feeds (*i)) {
1498                                 (*i)->fed_by.insert (*j);
1499                         } 
1500                 }
1501         }
1502         
1503         for (i = routes.begin(); i != routes.end(); ++i) {
1504                 trace_terminal (*i, *i);
1505         }
1506
1507         RouteSorter cmp;
1508         routes.sort (cmp);
1509
1510 #if 0
1511         cerr << "finished route resort\n";
1512         
1513         for (i = routes.begin(); i != routes.end(); ++i) {
1514                 cerr << " " << (*i)->name() << " signal order = " << (*i)->order_key ("signal") << endl;
1515         }
1516         cerr << endl;
1517 #endif
1518
1519 }
1520
1521 AudioTrack*
1522 Session::new_audio_track (int input_channels, int output_channels)
1523 {
1524         AudioTrack *track;
1525         char track_name[32];
1526         uint32_t n = 0;
1527         uint32_t channels_used = 0;
1528         string port;
1529         uint32_t nphysical_in;
1530         uint32_t nphysical_out;
1531
1532         /* count existing audio tracks */
1533
1534         {
1535                 LockMonitor lm (route_lock, __LINE__, __FILE__);
1536                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1537                         if (dynamic_cast<AudioTrack*>(*i) != 0) {
1538                                 if (!(*i)->hidden()) {
1539                                         n++;
1540                                         channels_used += (*i)->n_inputs();
1541                                 }
1542                         }
1543                 }
1544         }
1545
1546         /* check for duplicate route names, since we might have pre-existing
1547            routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1548            save, close,restart,add new route - first named route is now
1549            Audio2)
1550         */
1551
1552         do {
1553                 snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, n+1);
1554                 if (route_by_name (track_name) == 0) {
1555                         break;
1556                 }
1557                 n++;
1558
1559         } while (n < (UINT_MAX-1));
1560
1561         if (input_auto_connect & AutoConnectPhysical) {
1562                 nphysical_in = n_physical_inputs;
1563         } else {
1564                 nphysical_in = 0;
1565         }
1566
1567         if (output_auto_connect & AutoConnectPhysical) {
1568                 nphysical_out = n_physical_outputs;
1569         } else {
1570                 nphysical_out = 0;
1571         }
1572
1573         try {
1574                 track = new AudioTrack (*this, track_name);
1575
1576                 if (track->ensure_io (input_channels, output_channels, false, this)) {
1577                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1578                                           input_channels, output_channels)
1579                               << endmsg;
1580                 }
1581
1582                 if (nphysical_in) {
1583                         for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
1584                                 
1585                                 port = "";
1586                                 
1587                                 if (input_auto_connect & AutoConnectPhysical) {
1588                                         port = _engine.get_nth_physical_input ((channels_used+x)%nphysical_in);
1589                                 } 
1590                                 
1591                                 if (port.length() && track->connect_input (track->input (x), port, this)) {
1592                                         break;
1593                                 }
1594                         }
1595                 }
1596                 
1597                 for (uint32_t x = 0; x < track->n_outputs(); ++x) {
1598                         
1599                         port = "";
1600
1601                         if (nphysical_out && (output_auto_connect & AutoConnectPhysical)) {
1602                                 port = _engine.get_nth_physical_output ((channels_used+x)%nphysical_out);
1603                         } else if (output_auto_connect & AutoConnectMaster) {
1604                                 if (_master_out) {
1605                                         port = _master_out->input (x%_master_out->n_inputs())->name();
1606                                 }
1607                         }
1608
1609                         if (port.length() && track->connect_output (track->output (x), port, this)) {
1610                                 break;
1611                         }
1612                 }
1613
1614                 if (_control_out) {
1615                         vector<string> cports;
1616                         uint32_t ni = _control_out->n_inputs();
1617
1618                         for (n = 0; n < ni; ++n) {
1619                                 cports.push_back (_control_out->input(n)->name());
1620                         }
1621
1622                         track->set_control_outs (cports);
1623                 }
1624
1625                 track->diskstream_changed.connect (mem_fun (this, &Session::resort_routes));
1626
1627                 add_route (track);
1628         }
1629
1630         catch (failed_constructor &err) {
1631                 error << _("Session: could not create new audio track.") << endmsg;
1632                 return 0;
1633         }
1634
1635         return track;
1636 }
1637
1638 Route*
1639 Session::new_audio_route (int input_channels, int output_channels)
1640 {
1641         Route *bus;
1642         char bus_name[32];
1643         uint32_t n = 0;
1644         string port;
1645
1646         /* count existing audio busses */
1647
1648         {
1649                 LockMonitor lm (route_lock, __LINE__, __FILE__);
1650                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1651                         if (dynamic_cast<AudioTrack*>(*i) == 0) {
1652                                 if (!(*i)->hidden()) {
1653                                         n++;
1654                                 }
1655                         }
1656                 }
1657         }
1658
1659         do {
1660                 snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, n+1);
1661                 if (route_by_name (bus_name) == 0) {
1662                         break;
1663                 }
1664                 n++;
1665
1666         } while (n < (UINT_MAX-1));
1667
1668         try {
1669                 bus = new Route (*this, bus_name, -1, -1, -1, -1);
1670
1671                 if (bus->ensure_io (input_channels, output_channels, false, this)) {
1672                         error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1673                                           input_channels, output_channels)
1674                               << endmsg;
1675                 }
1676
1677                 for (uint32_t x = 0; x < bus->n_inputs(); ++x) {
1678                         
1679                         port = "";
1680
1681                         if (input_auto_connect & AutoConnectPhysical) {
1682                                 port = _engine.get_nth_physical_input ((n+x)%n_physical_inputs);
1683                         } 
1684                         
1685                         if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1686                                 break;
1687                         }
1688                 }
1689
1690                 for (uint32_t x = 0; x < bus->n_outputs(); ++x) {
1691                         
1692                         port = "";
1693
1694                         if (output_auto_connect & AutoConnectPhysical) {
1695                                 port = _engine.get_nth_physical_input ((n+x)%n_physical_outputs);
1696                         } else if (output_auto_connect & AutoConnectMaster) {
1697                                 if (_master_out) {
1698                                         port = _master_out->input (x%_master_out->n_inputs())->name();
1699                                 }
1700                         }
1701
1702                         if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1703                                 break;
1704                         }
1705                 }
1706
1707                 if (_control_out) {
1708                         vector<string> cports;
1709                         uint32_t ni = _control_out->n_inputs();
1710
1711                         for (uint32_t n = 0; n < ni; ++n) {
1712                                 cports.push_back (_control_out->input(n)->name());
1713                         }
1714                         bus->set_control_outs (cports);
1715                 }
1716                 
1717                 add_route (bus);
1718         }
1719
1720         catch (failed_constructor &err) {
1721                 error << _("Session: could not create new route.") << endmsg;
1722                 return 0;
1723         }
1724
1725         return bus;
1726 }
1727
1728 void
1729 Session::add_route (Route* route)
1730 {
1731         { 
1732                 LockMonitor lm (route_lock, __LINE__, __FILE__);
1733                 routes.push_front (route);
1734                 resort_routes(0);
1735         }
1736
1737         route->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), route));
1738         route->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1739         route->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1740         route->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
1741
1742         if (route->master()) {
1743                 _master_out = route;
1744         }
1745
1746         if (route->control()) {
1747                 _control_out = route;
1748         }
1749
1750         set_dirty();
1751         save_state (_current_snapshot_name);
1752
1753         RouteAdded (route); /* EMIT SIGNAL */
1754 }
1755
1756 void
1757 Session::add_diskstream (DiskStream* dstream)
1758 {
1759         { 
1760                 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
1761                 diskstreams.push_back (dstream);
1762         }
1763
1764         /* take a reference to the diskstream, preventing it from
1765            ever being deleted until the session itself goes away,
1766            or chooses to remove it for its own purposes.
1767         */
1768
1769         dstream->ref();
1770         dstream->set_block_size (current_block_size);
1771
1772         dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1773         /* this will connect to future changes, and check the current length */
1774         diskstream_playlist_changed (dstream);
1775
1776         dstream->prepare ();
1777
1778         set_dirty();
1779         save_state (_current_snapshot_name);
1780
1781         DiskStreamAdded (dstream); /* EMIT SIGNAL */
1782 }
1783
1784 void
1785 Session::remove_route (Route& route)
1786 {
1787         {       
1788                 LockMonitor lm (route_lock, __LINE__, __FILE__);
1789                 routes.remove (&route);
1790                 
1791                 /* deleting the master out seems like a dumb
1792                    idea, but its more of a UI policy issue
1793                    than our concern.
1794                 */
1795
1796                 if (&route == _master_out) {
1797                         _master_out = 0;
1798                 }
1799
1800                 if (&route == _control_out) {
1801                         _control_out = 0;
1802
1803                         /* cancel control outs for all routes */
1804
1805                         vector<string> empty;
1806
1807                         for (RouteList::iterator r = routes.begin(); r != routes.end(); ++r) {
1808                                 (*r)->set_control_outs (empty);
1809                         }
1810                 }
1811
1812                 update_route_solo_state ();
1813         }
1814
1815         {
1816                 LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
1817
1818                 AudioTrack* at;
1819
1820                 if ((at = dynamic_cast<AudioTrack*>(&route)) != 0) {
1821                         diskstreams.remove (&at->disk_stream());
1822                         at->disk_stream().unref ();
1823                 }
1824
1825                 find_current_end ();
1826         }
1827         
1828         update_latency_compensation (false, false);
1829         set_dirty();
1830         
1831         /* XXX should we disconnect from the Route's signals ? */
1832
1833         save_state (_current_snapshot_name);
1834
1835         delete &route;
1836 }       
1837
1838 void
1839 Session::route_mute_changed (void* src)
1840 {
1841         set_dirty ();
1842 }
1843
1844 void
1845 Session::route_solo_changed (void* src, Route* route)
1846 {      
1847         if (solo_update_disabled) {
1848                 // We know already
1849                 return;
1850         }
1851         
1852         LockMonitor lm (route_lock, __LINE__, __FILE__);
1853         bool is_track;
1854         
1855         is_track = (dynamic_cast<AudioTrack*>(route) != 0);
1856         
1857         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1858                 
1859                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
1860                 
1861                 if (is_track) {
1862                         
1863                         /* don't mess with busses */
1864                         
1865                         if (dynamic_cast<AudioTrack*>(*i) == 0) {
1866                                 continue;
1867                         }
1868                         
1869                 } else {
1870                         
1871                         /* don't mess with tracks */
1872                         
1873                         if (dynamic_cast<AudioTrack*>(*i) != 0) {
1874                                 continue;
1875                         }
1876                 }
1877                 
1878                 if ((*i) != route &&
1879                     ((*i)->mix_group () == 0 ||
1880                      (*i)->mix_group () != route->mix_group () ||
1881                      !route->mix_group ()->is_active())) {
1882                         
1883                         if ((*i)->soloed()) {
1884                                 
1885                                 /* if its already soloed, and solo latching is enabled,
1886                                    then leave it as it is.
1887                                 */
1888                                 
1889                                 if (_solo_latched) {
1890                                         continue;
1891                                 } 
1892                         }
1893                         
1894                         /* do it */
1895
1896                         solo_update_disabled = true;
1897                         (*i)->set_solo (false, src);
1898                         solo_update_disabled = false;
1899                 }
1900         }
1901         
1902         bool something_soloed = false;
1903         bool same_thing_soloed = false;
1904         bool signal = false;
1905
1906         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1907                 if ((*i)->soloed()) {
1908                         something_soloed = true;
1909                         if (dynamic_cast<AudioTrack*>(*i)) {
1910                                 if (is_track) {
1911                                         same_thing_soloed = true;
1912                                         break;
1913                                 }
1914                         } else {
1915                                 if (!is_track) {
1916                                         same_thing_soloed = true;
1917                                         break;
1918                                 }
1919                         }
1920                         break;
1921                 }
1922         }
1923         
1924         if (something_soloed != currently_soloing) {
1925                 signal = true;
1926                 currently_soloing = something_soloed;
1927         }
1928         
1929         modify_solo_mute (is_track, same_thing_soloed);
1930
1931         if (signal) {
1932                 SoloActive (currently_soloing);
1933         }
1934
1935         set_dirty();
1936 }
1937
1938 void
1939 Session::set_solo_latched (bool yn)
1940 {
1941         _solo_latched = yn;
1942         set_dirty ();
1943 }
1944
1945 void
1946 Session::update_route_solo_state ()
1947 {
1948         bool mute = false;
1949         bool is_track = false;
1950         bool signal = false;
1951
1952         /* caller must hold RouteLock */
1953
1954         /* this is where we actually implement solo by changing
1955            the solo mute setting of each track.
1956         */
1957                 
1958         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1959                 if ((*i)->soloed()) {
1960                         mute = true;
1961                         if (dynamic_cast<AudioTrack*>(*i)) {
1962                                 is_track = true;
1963                         }
1964                         break;
1965                 }
1966         }
1967
1968         if (mute != currently_soloing) {
1969                 signal = true;
1970                 currently_soloing = mute;
1971         }
1972
1973         if (!is_track && !mute) {
1974
1975                 /* nothing is soloed */
1976
1977                 for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1978                         (*i)->set_solo_mute (false);
1979                 }
1980                 
1981                 if (signal) {
1982                         SoloActive (false);
1983                 }
1984
1985                 return;
1986         }
1987
1988         modify_solo_mute (is_track, mute);
1989
1990         if (signal) {
1991                 SoloActive (currently_soloing);
1992         }
1993 }
1994
1995 void
1996 Session::modify_solo_mute (bool is_track, bool mute)
1997 {
1998         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
1999                 
2000                 if (is_track) {
2001                         
2002                         /* only alter track solo mute */
2003                         
2004                         if (dynamic_cast<AudioTrack*>(*i)) {
2005                                 if ((*i)->soloed()) {
2006                                         (*i)->set_solo_mute (!mute);
2007                                 } else {
2008                                         (*i)->set_solo_mute (mute);
2009                                 }
2010                         }
2011
2012                 } else {
2013
2014                         /* only alter bus solo mute */
2015
2016                         if (!dynamic_cast<AudioTrack*>(*i)) {
2017
2018                                 if ((*i)->soloed()) {
2019
2020                                         (*i)->set_solo_mute (false);
2021
2022                                 } else {
2023
2024                                         /* don't mute master or control outs
2025                                            in response to another bus solo
2026                                         */
2027                                         
2028                                         if ((*i) != _master_out &&
2029                                             (*i) != _control_out) {
2030                                                 (*i)->set_solo_mute (mute);
2031                                         }
2032                                 }
2033                         }
2034
2035                 }
2036         }
2037 }       
2038
2039
2040 void
2041 Session::catch_up_on_solo ()
2042 {
2043         /* this is called after set_state() to catch the full solo
2044            state, which can't be correctly determined on a per-route
2045            basis, but needs the global overview that only the session
2046            has.
2047         */
2048         LockMonitor lm (route_lock, __LINE__, __FILE__);
2049         update_route_solo_state();
2050 }       
2051                 
2052 Route *
2053 Session::route_by_name (string name)
2054 {
2055         LockMonitor lm (route_lock, __LINE__, __FILE__);
2056
2057         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2058                 if ((*i)->name() == name) {
2059                         return* i;
2060                 }
2061         }
2062
2063         return 0;
2064 }
2065
2066 void
2067 Session::find_current_end ()
2068 {
2069         jack_nframes_t max = 0;
2070         jack_nframes_t me; 
2071
2072         if (_state_of_the_state & Loading) {
2073                 return;
2074         }
2075
2076         /* Don't take the diskstream lock. Caller must have other ways to
2077            ensure atomicity.
2078         */
2079
2080         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2081                 Playlist* pl = (*i)->playlist();
2082                 if ((me = pl->get_maximum_extent()) > max) {
2083                         max = me;
2084                 }
2085         }
2086         
2087         if (max > end_location->end()) {
2088                 end_location->set_end (max);
2089                 set_dirty();
2090                 DurationChanged(); /* EMIT SIGNAL */
2091         }
2092 }
2093
2094 DiskStream *
2095 Session::diskstream_by_name (string name)
2096 {
2097         LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2098
2099         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2100                 if ((*i)->name() == name) {
2101                         return* i;
2102                 }
2103         }
2104
2105         return 0;
2106 }
2107
2108 DiskStream *
2109 Session::diskstream_by_id (id_t id)
2110 {
2111         LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2112
2113         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2114                 if ((*i)->id() == id) {
2115                         return *i;
2116                 }
2117         }
2118
2119         return 0;
2120 }
2121
2122 /* AudioRegion management */
2123
2124 string
2125 Session::new_region_name (string old)
2126 {
2127         string::size_type last_period;
2128         uint32_t number;
2129         string::size_type len = old.length() + 64;
2130         char buf[len];
2131
2132         if ((last_period = old.find_last_of ('.')) == string::npos) {
2133                 
2134                 /* no period present - add one explicitly */
2135
2136                 old += '.';
2137                 last_period = old.length() - 1;
2138                 number = 0;
2139
2140         } else {
2141
2142                 number = atoi (old.substr (last_period+1).c_str());
2143
2144         }
2145
2146         while (number < (UINT_MAX-1)) {
2147
2148                 AudioRegionList::const_iterator i;
2149                 string sbuf;
2150
2151                 number++;
2152
2153                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2154                 sbuf = buf;
2155
2156                 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2157                         if ((*i).second->name() == sbuf) {
2158                                 break;
2159                         }
2160                 }
2161                 
2162                 if (i == audio_regions.end()) {
2163                         break;
2164                 }
2165         }
2166
2167         if (number != (UINT_MAX-1)) {
2168                 return buf;
2169         } 
2170
2171         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2172         return old;
2173 }
2174
2175 int
2176 Session::region_name (string& result, string base, bool newlevel) const
2177 {
2178         char buf[16];
2179         string subbase;
2180
2181         if (base == "") {
2182                 
2183                 LockMonitor lm (region_lock, __LINE__, __FILE__);
2184
2185                 snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
2186
2187                 
2188                 result = "region.";
2189                 result += buf;
2190
2191         } else {
2192
2193                 /* XXX this is going to be slow. optimize me later */
2194                 
2195                 if (newlevel) {
2196                         subbase = base;
2197                 } else {
2198                         string::size_type pos;
2199
2200                         if ((pos = base.find_last_of ('-')) == string::npos) {
2201                                 pos = base.find_last_of ('.');
2202                         }
2203
2204                         /* pos may be npos, but then we just use entire base */
2205
2206                         subbase = base.substr (0, pos);
2207                 }
2208                 
2209                 bool name_taken = true;
2210                 
2211                 {
2212                         LockMonitor lm (region_lock, __LINE__, __FILE__);
2213                         
2214                         for (int n = 1; n < 5000; ++n) {
2215                                 
2216                                 result = subbase;
2217                                 snprintf (buf, sizeof (buf), ".%d", n);
2218                                 result += buf;
2219                                 
2220                                 name_taken = false;
2221                                 
2222                                 for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2223                                         if ((*i).second->name() == result) {
2224                                                 name_taken = true;
2225                                                 break;
2226                                         }
2227                                 }
2228                                 
2229                                 if (!name_taken) {
2230                                         break;
2231                                 }
2232                         }
2233                 }
2234                         
2235                 if (name_taken) {
2236                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2237                         /*NOTREACHED*/
2238                 }
2239         }
2240
2241         return 0;
2242 }       
2243
2244 void
2245 Session::add_region (Region* region)
2246 {
2247         AudioRegion* ar = 0;
2248         AudioRegion* oar = 0;
2249         bool added = false;
2250
2251         { 
2252                 LockMonitor lm (region_lock, __LINE__, __FILE__);
2253
2254                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2255
2256                         AudioRegionList::iterator x;
2257
2258                         for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
2259
2260                                 oar = dynamic_cast<AudioRegion*> (x->second);
2261
2262                                 if (ar->region_list_equivalent (*oar)) {
2263                                         break;
2264                                 }
2265                         }
2266
2267                         if (x == audio_regions.end()) {
2268
2269                                 pair<AudioRegionList::key_type, AudioRegionList::mapped_type> entry;
2270         
2271                                 entry.first = region->id();
2272                                 entry.second = ar;
2273
2274                                 pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
2275                                 
2276                                 if (!x.second) {
2277                                         return;
2278                                 }
2279
2280                                 added = true;
2281                         } 
2282
2283                 } else {
2284
2285                         fatal << _("programming error: ")
2286                               << X_("unknown region type passed to Session::add_region()")
2287                               << endmsg;
2288                         /*NOTREACHED*/
2289
2290                 }
2291         }
2292
2293         /* mark dirty because something has changed even if we didn't
2294            add the region to the region list.
2295         */
2296         
2297         set_dirty();
2298         
2299         if (added) {
2300                 region->GoingAway.connect (mem_fun (*this, &Session::remove_region));
2301                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), region));
2302                 AudioRegionAdded (ar); /* EMIT SIGNAL */
2303         }
2304 }
2305
2306 void
2307 Session::region_changed (Change what_changed, Region* region)
2308 {
2309         if (what_changed & Region::HiddenChanged) {
2310                 /* relay hidden changes */
2311                 RegionHiddenChange (region);
2312         }
2313 }
2314
2315 void
2316 Session::region_renamed (Region* region)
2317 {
2318         add_region (region);
2319 }
2320
2321 void
2322 Session::remove_region (Region* region)
2323 {
2324         AudioRegionList::iterator i;
2325         AudioRegion* ar = 0;
2326         bool removed = false;
2327
2328         { 
2329                 LockMonitor lm (region_lock, __LINE__, __FILE__);
2330
2331                 if ((ar = dynamic_cast<AudioRegion*> (region)) != 0) {
2332                         if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
2333                                 audio_regions.erase (i);
2334                                 removed = true;
2335                         } 
2336                 } else {
2337                         fatal << _("programming error: ") 
2338                               << X_("unknown region type passed to Session::remove_region()")
2339                               << endmsg;
2340                         /*NOTREACHED*/
2341                 }
2342         }
2343
2344         /* mark dirty because something has changed even if we didn't
2345            remove the region from the region list.
2346         */
2347
2348         set_dirty();
2349
2350         if (removed) {
2351                  AudioRegionRemoved(ar); /* EMIT SIGNAL */
2352         }
2353 }
2354
2355 AudioRegion*
2356 Session::find_whole_file_parent (AudioRegion& child)
2357 {
2358         AudioRegionList::iterator i;
2359         AudioRegion* region;
2360         LockMonitor lm (region_lock, __LINE__, __FILE__);
2361
2362         for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2363
2364                 region = (*i).second;
2365
2366                 if (region->whole_file()) {
2367
2368                         if (child.source_equivalent (*region)) {
2369                                 return region;
2370                         }
2371                 }
2372         } 
2373
2374         return 0;
2375 }       
2376
2377 void
2378 Session::find_equivalent_playlist_regions (AudioRegion& region, vector<AudioRegion*>& result)
2379 {
2380         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2381
2382                 AudioPlaylist* pl;
2383
2384                 if ((pl = dynamic_cast<AudioPlaylist*>(*i)) == 0) {
2385                         continue;
2386                 }
2387
2388                 pl->get_region_list_equivalent_regions (region, result);
2389         }
2390 }
2391
2392 int
2393 Session::destroy_region (Region* region)
2394 {
2395         AudioRegion* aregion;
2396
2397         if ((aregion = dynamic_cast<AudioRegion*> (region)) == 0) {
2398                 return 0;
2399         }
2400
2401         if (aregion->playlist()) {
2402                 aregion->playlist()->destroy_region (region);
2403         }
2404
2405         vector<Source*> srcs;
2406         
2407         for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2408                 srcs.push_back (&aregion->source (n));
2409         }
2410
2411         for (vector<Source*>::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2412                 
2413                 if ((*i)->use_cnt() == 0) {
2414                         (*i)->mark_for_remove ();
2415                         delete *i;
2416                 }
2417         }
2418
2419         return 0;
2420 }
2421
2422 int
2423 Session::destroy_regions (list<Region*> regions)
2424 {
2425         for (list<Region*>::iterator i = regions.begin(); i != regions.end(); ++i) {
2426                 destroy_region (*i);
2427         }
2428         return 0;
2429 }
2430
2431 int
2432 Session::remove_last_capture ()
2433 {
2434         list<Region*> r;
2435
2436         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2437                 list<Region*>& l = (*i)->last_capture_regions();
2438                 
2439                 if (!l.empty()) {
2440                         r.insert (r.end(), l.begin(), l.end());
2441                         l.clear ();
2442                 }
2443         }
2444
2445         destroy_regions (r);
2446         return 0;
2447 }
2448
2449 int
2450 Session::remove_region_from_region_list (Region& r)
2451 {
2452         remove_region (&r);
2453         return 0;
2454 }
2455
2456 /* Source Management */
2457
2458 void
2459 Session::add_source (Source* source)
2460 {
2461         pair<SourceList::key_type, SourceList::mapped_type> entry;
2462         
2463         {
2464                 LockMonitor lm (source_lock, __LINE__, __FILE__);
2465                 entry.first = source->id();
2466                 entry.second = source;
2467                 sources.insert (entry);
2468         }
2469         
2470         source->GoingAway.connect (mem_fun (this, &Session::remove_source));
2471         set_dirty();
2472         
2473         SourceAdded (source); /* EMIT SIGNAL */
2474 }
2475
2476 void
2477 Session::remove_source (Source* source)
2478 {
2479         SourceList::iterator i;
2480
2481         { 
2482                 LockMonitor lm (source_lock, __LINE__, __FILE__);
2483
2484                 if ((i = sources.find (source->id())) != sources.end()) {
2485                         sources.erase (i);
2486                 }
2487         }
2488
2489         if (!_state_of_the_state & InCleanup) {
2490
2491                 /* save state so we don't end up with a session file
2492                    referring to non-existent sources.
2493                 */
2494                 
2495                 save_state (_current_snapshot_name);
2496         }
2497
2498         SourceRemoved(source); /* EMIT SIGNAL */
2499 }
2500
2501 Source *
2502 Session::get_source (ARDOUR::id_t id)
2503 {
2504         LockMonitor lm (source_lock, __LINE__, __FILE__);
2505         SourceList::iterator i;
2506         Source* source = 0;
2507
2508         if ((i = sources.find (id)) != sources.end()) {
2509                 source = (*i).second;
2510         }
2511
2512         return source;
2513 }
2514
2515 FileSource *
2516 Session::create_file_source (DiskStream& ds, int32_t chan)
2517 {
2518         string spath;
2519         uint32_t cnt;
2520         char buf[PATH_MAX+1];
2521         const uint32_t limit = 10000;
2522         string legalized;
2523
2524         buf[0] = '\0';
2525         legalized = legalize_for_path (ds.name());
2526
2527         /* find a "version" of the file name that doesn't exist in
2528            any of the possible directories.
2529         */
2530         
2531         for (cnt = 1; cnt <= limit; ++cnt) {
2532
2533                 vector<space_and_path>::iterator i;
2534                 uint32_t existing = 0;
2535
2536                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2537
2538                         spath = (*i).path;
2539                         spath += sound_dir_name;
2540                         spath += '/';
2541                         spath += legalized;
2542
2543                         if (ds.n_channels() < 2) {
2544                                 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2545                         } else if (ds.n_channels() == 2) {
2546                                 if (chan == 0) {
2547                                         snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2548                                 } else {
2549                                         snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2550                                 }
2551                         } else if (ds.n_channels() < 26) {
2552                                 snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2553                         } else {
2554                                 snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2555                         }
2556
2557                         if (access (buf, F_OK) == 0) {
2558                                 existing++;
2559                         }
2560                 }
2561
2562                 if (existing == 0) {
2563                         break;
2564                 }
2565         }
2566
2567         if (cnt > limit) {
2568                 error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, ds.name()) << endmsg;
2569                 throw failed_constructor();
2570         }
2571
2572         /* we now have a unique name for the file, but figure out where to
2573            actually put it.
2574         */
2575
2576         string foo = buf;
2577
2578         spath = discover_best_sound_dir ();
2579
2580         string::size_type pos = foo.find_last_of ('/');
2581         
2582         if (pos == string::npos) {
2583                 spath += foo;
2584         } else {
2585                 spath += foo.substr (pos + 1);
2586         }
2587
2588         /* this might throw failed_constructor(), which is OK */
2589
2590         return new FileSource (spath, frame_rate());
2591 }
2592
2593 /* Playlist management */
2594
2595 Playlist *
2596 Session::get_playlist (string name)
2597 {
2598         Playlist* ret = 0;
2599
2600         if ((ret = playlist_by_name (name)) == 0) {
2601                 ret = new AudioPlaylist (*this, name);
2602         }
2603
2604         return ret;
2605 }
2606
2607 Playlist *
2608 Session::playlist_by_name (string name)
2609 {
2610         LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2611         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2612                 if ((*i)->name() == name) {
2613                         return* i;
2614                 }
2615         }
2616         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
2617                 if ((*i)->name() == name) {
2618                         return* i;
2619                 }
2620         }
2621         return 0;
2622 }
2623
2624 void
2625 Session::add_playlist (Playlist* playlist)
2626 {
2627         if (playlist->hidden()) {
2628                 return;
2629         }
2630
2631         { 
2632                 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2633                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
2634                         playlists.insert (playlists.begin(), playlist);
2635                         // playlist->ref();
2636                         playlist->InUse.connect (mem_fun (*this, &Session::track_playlist));
2637                         playlist->GoingAway.connect (mem_fun (*this, &Session::remove_playlist));
2638                 }
2639         }
2640
2641         set_dirty();
2642
2643         PlaylistAdded (playlist); /* EMIT SIGNAL */
2644 }
2645
2646 void
2647 Session::track_playlist (Playlist* pl, bool inuse)
2648 {
2649         PlaylistList::iterator x;
2650
2651         { 
2652                 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2653
2654                 if (!inuse) {
2655                         //cerr << "shifting playlist to unused: " << pl->name() << endl;
2656
2657                         unused_playlists.insert (pl);
2658                         
2659                         if ((x = playlists.find (pl)) != playlists.end()) {
2660                                 playlists.erase (x);
2661                         }
2662
2663                         
2664                 } else {
2665                         //cerr << "shifting playlist to used: " << pl->name() << endl;
2666                         
2667                         playlists.insert (pl);
2668                         
2669                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
2670                                 unused_playlists.erase (x);
2671                         }
2672                 }
2673         }
2674 }
2675
2676 void
2677 Session::remove_playlist (Playlist* playlist)
2678 {
2679         if (_state_of_the_state & Deletion) {
2680                 return;
2681         }
2682
2683         { 
2684                 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
2685                 // cerr << "removing playlist: " << playlist->name() << endl;
2686
2687                 PlaylistList::iterator i;
2688
2689                 i = find (playlists.begin(), playlists.end(), playlist);
2690
2691                 if (i != playlists.end()) {
2692                         playlists.erase (i);
2693                 }
2694
2695                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
2696                 if (i != unused_playlists.end()) {
2697                         unused_playlists.erase (i);
2698                 }
2699                 
2700         }
2701
2702         set_dirty();
2703
2704         PlaylistRemoved (playlist); /* EMIT SIGNAL */
2705 }
2706
2707 void 
2708 Session::set_audition (AudioRegion* r)
2709 {
2710         pending_audition_region = r;
2711         post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
2712         schedule_butler_transport_work ();
2713 }
2714
2715 void
2716 Session::non_realtime_set_audition ()
2717 {
2718         if (pending_audition_region == (AudioRegion*) 0xfeedface) {
2719                 auditioner->audition_current_playlist ();
2720         } else if (pending_audition_region) {
2721                 auditioner->audition_region (*pending_audition_region);
2722         }
2723         pending_audition_region = 0;
2724         AuditionActive (true); /* EMIT SIGNAL */
2725 }
2726
2727 void
2728 Session::audition_playlist ()
2729 {
2730         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
2731         ev->set_ptr ((void*) 0xfeedface);
2732         queue_event (ev);
2733 }
2734
2735 void
2736 Session::audition_region (AudioRegion& r)
2737 {
2738         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
2739         ev->set_ptr (&r);
2740         queue_event (ev);
2741 }
2742
2743 void
2744 Session::cancel_audition ()
2745 {
2746         if (auditioner->active()) {
2747                 auditioner->cancel_audition ();
2748                  AuditionActive (false); /* EMIT SIGNAL */
2749         }
2750 }
2751
2752 bool
2753 Session::RoutePublicOrderSorter::operator() (Route* a, Route* b)
2754 {
2755         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
2756 }
2757
2758 void
2759 Session::remove_empty_sounds ()
2760 {
2761
2762         PathScanner scanner;
2763         string dir;
2764
2765         dir = sound_dir ();
2766
2767         vector<string *>* possible_audiofiles = scanner (dir, "\\.wav$", false, true);
2768         
2769         for (vector<string *>::iterator i = possible_audiofiles->begin(); i != possible_audiofiles->end(); ++i) {
2770
2771                 if (FileSource::is_empty (*(*i))) {
2772
2773                         unlink ((*i)->c_str());
2774                         
2775                         string peak_path = peak_path_from_audio_path (**i);
2776                         unlink (peak_path.c_str());
2777                 }
2778
2779                 delete* i;
2780         }
2781
2782         delete possible_audiofiles;
2783 }
2784
2785 bool
2786 Session::is_auditioning () const
2787 {
2788         /* can be called before we have an auditioner object */
2789         if (auditioner) {
2790                 return auditioner->active();
2791         } else {
2792                 return false;
2793         }
2794 }
2795
2796
2797 string
2798 Session::peak_path_from_audio_path (string audio_path)
2799 {
2800         /* XXX hardly bombproof! fix me */
2801
2802         string res;
2803
2804         res = PBD::dirname (audio_path);
2805         res = PBD::dirname (res);
2806         res += '/';
2807         res += peak_dir_name;
2808         res += '/';
2809         res += PBD::basename_nosuffix (audio_path);
2810         res += ".peak";
2811
2812         return res;
2813 }
2814
2815 string
2816 Session::old_peak_path_from_audio_path (string audio_path)
2817 {
2818         /* This is a hangover from when audio and peak files
2819            lived in the same directory. We need it to to 
2820            be able to open old sessions.
2821         */
2822
2823         /* XXX hardly bombproof! fix me */
2824
2825         string res = audio_path.substr (0, audio_path.find_last_of ('.'));
2826         res += ".peak";
2827         return res;
2828 }
2829
2830 void
2831 Session::set_all_solo (bool yn)
2832 {
2833         /* XXX this copy is not safe: the Routes within the list
2834            can still be deleted after the Route lock is released.
2835         */
2836
2837         RouteList copy;
2838         {
2839                 LockMonitor lm (route_lock, __LINE__, __FILE__);
2840                 copy = routes;
2841         }
2842
2843         for (RouteList::iterator i = copy.begin(); i != copy.end(); ++i) {
2844                 if (!(*i)->hidden()) {
2845                         (*i)->set_solo (yn, this);
2846                 }
2847         }
2848
2849         set_dirty();
2850 }
2851                 
2852 void
2853 Session::set_all_mute (bool yn)
2854 {
2855         RouteList copy;
2856         {
2857                 LockMonitor lm (route_lock, __LINE__, __FILE__);
2858                 copy = routes;
2859         }
2860
2861         for (RouteList::iterator i = copy.begin(); i != copy.end(); ++i) {
2862                 if (!(*i)->hidden()) {
2863                         (*i)->set_mute (yn, this);
2864                 }
2865         }
2866
2867         set_dirty();
2868 }
2869                 
2870 uint32_t
2871 Session::n_diskstreams () const
2872 {
2873         LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2874         uint32_t n = 0;
2875
2876         for (DiskStreamList::const_iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2877                 if (!(*i)->hidden()) {
2878                         n++;
2879                 }
2880         }
2881         return n;
2882 }
2883
2884 void 
2885 Session::foreach_diskstream (void (DiskStream::*func)(void)) 
2886 {
2887         LockMonitor lm (diskstream_lock, __LINE__, __FILE__);
2888         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2889                 if (!(*i)->hidden()) {
2890                         ((*i)->*func)();
2891                 }
2892         }
2893 }
2894
2895 void
2896 Session::graph_reordered ()
2897 {
2898         /* don't do this stuff if we are setting up connections
2899            from a set_state() call.
2900         */
2901
2902         if (_state_of_the_state & InitialConnecting) {
2903                 return;
2904         }
2905
2906         LockMonitor lm1 (route_lock, __LINE__, __FILE__);
2907         LockMonitor lm2 (diskstream_lock, __LINE__, __FILE__);
2908
2909         resort_routes (0);
2910
2911         /* force all diskstreams to update their capture offset values to 
2912            reflect any changes in latencies within the graph.
2913         */
2914         
2915         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
2916                 (*i)->set_capture_offset ();
2917         }
2918 }
2919
2920 void
2921 Session::record_disenable_all ()
2922 {
2923         record_enable_change_all (false);
2924 }
2925
2926 void
2927 Session::record_enable_all ()
2928 {
2929         record_enable_change_all (true);
2930 }
2931
2932 void
2933 Session::record_enable_change_all (bool yn)
2934 {
2935         LockMonitor lm1 (route_lock, __LINE__, __FILE__);
2936         
2937         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
2938                 AudioTrack* at;
2939
2940                 if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
2941                         at->set_record_enable (yn, this);
2942                 }
2943         }
2944         
2945         /* since we don't keep rec-enable state, don't mark session dirty */
2946 }
2947
2948 void
2949 Session::add_redirect (Redirect* redirect)
2950 {
2951         Send* send;
2952         Insert* insert;
2953         PortInsert* port_insert;
2954         PluginInsert* plugin_insert;
2955
2956         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
2957                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
2958                         _port_inserts.insert (_port_inserts.begin(), port_insert);
2959                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
2960                         _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
2961                 } else {
2962                         fatal << _("programming error: unknown type of Insert created!") << endmsg;
2963                         /*NOTREACHED*/
2964                 }
2965         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
2966                 _sends.insert (_sends.begin(), send);
2967         } else {
2968                 fatal << _("programming error: unknown type of Redirect created!") << endmsg;
2969                 /*NOTREACHED*/
2970         }
2971
2972         redirect->GoingAway.connect (mem_fun (*this, &Session::remove_redirect));
2973
2974         set_dirty();
2975 }
2976
2977 void
2978 Session::remove_redirect (Redirect* redirect)
2979 {
2980         Send* send;
2981         Insert* insert;
2982         PortInsert* port_insert;
2983         PluginInsert* plugin_insert;
2984
2985         if ((insert = dynamic_cast<Insert *> (redirect)) != 0) {
2986                 if ((port_insert = dynamic_cast<PortInsert *> (insert)) != 0) {
2987                         _port_inserts.remove (port_insert);
2988                 } else if ((plugin_insert = dynamic_cast<PluginInsert *> (insert)) != 0) {
2989                         _plugin_inserts.remove (plugin_insert);
2990                 } else {
2991                         fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
2992                         /*NOTREACHED*/
2993                 }
2994         } else if ((send = dynamic_cast<Send *> (redirect)) != 0) {
2995                 _sends.remove (send);
2996         } else {
2997                 fatal << _("programming error: unknown type of Redirect deleted!") << endmsg;
2998                 /*NOTREACHED*/
2999         }
3000
3001         set_dirty();
3002 }
3003
3004 jack_nframes_t
3005 Session::available_capture_duration ()
3006 {
3007         const double scale = 4096.0 / sizeof (Sample);
3008         
3009         if (_total_free_4k_blocks * scale > (double) max_frames) {
3010                 return max_frames;
3011         }
3012         
3013         return (jack_nframes_t) floor (_total_free_4k_blocks * scale);
3014 }
3015
3016 void
3017 Session::add_connection (ARDOUR::Connection* connection)
3018 {
3019         {
3020                 LockMonitor (connection_lock, __LINE__, __FILE__);
3021                 _connections.push_back (connection);
3022         }
3023         
3024         ConnectionAdded (connection); /* EMIT SIGNAL */
3025
3026         set_dirty();
3027 }
3028
3029 void
3030 Session::remove_connection (ARDOUR::Connection* connection)
3031 {
3032         bool removed = false;
3033
3034         {
3035                 LockMonitor (connection_lock, __LINE__, __FILE__);
3036                 ConnectionList::iterator i = find (_connections.begin(), _connections.end(), connection);
3037                 
3038                 if (i != _connections.end()) {
3039                         _connections.erase (i);
3040                         removed = true;
3041                 }
3042         }
3043
3044         if (removed) {
3045                  ConnectionRemoved (connection); /* EMIT SIGNAL */
3046         }
3047
3048         set_dirty();
3049 }
3050
3051 ARDOUR::Connection *
3052 Session::connection_by_name (string name) const
3053 {
3054         LockMonitor lm (connection_lock, __LINE__, __FILE__);
3055
3056         for (ConnectionList::const_iterator i = _connections.begin(); i != _connections.end(); ++i) {
3057                 if ((*i)->name() == name) {
3058                         return* i;
3059                 }
3060         }
3061
3062         return 0;
3063 }
3064
3065 void
3066 Session::set_edit_mode (EditMode mode)
3067 {
3068         _edit_mode = mode;
3069         
3070         { 
3071                 LockMonitor lm (playlist_lock, __LINE__, __FILE__);
3072                 
3073                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3074                         (*i)->set_edit_mode (mode);
3075                 }
3076         }
3077
3078         set_dirty ();
3079         ControlChanged (EditingMode); /* EMIT SIGNAL */
3080 }
3081
3082 void
3083 Session::tempo_map_changed (Change ignored)
3084 {
3085         clear_clicks ();
3086         set_dirty ();
3087 }
3088
3089 void
3090 Session::ensure_passthru_buffers (uint32_t howmany)
3091 {
3092         while (howmany > _passthru_buffers.size()) {
3093                 Sample *p;
3094 #ifdef NO_POSIX_MEMALIGN
3095                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3096 #else
3097                 posix_memalign((void **)&p,16,current_block_size * 4);
3098 #endif                  
3099                 _passthru_buffers.push_back (p);
3100
3101                 *p = 0;
3102                 
3103 #ifdef NO_POSIX_MEMALIGN
3104                 p =  (Sample *) malloc(current_block_size * sizeof(Sample));
3105 #else
3106                 posix_memalign((void **)&p,16,current_block_size * 4);
3107 #endif                  
3108                 memset (p, 0, sizeof (Sample) * current_block_size);
3109                 _silent_buffers.push_back (p);
3110
3111         }
3112         allocate_pan_automation_buffers (current_block_size, howmany, false);
3113 }
3114
3115 string
3116 Session::next_send_name ()
3117 {
3118         char buf[32];
3119         snprintf (buf, sizeof (buf), "send %" PRIu32, ++send_cnt);
3120         return buf;
3121 }
3122
3123 string
3124 Session::next_insert_name ()
3125 {
3126         char buf[32];
3127         snprintf (buf, sizeof (buf), "insert %" PRIu32, ++insert_cnt);
3128         return buf;
3129 }
3130
3131 /* Named Selection management */
3132
3133 NamedSelection *
3134 Session::named_selection_by_name (string name)
3135 {
3136         LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
3137         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3138                 if ((*i)->name == name) {
3139                         return* i;
3140                 }
3141         }
3142         return 0;
3143 }
3144
3145 void
3146 Session::add_named_selection (NamedSelection* named_selection)
3147 {
3148         { 
3149                 LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
3150                 named_selections.insert (named_selections.begin(), named_selection);
3151         }
3152
3153         set_dirty();
3154
3155          NamedSelectionAdded (); /* EMIT SIGNAL */
3156 }
3157
3158 void
3159 Session::remove_named_selection (NamedSelection* named_selection)
3160 {
3161         bool removed = false;
3162
3163         { 
3164                 LockMonitor lm (named_selection_lock, __LINE__, __FILE__);
3165
3166                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3167
3168                 if (i != named_selections.end()) {
3169                         delete (*i);
3170                         named_selections.erase (i);
3171                         set_dirty();
3172                         removed = true;
3173                 }
3174         }
3175
3176         if (removed) {
3177                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3178         }
3179 }
3180
3181 void
3182 Session::reset_native_file_format ()
3183 {
3184         LockMonitor lm1 (route_lock, __LINE__, __FILE__);
3185         LockMonitor lm2 (diskstream_lock, __LINE__, __FILE__);
3186
3187         for (DiskStreamList::iterator i = diskstreams.begin(); i != diskstreams.end(); ++i) {
3188                 (*i)->reset_write_sources (false);
3189         }
3190 }
3191
3192 bool
3193 Session::route_name_unique (string n) const
3194 {
3195         LockMonitor lm (route_lock, __LINE__, __FILE__);
3196         
3197         for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3198                 if ((*i)->name() == n) {
3199                         return false;
3200                 }
3201         }
3202         
3203         return true;
3204 }
3205
3206 int
3207 Session::remove_file_source (FileSource& fs)
3208 {
3209         return fs.move_to_trash (dead_sound_dir_name);
3210 }
3211
3212 uint32_t
3213 Session::n_playlists () const
3214 {
3215         LockMonitor lm (playlist_lock, __LINE__, __FILE__);
3216         return playlists.size();
3217 }
3218
3219 void
3220 Session::set_align_style (AlignStyle style)
3221 {
3222         align_style = style;
3223
3224         foreach_diskstream (&DiskStream::set_capture_offset);
3225
3226         set_dirty ();
3227         ControlChanged (AlignChoice);
3228 }
3229
3230 void
3231 Session::set_solo_model (SoloModel sm)
3232 {
3233         _solo_model = sm;
3234         set_dirty ();
3235 }
3236
3237 void
3238 Session::allocate_pan_automation_buffers (jack_nframes_t nframes, uint32_t howmany, bool force)
3239 {
3240         if (!force && howmany <= _npan_buffers) {
3241                 return;
3242         }
3243
3244         if (_pan_automation_buffer) {
3245
3246                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3247                         delete [] _pan_automation_buffer[i];
3248                 }
3249
3250                 delete [] _pan_automation_buffer;
3251         }
3252
3253         _pan_automation_buffer = new pan_t*[howmany];
3254         
3255         for (uint32_t i = 0; i < howmany; ++i) {
3256                 _pan_automation_buffer[i] = new pan_t[nframes];
3257         }
3258
3259         _npan_buffers = howmany;
3260 }
3261
3262 void 
3263 Session::add_instant_xml (XMLNode& node, const std::string& dir)
3264 {
3265         Stateful::add_instant_xml (node, dir);
3266         Config->add_instant_xml (node, Config->get_user_ardour_path());
3267 }
3268
3269 int
3270 Session::freeze (InterThreadInfo& itt)
3271 {
3272         LockMonitor lm (route_lock, __LINE__, __FILE__);
3273
3274         for (RouteList::iterator i = routes.begin(); i != routes.end(); ++i) {
3275
3276                 AudioTrack *at;
3277
3278                 if ((at = dynamic_cast<AudioTrack*>(*i)) != 0) {
3279                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3280                            of every track.
3281                         */
3282                         at->freeze (itt);
3283                 }
3284         }
3285
3286         return 0;
3287 }
3288
3289 int
3290 Session::write_one_track (AudioTrack& track, jack_nframes_t start, jack_nframes_t len,  bool overwrite, vector<Source*>& srcs,
3291                           InterThreadInfo& itt)
3292 {
3293         int ret = -1;
3294         Playlist* playlist;
3295         FileSource* fsource;
3296         uint32_t x;
3297         char buf[PATH_MAX+1];
3298         string dir;
3299         uint32_t nchans;
3300         jack_nframes_t position;
3301         jack_nframes_t this_chunk;
3302         jack_nframes_t to_do;
3303         vector<Sample*> buffers;
3304         const jack_nframes_t chunk_size = (256 * 1024)/4;
3305
3306         atomic_set (&processing_prohibited, 1);
3307         
3308         /* call tree *MUST* hold route_lock */
3309         
3310         if ((playlist = track.disk_stream().playlist()) == 0) {
3311                 goto out;
3312         }
3313
3314         /* external redirects will be a problem */
3315
3316         if (track.has_external_redirects()) {
3317                 goto out;
3318         }
3319
3320         nchans = track.disk_stream().n_channels();
3321         
3322         dir = discover_best_sound_dir ();
3323
3324         for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
3325
3326                 for (x = 0; x < 99999; ++x) {
3327                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3328                         if (access (buf, F_OK) != 0) {
3329                                 break;
3330                         }
3331                 }
3332                 
3333                 if (x == 99999) {
3334                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3335                         goto out;
3336                 }
3337                 
3338                 try {
3339                         fsource = new FileSource (buf, frame_rate());
3340                 }
3341                 
3342                 catch (failed_constructor& err) {
3343                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3344                         goto out;
3345                 }
3346
3347                 srcs.push_back(fsource);
3348         }
3349
3350         /* XXX need to flush all redirects */
3351         
3352         position = start;
3353         to_do = len;
3354
3355         /* create a set of reasonably-sized buffers */
3356
3357         for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
3358                 Sample* b;
3359 #ifdef NO_POSIX_MEMALIGN
3360                 b =  (Sample *) malloc(chunk_size * sizeof(Sample));
3361 #else
3362                 posix_memalign((void **)&b,16,chunk_size * 4);
3363 #endif                  
3364                 buffers.push_back (b);
3365         }
3366         
3367         while (to_do && !itt.cancel) {
3368                 
3369                 this_chunk = min (to_do, chunk_size);
3370                 
3371                 if (track.export_stuff (buffers, nchans, start, this_chunk)) {
3372                         goto out;
3373                 }
3374
3375                 uint32_t n = 0;
3376                 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3377                         if ((*src)->write (buffers[n], this_chunk) != this_chunk) {
3378                                 goto out;
3379                         }
3380                 }
3381                 
3382                 start += this_chunk;
3383                 to_do -= this_chunk;
3384                 
3385                 itt.progress = (float) (1.0 - ((double) to_do / len));
3386
3387         }
3388
3389         if (!itt.cancel) {
3390                 
3391                 time_t now;
3392                 struct tm* xnow;
3393                 time (&now);
3394                 xnow = localtime (&now);
3395                 
3396                 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3397                         dynamic_cast<FileSource*>((*src))->update_header (position, *xnow, now);
3398                 }
3399                 
3400                 /* build peakfile for new source */
3401                 
3402                 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3403                         dynamic_cast<FileSource*>(*src)->build_peaks ();
3404                 }
3405                 
3406                 ret = 0;
3407         }
3408                 
3409   out:
3410         if (ret) {
3411                 for (vector<Source*>::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3412                         dynamic_cast<FileSource*>(*src)->mark_for_remove ();
3413                         delete *src;
3414                 }
3415         }
3416
3417         for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
3418                 free(*i);
3419         }
3420
3421         atomic_set (&processing_prohibited, 0);
3422
3423         itt.done = true;
3424
3425         return ret;
3426 }
3427
3428 vector<Sample*>&
3429 Session::get_silent_buffers (uint32_t howmany)
3430 {
3431         for (uint32_t i = 0; i < howmany; ++i) {
3432                 memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
3433         }
3434         return _silent_buffers;
3435 }
3436
3437 uint32_t 
3438 Session::ntracks () const
3439 {
3440         uint32_t n = 0;
3441         LockMonitor lm (route_lock, __LINE__, __FILE__);
3442
3443         for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3444                 if (dynamic_cast<AudioTrack*> (*i)) {
3445                         ++n;
3446                 }
3447         }
3448
3449         return n;
3450 }
3451
3452 uint32_t 
3453 Session::nbusses () const
3454 {
3455         uint32_t n = 0;
3456         LockMonitor lm (route_lock, __LINE__, __FILE__);
3457
3458         for (RouteList::const_iterator i = routes.begin(); i != routes.end(); ++i) {
3459                 if (dynamic_cast<AudioTrack*> (*i) == 0) {
3460                         ++n;
3461                 }
3462         }
3463
3464         return n;
3465 }
3466
3467 void
3468 Session::set_layer_model (LayerModel lm)
3469 {
3470         layer_model = lm;
3471         LayerModelChanged (); /* EMIT SIGNAL */
3472         set_dirty ();
3473 }
3474
3475 void
3476 Session::set_xfade_model (CrossfadeModel xm)
3477 {
3478         xfade_model = xm;
3479         set_dirty ();
3480 }
3481