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