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