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