use dynamic bitsets for send + port insert naming; fix up ardev, arval etc more gener...
[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
1619         /* count existing audio tracks */
1620
1621         {
1622                 shared_ptr<RouteList> r = routes.reader ();
1623
1624                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1625                         if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
1626                                 if (!(*i)->hidden()) {
1627                                         n++;
1628                                         channels_used += (*i)->n_inputs();
1629                                 }
1630                         }
1631                 }
1632         }
1633
1634         vector<string> physinputs;
1635         vector<string> physoutputs;
1636         uint32_t nphysical_in;
1637         uint32_t nphysical_out;
1638
1639         _engine.get_physical_outputs (physoutputs);
1640         _engine.get_physical_inputs (physinputs);
1641
1642         while (how_many) {
1643
1644                 /* check for duplicate route names, since we might have pre-existing
1645                    routes with this name (e.g. create Audio1, Audio2, delete Audio1,
1646                    save, close,restart,add new route - first named route is now
1647                    Audio2)
1648                 */
1649                 
1650
1651                 do {
1652                         ++track_id;
1653
1654                         snprintf (track_name, sizeof(track_name), "Audio %" PRIu32, track_id);
1655
1656                         if (route_by_name (track_name) == 0) {
1657                                 break;
1658                         }
1659                         
1660                 } while (track_id < (UINT_MAX-1));
1661
1662                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1663                         nphysical_in = min (n_physical_inputs, (uint32_t) physinputs.size());
1664                 } else {
1665                         nphysical_in = 0;
1666                 }
1667                 
1668                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1669                         nphysical_out = min (n_physical_outputs, (uint32_t) physinputs.size());
1670                 } else {
1671                         nphysical_out = 0;
1672                 }
1673                 
1674                 try {
1675                         shared_ptr<AudioTrack> track (new AudioTrack (*this, track_name, Route::Flag (0), mode));
1676                         
1677                         if (track->ensure_io (input_channels, output_channels, false, this)) {
1678                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1679                                                          input_channels, output_channels)
1680                                       << endmsg;
1681                         }
1682                         
1683                         if (nphysical_in) {
1684                                 for (uint32_t x = 0; x < track->n_inputs() && x < nphysical_in; ++x) {
1685                                         
1686                                         port = "";
1687                                         
1688                                         if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1689                                                 port = physinputs[(channels_used+x)%nphysical_in];
1690                                         } 
1691                                         
1692                                         if (port.length() && track->connect_input (track->input (x), port, this)) {
1693                                                 break;
1694                                         }
1695                                 }
1696                         }
1697                         
1698                         for (uint32_t x = 0; x < track->n_outputs(); ++x) {
1699                                 
1700                                 port = "";
1701                                 
1702                                 if (nphysical_out && (Config->get_output_auto_connect() & AutoConnectPhysical)) {
1703                                         port = physoutputs[(channels_used+x)%nphysical_out];
1704                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1705                                         if (_master_out) {
1706                                                 port = _master_out->input (x%_master_out->n_inputs())->name();
1707                                         }
1708                                 }
1709                                 
1710                                 if (port.length() && track->connect_output (track->output (x), port, this)) {
1711                                         break;
1712                                 }
1713                         }
1714                         
1715                         channels_used += track->n_inputs ();
1716
1717                         if (_control_out) {
1718                                 vector<string> cports;
1719                                 uint32_t ni = _control_out->n_inputs();
1720                                 
1721                                 for (n = 0; n < ni; ++n) {
1722                                         cports.push_back (_control_out->input(n)->name());
1723                                 }
1724                                 
1725                                 track->set_control_outs (cports);
1726                         }
1727                         
1728                         track->DiskstreamChanged.connect (mem_fun (this, &Session::resort_routes));
1729                         track->set_remote_control_id (ntracks());
1730
1731                         new_routes.push_back (track);
1732                         ret.push_back (track);
1733                 }
1734
1735                 catch (failed_constructor &err) {
1736                         error << _("Session: could not create new audio track.") << endmsg;
1737                         // XXX should we delete the tracks already created? 
1738                         ret.clear ();
1739                         return ret;
1740                 }
1741                 
1742                 --how_many;
1743         }
1744
1745         if (!new_routes.empty()) {
1746                 add_routes (new_routes, false);
1747                 save_state (_current_snapshot_name);
1748         }
1749
1750         return ret;
1751 }
1752
1753 Session::RouteList
1754 Session::new_audio_route (int input_channels, int output_channels, uint32_t how_many)
1755 {
1756         char bus_name[32];
1757         uint32_t bus_id = 1;
1758         uint32_t n = 0;
1759         string port;
1760         RouteList ret;
1761
1762         /* count existing audio busses */
1763
1764         {
1765                 shared_ptr<RouteList> r = routes.reader ();
1766
1767                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
1768                         if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
1769                                 if (!(*i)->hidden()) {
1770                                         bus_id++;
1771                                 }
1772                         }
1773                 }
1774         }
1775
1776         vector<string> physinputs;
1777         vector<string> physoutputs;
1778
1779         _engine.get_physical_outputs (physoutputs);
1780         _engine.get_physical_inputs (physinputs);
1781
1782         while (how_many) {
1783
1784                 do {
1785                         ++bus_id;
1786
1787                         snprintf (bus_name, sizeof(bus_name), "Bus %" PRIu32, bus_id);
1788
1789                         if (route_by_name (bus_name) == 0) {
1790                                 break;
1791                         }
1792
1793                 } while (bus_id < (UINT_MAX-1));
1794
1795                 try {
1796                         shared_ptr<Route> bus (new Route (*this, bus_name, -1, -1, -1, -1, Route::Flag(0), DataType::AUDIO));
1797                         
1798                         if (bus->ensure_io (input_channels, output_channels, false, this)) {
1799                                 error << string_compose (_("cannot configure %1 in/%2 out configuration for new audio track"),
1800                                                          input_channels, output_channels)
1801                                       << endmsg;
1802                         }
1803                         
1804                         for (uint32_t x = 0; n_physical_inputs && x < bus->n_inputs(); ++x) {
1805                                 
1806                                 port = "";
1807
1808                                 if (Config->get_input_auto_connect() & AutoConnectPhysical) {
1809                                                 port = physinputs[((n+x)%n_physical_inputs)];
1810                                 } 
1811                                 
1812                                 if (port.length() && bus->connect_input (bus->input (x), port, this)) {
1813                                         break;
1814                                 }
1815                         }
1816                         
1817                         for (uint32_t x = 0; n_physical_outputs && x < bus->n_outputs(); ++x) {
1818                                 
1819                                 port = "";
1820                                 
1821                                 if (Config->get_output_auto_connect() & AutoConnectPhysical) {
1822                                         port = physoutputs[((n+x)%n_physical_outputs)];
1823                                 } else if (Config->get_output_auto_connect() & AutoConnectMaster) {
1824                                         if (_master_out) {
1825                                                 port = _master_out->input (x%_master_out->n_inputs())->name();
1826                                         }
1827                                 }
1828                                 
1829                                 if (port.length() && bus->connect_output (bus->output (x), port, this)) {
1830                                         break;
1831                                 }
1832                         }
1833                         
1834                         if (_control_out) {
1835                                 vector<string> cports;
1836                                 uint32_t ni = _control_out->n_inputs();
1837                                 
1838                                 for (uint32_t n = 0; n < ni; ++n) {
1839                                         cports.push_back (_control_out->input(n)->name());
1840                                 }
1841                                 bus->set_control_outs (cports);
1842                         }
1843
1844                         ret.push_back (bus);
1845                 }
1846         
1847
1848                 catch (failed_constructor &err) {
1849                         error << _("Session: could not create new audio route.") << endmsg;
1850                         ret.clear ();
1851                         return ret;
1852                 }
1853
1854                 --how_many;
1855         }
1856
1857         if (!ret.empty()) {
1858                 add_routes (ret, false);
1859                 save_state (_current_snapshot_name);
1860         }
1861
1862         return ret;
1863
1864 }
1865
1866 void
1867 Session::add_routes (RouteList& new_routes, bool save)
1868 {
1869         { 
1870                 RCUWriter<RouteList> writer (routes);
1871                 shared_ptr<RouteList> r = writer.get_copy ();
1872                 r->insert (r->end(), new_routes.begin(), new_routes.end());
1873                 resort_routes_using (r);
1874         }
1875
1876         for (RouteList::iterator x = new_routes.begin(); x != new_routes.end(); ++x) {
1877                 
1878                 boost::weak_ptr<Route> wpr (*x);
1879
1880                 (*x)->solo_changed.connect (sigc::bind (mem_fun (*this, &Session::route_solo_changed), wpr));
1881                 (*x)->mute_changed.connect (mem_fun (*this, &Session::route_mute_changed));
1882                 (*x)->output_changed.connect (mem_fun (*this, &Session::set_worst_io_latencies_x));
1883                 (*x)->redirects_changed.connect (mem_fun (*this, &Session::update_latency_compensation_proxy));
1884                 
1885                 if ((*x)->master()) {
1886                         _master_out = (*x);
1887                 }
1888                 
1889                 if ((*x)->control()) {
1890                         _control_out = (*x);
1891                 }
1892         }
1893
1894         set_dirty();
1895
1896         if (save) {
1897                 save_state (_current_snapshot_name);
1898         }
1899
1900         RouteAdded (new_routes); /* EMIT SIGNAL */
1901 }
1902
1903 void
1904 Session::add_diskstream (boost::shared_ptr<Diskstream> dstream)
1905 {
1906         /* need to do this in case we're rolling at the time, to prevent false underruns */
1907         dstream->do_refill_with_alloc();
1908         
1909         { 
1910                 RCUWriter<DiskstreamList> writer (diskstreams);
1911                 boost::shared_ptr<DiskstreamList> ds = writer.get_copy();
1912                 ds->push_back (dstream);
1913         }
1914
1915         dstream->set_block_size (current_block_size);
1916
1917         dstream->PlaylistChanged.connect (sigc::bind (mem_fun (*this, &Session::diskstream_playlist_changed), dstream));
1918         /* this will connect to future changes, and check the current length */
1919         diskstream_playlist_changed (dstream);
1920
1921         dstream->prepare ();
1922 }
1923
1924 void
1925 Session::remove_route (shared_ptr<Route> route)
1926 {
1927         {       
1928                 RCUWriter<RouteList> writer (routes);
1929                 shared_ptr<RouteList> rs = writer.get_copy ();
1930                 
1931                 rs->remove (route);
1932
1933                 /* deleting the master out seems like a dumb
1934                    idea, but its more of a UI policy issue
1935                    than our concern.
1936                 */
1937
1938                 if (route == _master_out) {
1939                         _master_out = shared_ptr<Route> ();
1940                 }
1941
1942                 if (route == _control_out) {
1943                         _control_out = shared_ptr<Route> ();
1944
1945                         /* cancel control outs for all routes */
1946
1947                         vector<string> empty;
1948
1949                         for (RouteList::iterator r = rs->begin(); r != rs->end(); ++r) {
1950                                 (*r)->set_control_outs (empty);
1951                         }
1952                 }
1953
1954                 update_route_solo_state ();
1955                 
1956                 /* writer goes out of scope, forces route list update */
1957         }
1958
1959         // FIXME: audio specific
1960         AudioTrack* at;
1961         boost::shared_ptr<AudioDiskstream> ds;
1962         
1963         if ((at = dynamic_cast<AudioTrack*>(route.get())) != 0) {
1964                 ds = at->audio_diskstream();
1965         }
1966         
1967         if (ds) {
1968
1969                 {
1970                         RCUWriter<DiskstreamList> dsl (diskstreams);
1971                         boost::shared_ptr<DiskstreamList> d = dsl.get_copy();
1972                         d->remove (ds);
1973                 }
1974         }
1975
1976         find_current_end ();
1977         
1978         update_latency_compensation (false, false);
1979         set_dirty();
1980
1981         // We need to disconnect the routes inputs and outputs 
1982         route->disconnect_inputs(NULL);
1983         route->disconnect_outputs(NULL);
1984         
1985         /* get rid of it from the dead wood collection in the route list manager */
1986
1987         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
1988
1989         routes.flush ();
1990
1991         /* try to cause everyone to drop their references */
1992
1993         route->drop_references ();
1994
1995         /* save the new state of the world */
1996
1997         if (save_state (_current_snapshot_name)) {
1998                 save_history (_current_snapshot_name);
1999         }
2000 }       
2001
2002 void
2003 Session::route_mute_changed (void* src)
2004 {
2005         set_dirty ();
2006 }
2007
2008 void
2009 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2010 {      
2011         if (solo_update_disabled) {
2012                 // We know already
2013                 return;
2014         }
2015         
2016         bool is_track;
2017         boost::shared_ptr<Route> route = wpr.lock ();
2018
2019         if (!route) {
2020                 /* should not happen */
2021                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2022                 return;
2023         }
2024
2025         is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2026         
2027         shared_ptr<RouteList> r = routes.reader ();
2028
2029         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2030                 
2031                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2032                 
2033                 if (is_track) {
2034                         
2035                         /* don't mess with busses */
2036                         
2037                         if (dynamic_cast<AudioTrack*>((*i).get()) == 0) {
2038                                 continue;
2039                         }
2040                         
2041                 } else {
2042                         
2043                         /* don't mess with tracks */
2044                         
2045                         if (dynamic_cast<AudioTrack*>((*i).get()) != 0) {
2046                                 continue;
2047                         }
2048                 }
2049                 
2050                 if ((*i) != route &&
2051                     ((*i)->mix_group () == 0 ||
2052                      (*i)->mix_group () != route->mix_group () ||
2053                      !route->mix_group ()->is_active())) {
2054                         
2055                         if ((*i)->soloed()) {
2056                                 
2057                                 /* if its already soloed, and solo latching is enabled,
2058                                    then leave it as it is.
2059                                 */
2060                                 
2061                                 if (Config->get_solo_latched()) {
2062                                         continue;
2063                                 } 
2064                         }
2065                         
2066                         /* do it */
2067
2068                         solo_update_disabled = true;
2069                         (*i)->set_solo (false, src);
2070                         solo_update_disabled = false;
2071                 }
2072         }
2073         
2074         bool something_soloed = false;
2075         bool same_thing_soloed = false;
2076         bool signal = false;
2077
2078         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2079                 if ((*i)->soloed()) {
2080                         something_soloed = true;
2081                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2082                                 if (is_track) {
2083                                         same_thing_soloed = true;
2084                                         break;
2085                                 }
2086                         } else {
2087                                 if (!is_track) {
2088                                         same_thing_soloed = true;
2089                                         break;
2090                                 }
2091                         }
2092                         break;
2093                 }
2094         }
2095         
2096         if (something_soloed != currently_soloing) {
2097                 signal = true;
2098                 currently_soloing = something_soloed;
2099         }
2100         
2101         modify_solo_mute (is_track, same_thing_soloed);
2102
2103         if (signal) {
2104                 SoloActive (currently_soloing);
2105         }
2106
2107         set_dirty();
2108 }
2109
2110 void
2111 Session::update_route_solo_state ()
2112 {
2113         bool mute = false;
2114         bool is_track = false;
2115         bool signal = false;
2116
2117         /* caller must hold RouteLock */
2118
2119         /* this is where we actually implement solo by changing
2120            the solo mute setting of each track.
2121         */
2122         
2123         shared_ptr<RouteList> r = routes.reader ();
2124
2125         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2126                 if ((*i)->soloed()) {
2127                         mute = true;
2128                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2129                                 is_track = true;
2130                         }
2131                         break;
2132                 }
2133         }
2134
2135         if (mute != currently_soloing) {
2136                 signal = true;
2137                 currently_soloing = mute;
2138         }
2139
2140         if (!is_track && !mute) {
2141
2142                 /* nothing is soloed */
2143
2144                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2145                         (*i)->set_solo_mute (false);
2146                 }
2147                 
2148                 if (signal) {
2149                         SoloActive (false);
2150                 }
2151
2152                 return;
2153         }
2154
2155         modify_solo_mute (is_track, mute);
2156
2157         if (signal) {
2158                 SoloActive (currently_soloing);
2159         }
2160 }
2161
2162 void
2163 Session::modify_solo_mute (bool is_track, bool mute)
2164 {
2165         shared_ptr<RouteList> r = routes.reader ();
2166
2167         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2168                 
2169                 if (is_track) {
2170                         
2171                         /* only alter track solo mute */
2172                         
2173                         if (dynamic_cast<AudioTrack*>((*i).get())) {
2174                                 if ((*i)->soloed()) {
2175                                         (*i)->set_solo_mute (!mute);
2176                                 } else {
2177                                         (*i)->set_solo_mute (mute);
2178                                 }
2179                         }
2180
2181                 } else {
2182
2183                         /* only alter bus solo mute */
2184
2185                         if (!dynamic_cast<AudioTrack*>((*i).get())) {
2186
2187                                 if ((*i)->soloed()) {
2188
2189                                         (*i)->set_solo_mute (false);
2190
2191                                 } else {
2192
2193                                         /* don't mute master or control outs
2194                                            in response to another bus solo
2195                                         */
2196                                         
2197                                         if ((*i) != _master_out &&
2198                                             (*i) != _control_out) {
2199                                                 (*i)->set_solo_mute (mute);
2200                                         }
2201                                 }
2202                         }
2203
2204                 }
2205         }
2206 }       
2207
2208
2209 void
2210 Session::catch_up_on_solo ()
2211 {
2212         /* this is called after set_state() to catch the full solo
2213            state, which can't be correctly determined on a per-route
2214            basis, but needs the global overview that only the session
2215            has.
2216         */
2217         update_route_solo_state();
2218 }       
2219                 
2220 shared_ptr<Route>
2221 Session::route_by_name (string name)
2222 {
2223         shared_ptr<RouteList> r = routes.reader ();
2224
2225         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2226                 if ((*i)->name() == name) {
2227                         return *i;
2228                 }
2229         }
2230
2231         return shared_ptr<Route> ((Route*) 0);
2232 }
2233
2234 shared_ptr<Route>
2235 Session::route_by_id (PBD::ID id)
2236 {
2237         shared_ptr<RouteList> r = routes.reader ();
2238
2239         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2240                 if ((*i)->id() == id) {
2241                         return *i;
2242                 }
2243         }
2244
2245         return shared_ptr<Route> ((Route*) 0);
2246 }
2247
2248 shared_ptr<Route>
2249 Session::route_by_remote_id (uint32_t id)
2250 {
2251         shared_ptr<RouteList> r = routes.reader ();
2252
2253         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2254                 if ((*i)->remote_control_id() == id) {
2255                         return *i;
2256                 }
2257         }
2258
2259         return shared_ptr<Route> ((Route*) 0);
2260 }
2261
2262 void
2263 Session::find_current_end ()
2264 {
2265         if (_state_of_the_state & Loading) {
2266                 return;
2267         }
2268
2269         nframes_t max = get_maximum_extent ();
2270
2271         if (max > end_location->end()) {
2272                 end_location->set_end (max);
2273                 set_dirty();
2274                 DurationChanged(); /* EMIT SIGNAL */
2275         }
2276 }
2277
2278 nframes_t
2279 Session::get_maximum_extent () const
2280 {
2281         nframes_t max = 0;
2282         nframes_t me; 
2283
2284         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2285
2286         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2287                 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2288                 if ((me = pl->get_maximum_extent()) > max) {
2289                         max = me;
2290                 }
2291         }
2292
2293         return max;
2294 }
2295
2296 boost::shared_ptr<Diskstream>
2297 Session::diskstream_by_name (string name)
2298 {
2299         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2300
2301         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2302                 if ((*i)->name() == name) {
2303                         return *i;
2304                 }
2305         }
2306
2307         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2308 }
2309
2310 boost::shared_ptr<Diskstream>
2311 Session::diskstream_by_id (const PBD::ID& id)
2312 {
2313         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2314
2315         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2316                 if ((*i)->id() == id) {
2317                         return *i;
2318                 }
2319         }
2320
2321         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2322 }
2323
2324 /* AudioRegion management */
2325
2326 string
2327 Session::new_region_name (string old)
2328 {
2329         string::size_type last_period;
2330         uint32_t number;
2331         string::size_type len = old.length() + 64;
2332         char buf[len];
2333
2334         if ((last_period = old.find_last_of ('.')) == string::npos) {
2335                 
2336                 /* no period present - add one explicitly */
2337
2338                 old += '.';
2339                 last_period = old.length() - 1;
2340                 number = 0;
2341
2342         } else {
2343
2344                 number = atoi (old.substr (last_period+1).c_str());
2345
2346         }
2347
2348         while (number < (UINT_MAX-1)) {
2349
2350                 AudioRegionList::const_iterator i;
2351                 string sbuf;
2352
2353                 number++;
2354
2355                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2356                 sbuf = buf;
2357
2358                 for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2359                         if (i->second->name() == sbuf) {
2360                                 break;
2361                         }
2362                 }
2363                 
2364                 if (i == audio_regions.end()) {
2365                         break;
2366                 }
2367         }
2368
2369         if (number != (UINT_MAX-1)) {
2370                 return buf;
2371         } 
2372
2373         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2374         return old;
2375 }
2376
2377 int
2378 Session::region_name (string& result, string base, bool newlevel) const
2379 {
2380         char buf[16];
2381         string subbase;
2382
2383         if (base == "") {
2384                 
2385                 Glib::Mutex::Lock lm (region_lock);
2386
2387                 snprintf (buf, sizeof (buf), "%d", (int)audio_regions.size() + 1);
2388
2389                 
2390                 result = "region.";
2391                 result += buf;
2392
2393         } else {
2394
2395                 /* XXX this is going to be slow. optimize me later */
2396                 
2397                 if (newlevel) {
2398                         subbase = base;
2399                 } else {
2400                         string::size_type pos;
2401
2402                         pos = base.find_last_of ('.');
2403
2404                         /* pos may be npos, but then we just use entire base */
2405
2406                         subbase = base.substr (0, pos);
2407
2408                 }
2409
2410                 bool name_taken = true;
2411                 
2412                 {
2413                         Glib::Mutex::Lock lm (region_lock);
2414                         
2415                         for (int n = 1; n < 5000; ++n) {
2416                                 
2417                                 result = subbase;
2418                                 snprintf (buf, sizeof (buf), ".%d", n);
2419                                 result += buf;
2420                                 
2421                                 name_taken = false;
2422                                 
2423                                 for (AudioRegionList::const_iterator i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2424                                         if (i->second->name() == result) {
2425                                                 name_taken = true;
2426                                                 break;
2427                                         }
2428                                 }
2429                                 
2430                                 if (!name_taken) {
2431                                         break;
2432                                 }
2433                         }
2434                 }
2435                         
2436                 if (name_taken) {
2437                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2438                         /*NOTREACHED*/
2439                 }
2440         }
2441         return 0;
2442 }       
2443
2444 void
2445 Session::add_region (boost::shared_ptr<Region> region)
2446 {
2447         boost::shared_ptr<AudioRegion> ar;
2448         boost::shared_ptr<AudioRegion> oar;
2449         bool added = false;
2450
2451         { 
2452                 Glib::Mutex::Lock lm (region_lock);
2453
2454                 if ((ar = boost::dynamic_pointer_cast<AudioRegion> (region)) != 0) {
2455
2456                         AudioRegionList::iterator x;
2457
2458                         for (x = audio_regions.begin(); x != audio_regions.end(); ++x) {
2459
2460                                 oar = boost::dynamic_pointer_cast<AudioRegion> (x->second);
2461
2462                                 if (ar->region_list_equivalent (oar)) {
2463                                         break;
2464                                 }
2465                         }
2466
2467                         if (x == audio_regions.end()) {
2468
2469                                 pair<AudioRegionList::key_type,AudioRegionList::mapped_type> entry;
2470
2471                                 entry.first = region->id();
2472                                 entry.second = ar;
2473
2474                                 pair<AudioRegionList::iterator,bool> x = audio_regions.insert (entry);
2475
2476                                 
2477                                 if (!x.second) {
2478                                         return;
2479                                 }
2480
2481                                 added = true;
2482                         } 
2483
2484                 } else {
2485
2486                         fatal << _("programming error: ")
2487                               << X_("unknown region type passed to Session::add_region()")
2488                               << endmsg;
2489                         /*NOTREACHED*/
2490
2491                 }
2492         }
2493
2494         /* mark dirty because something has changed even if we didn't
2495            add the region to the region list.
2496         */
2497         
2498         set_dirty();
2499         
2500         if (added) {
2501                 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2502                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2503                 AudioRegionAdded (ar); /* EMIT SIGNAL */
2504         }
2505 }
2506
2507 void
2508 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2509 {
2510         boost::shared_ptr<Region> region (weak_region.lock ());
2511
2512         if (!region) {
2513                 return;
2514         }
2515
2516         if (what_changed & Region::HiddenChanged) {
2517                 /* relay hidden changes */
2518                 RegionHiddenChange (region);
2519         }
2520 }
2521
2522 void
2523 Session::remove_region (boost::weak_ptr<Region> weak_region)
2524 {
2525         AudioRegionList::iterator i;
2526         boost::shared_ptr<Region> region (weak_region.lock ());
2527
2528         if (!region) {
2529                 return;
2530         }
2531
2532         boost::shared_ptr<AudioRegion> ar;
2533         bool removed = false;
2534
2535         { 
2536                 Glib::Mutex::Lock lm (region_lock);
2537
2538                 if ((ar = boost::dynamic_pointer_cast<AudioRegion> (region)) != 0) {
2539                         if ((i = audio_regions.find (region->id())) != audio_regions.end()) {
2540                                 audio_regions.erase (i);
2541                                 removed = true;
2542                         }
2543
2544                 } else {
2545
2546                         fatal << _("programming error: ") 
2547                               << X_("unknown region type passed to Session::remove_region()")
2548                               << endmsg;
2549                         /*NOTREACHED*/
2550                 }
2551         }
2552
2553         /* mark dirty because something has changed even if we didn't
2554            remove the region from the region list.
2555         */
2556
2557         set_dirty();
2558
2559         if (removed) {
2560                 AudioRegionRemoved (ar); /* EMIT SIGNAL */
2561         }
2562 }
2563
2564 boost::shared_ptr<AudioRegion>
2565 Session::find_whole_file_parent (boost::shared_ptr<AudioRegion const> child)
2566 {
2567         AudioRegionList::iterator i;
2568         boost::shared_ptr<AudioRegion> region;
2569         Glib::Mutex::Lock lm (region_lock);
2570
2571         for (i = audio_regions.begin(); i != audio_regions.end(); ++i) {
2572
2573                 region = i->second;
2574
2575                 if (region->whole_file()) {
2576
2577                         if (child->source_equivalent (region)) {
2578                                 return region;
2579                         }
2580                 }
2581         } 
2582
2583         return boost::shared_ptr<AudioRegion> ();
2584 }       
2585
2586 void
2587 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2588 {
2589         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2590                 (*i)->get_region_list_equivalent_regions (region, result);
2591 }
2592
2593 int
2594 Session::destroy_region (boost::shared_ptr<Region> region)
2595 {
2596         vector<boost::shared_ptr<Source> > srcs;
2597                 
2598         {
2599                 boost::shared_ptr<AudioRegion> aregion;
2600                 
2601                 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2602                         return 0;
2603                 }
2604                 
2605                 if (aregion->playlist()) {
2606                         aregion->playlist()->destroy_region (region);
2607                 }
2608                 
2609                 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2610                         srcs.push_back (aregion->source (n));
2611                 }
2612         }
2613
2614         region->drop_references ();
2615
2616         for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2617
2618                 if (!(*i)->used()) {
2619                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2620                         
2621                         if (afs) {
2622                                 (afs)->mark_for_remove ();
2623                         }
2624                         
2625                         (*i)->drop_references ();
2626                         
2627                         cerr << "source was not used by any playlist\n";
2628                 }
2629         }
2630
2631         return 0;
2632 }
2633
2634 int
2635 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2636 {
2637         for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2638                 destroy_region (*i);
2639         }
2640         return 0;
2641 }
2642
2643 int
2644 Session::remove_last_capture ()
2645 {
2646         list<boost::shared_ptr<Region> > r;
2647         
2648         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2649         
2650         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2651                 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2652                 
2653                 if (!l.empty()) {
2654                         r.insert (r.end(), l.begin(), l.end());
2655                         l.clear ();
2656                 }
2657         }
2658
2659         destroy_regions (r);
2660         return 0;
2661 }
2662
2663 int
2664 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2665 {
2666         remove_region (r);
2667         return 0;
2668 }
2669
2670 /* Source Management */
2671
2672 void
2673 Session::add_source (boost::shared_ptr<Source> source)
2674 {
2675         boost::shared_ptr<AudioFileSource> afs;
2676
2677         if ((afs = boost::dynamic_pointer_cast<AudioFileSource>(source)) != 0) {
2678
2679                 pair<AudioSourceList::key_type, AudioSourceList::mapped_type> entry;
2680                 pair<AudioSourceList::iterator,bool> result;
2681
2682                 entry.first = source->id();
2683                 entry.second = afs;
2684                 
2685                 {
2686                         Glib::Mutex::Lock lm (audio_source_lock);
2687                         result = audio_sources.insert (entry);
2688                 }
2689
2690                 if (result.second) {
2691                         source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2692                         set_dirty();
2693                 }
2694
2695         } 
2696 }
2697
2698 void
2699 Session::remove_source (boost::weak_ptr<Source> src)
2700 {
2701         AudioSourceList::iterator i;
2702         boost::shared_ptr<Source> source = src.lock();
2703
2704         if (!source) {
2705                 return;
2706         } 
2707
2708         { 
2709                 Glib::Mutex::Lock lm (audio_source_lock);
2710                 
2711                 if ((i = audio_sources.find (source->id())) != audio_sources.end()) {
2712                         audio_sources.erase (i);
2713                 } 
2714         }
2715         
2716         if (!_state_of_the_state & InCleanup) {
2717                 
2718                 /* save state so we don't end up with a session file
2719                    referring to non-existent sources.
2720                 */
2721                 
2722                 save_state (_current_snapshot_name);
2723         }
2724 }
2725
2726 boost::shared_ptr<Source>
2727 Session::source_by_id (const PBD::ID& id)
2728 {
2729         Glib::Mutex::Lock lm (audio_source_lock);
2730         AudioSourceList::iterator i;
2731         boost::shared_ptr<Source> source;
2732
2733         if ((i = audio_sources.find (id)) != audio_sources.end()) {
2734                 source = i->second;
2735         }
2736
2737         /* XXX search MIDI or other searches here */
2738         
2739         return source;
2740 }
2741
2742 string
2743 Session::peak_path_from_audio_path (string audio_path) const
2744 {
2745         string res;
2746
2747         res = peak_dir ();
2748         res += PBD::basename_nosuffix (audio_path);
2749         res += ".peak";
2750
2751         return res;
2752 }
2753
2754 string
2755 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2756 {
2757         string look_for;
2758         string old_basename = PBD::basename_nosuffix (oldname);
2759         string new_legalized = legalize_for_path (newname);
2760
2761         /* note: we know (or assume) the old path is already valid */
2762
2763         if (destructive) {
2764                 
2765                 /* destructive file sources have a name of the form:
2766
2767                     /path/to/Tnnnn-NAME(%[LR])?.wav
2768                   
2769                     the task here is to replace NAME with the new name.
2770                 */
2771                 
2772                 /* find last slash */
2773
2774                 string dir;
2775                 string prefix;
2776                 string::size_type slash;
2777                 string::size_type dash;
2778
2779                 if ((slash = path.find_last_of ('/')) == string::npos) {
2780                         return "";
2781                 }
2782
2783                 dir = path.substr (0, slash+1);
2784
2785                 /* '-' is not a legal character for the NAME part of the path */
2786
2787                 if ((dash = path.find_last_of ('-')) == string::npos) {
2788                         return "";
2789                 }
2790
2791                 prefix = path.substr (slash+1, dash-(slash+1));
2792
2793                 path = dir;
2794                 path += prefix;
2795                 path += '-';
2796                 path += new_legalized;
2797                 path += ".wav";  /* XXX gag me with a spoon */
2798                 
2799         } else {
2800                 
2801                 /* non-destructive file sources have a name of the form:
2802
2803                     /path/to/NAME-nnnnn(%[LR])?.wav
2804                   
2805                     the task here is to replace NAME with the new name.
2806                 */
2807                 
2808                 string dir;
2809                 string suffix;
2810                 string::size_type slash;
2811                 string::size_type dash;
2812                 string::size_type postfix;
2813
2814                 /* find last slash */
2815
2816                 if ((slash = path.find_last_of ('/')) == string::npos) {
2817                         return "";
2818                 }
2819
2820                 dir = path.substr (0, slash+1);
2821
2822                 /* '-' is not a legal character for the NAME part of the path */
2823
2824                 if ((dash = path.find_last_of ('-')) == string::npos) {
2825                         return "";
2826                 }
2827
2828                 suffix = path.substr (dash+1);
2829                 
2830                 // Suffix is now everything after the dash. Now we need to eliminate
2831                 // the nnnnn part, which is done by either finding a '%' or a '.'
2832
2833                 postfix = suffix.find_last_of ("%");
2834                 if (postfix == string::npos) {
2835                         postfix = suffix.find_last_of ('.');
2836                 }
2837
2838                 if (postfix != string::npos) {
2839                         suffix = suffix.substr (postfix);
2840                 } else {
2841                         error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2842                         return "";
2843                 }
2844
2845                 const uint32_t limit = 10000;
2846                 char buf[PATH_MAX+1];
2847
2848                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2849
2850                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2851
2852                         if (access (buf, F_OK) != 0) {
2853                                 path = buf;
2854                                 break;
2855                         }
2856                         path = "";
2857                 }
2858
2859                 if (path == "") {
2860                         error << "FATAL ERROR! Could not find a " << endl;
2861                 }
2862
2863         }
2864
2865         return path;
2866 }
2867
2868 string
2869 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2870 {
2871         string spath;
2872         uint32_t cnt;
2873         char buf[PATH_MAX+1];
2874         const uint32_t limit = 10000;
2875         string legalized;
2876
2877         buf[0] = '\0';
2878         legalized = legalize_for_path (name);
2879
2880         /* find a "version" of the file name that doesn't exist in
2881            any of the possible directories.
2882         */
2883
2884         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2885
2886                 vector<space_and_path>::iterator i;
2887                 uint32_t existing = 0;
2888
2889                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2890
2891                         spath = (*i).path;
2892
2893                         spath += sound_dir (false);
2894
2895                         if (destructive) {
2896                                 if (nchan < 2) {
2897                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2898                                 } else if (nchan == 2) {
2899                                         if (chan == 0) {
2900                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
2901                                         } else {
2902                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
2903                                         }
2904                                 } else if (nchan < 26) {
2905                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
2906                                 } else {
2907                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
2908                                 }
2909
2910                         } else {
2911
2912                                 spath += '/';
2913                                 spath += legalized;
2914
2915                                 if (nchan < 2) {
2916                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2917                                 } else if (nchan == 2) {
2918                                         if (chan == 0) {
2919                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
2920                                         } else {
2921                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
2922                                         }
2923                                 } else if (nchan < 26) {
2924                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
2925                                 } else {
2926                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
2927                                 }
2928                         }
2929
2930                         if (g_file_test (buf, G_FILE_TEST_EXISTS)) {
2931                                 existing++;
2932                         } 
2933
2934                 }
2935
2936                 if (existing == 0) {
2937                         break;
2938                 }
2939
2940                 if (cnt > limit) {
2941                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
2942                         destroy ();
2943                         throw failed_constructor();
2944                 }
2945         }
2946
2947         /* we now have a unique name for the file, but figure out where to
2948            actually put it.
2949         */
2950
2951         string foo = buf;
2952
2953         spath = discover_best_sound_dir ();
2954         spath += '/';
2955
2956         string::size_type pos = foo.find_last_of ('/');
2957         
2958         if (pos == string::npos) {
2959                 spath += foo;
2960         } else {
2961                 spath += foo.substr (pos + 1);
2962         }
2963
2964         return spath;
2965 }
2966
2967 boost::shared_ptr<AudioFileSource>
2968 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
2969 {
2970         string spath = audio_path_from_name (ds.name(), ds.n_channels(), chan, destructive);
2971         return boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, spath, destructive, frame_rate()));
2972 }
2973
2974 /* Playlist management */
2975
2976 boost::shared_ptr<Playlist>
2977 Session::playlist_by_name (string name)
2978 {
2979         Glib::Mutex::Lock lm (playlist_lock);
2980         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2981                 if ((*i)->name() == name) {
2982                         return* i;
2983                 }
2984         }
2985         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
2986                 if ((*i)->name() == name) {
2987                         return* i;
2988                 }
2989         }
2990
2991         return boost::shared_ptr<Playlist>();
2992 }
2993
2994 void
2995 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
2996 {
2997         if (playlist->hidden()) {
2998                 return;
2999         }
3000
3001         { 
3002                 Glib::Mutex::Lock lm (playlist_lock);
3003                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3004                         playlists.insert (playlists.begin(), playlist);
3005                         playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3006                         playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3007                 }
3008         }
3009
3010         set_dirty();
3011
3012         PlaylistAdded (playlist); /* EMIT SIGNAL */
3013 }
3014
3015 void
3016 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3017 {
3018         { 
3019                 Glib::Mutex::Lock lm (playlist_lock);
3020                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3021                         s.push_back (*i);
3022                 }
3023                 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3024                         s.push_back (*i);
3025                 }
3026         }
3027 }
3028
3029 void
3030 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3031 {
3032         boost::shared_ptr<Playlist> pl(wpl.lock());
3033
3034         if (!pl) {
3035                 return;
3036         }
3037
3038         PlaylistList::iterator x;
3039
3040         if (pl->hidden()) {
3041                 /* its not supposed to be visible */
3042                 return;
3043         }
3044
3045         { 
3046                 Glib::Mutex::Lock lm (playlist_lock);
3047
3048                 if (!inuse) {
3049
3050                         unused_playlists.insert (pl);
3051                         
3052                         if ((x = playlists.find (pl)) != playlists.end()) {
3053                                 playlists.erase (x);
3054                         }
3055
3056                         
3057                 } else {
3058
3059                         playlists.insert (pl);
3060                         
3061                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3062                                 unused_playlists.erase (x);
3063                         }
3064                 }
3065         }
3066 }
3067
3068 void
3069 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3070 {
3071         if (_state_of_the_state & Deletion) {
3072                 return;
3073         }
3074
3075         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3076
3077         if (!playlist) {
3078                 return;
3079         }
3080
3081         { 
3082                 Glib::Mutex::Lock lm (playlist_lock);
3083                 cerr << "removing playlist: " << playlist->name() << endl;
3084
3085                 PlaylistList::iterator i;
3086
3087                 i = find (playlists.begin(), playlists.end(), playlist);
3088                 if (i != playlists.end()) {
3089                         cerr << "\tfound it in used playlist\n";
3090                         playlists.erase (i);
3091                 }
3092
3093                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3094                 if (i != unused_playlists.end()) {
3095                         cerr << "\tfound it in unused playlist\n";
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 int
3644 Session::cleanup_audio_file_source (boost::shared_ptr<AudioFileSource> fs)
3645 {
3646         return fs->move_to_trash (dead_sound_dir_name);
3647 }
3648
3649 uint32_t
3650 Session::n_playlists () const
3651 {
3652         Glib::Mutex::Lock lm (playlist_lock);
3653         return playlists.size();
3654 }
3655
3656 void
3657 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3658 {
3659         if (!force && howmany <= _npan_buffers) {
3660                 return;
3661         }
3662
3663         if (_pan_automation_buffer) {
3664
3665                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3666                         delete [] _pan_automation_buffer[i];
3667                 }
3668
3669                 delete [] _pan_automation_buffer;
3670         }
3671
3672         _pan_automation_buffer = new pan_t*[howmany];
3673         
3674         for (uint32_t i = 0; i < howmany; ++i) {
3675                 _pan_automation_buffer[i] = new pan_t[nframes];
3676         }
3677
3678         _npan_buffers = howmany;
3679 }
3680
3681 int
3682 Session::freeze (InterThreadInfo& itt)
3683 {
3684         shared_ptr<RouteList> r = routes.reader ();
3685
3686         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3687
3688                 AudioTrack *at;
3689
3690                 if ((at = dynamic_cast<AudioTrack*>((*i).get())) != 0) {
3691                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3692                            of every track.
3693                         */
3694                         at->freeze (itt);
3695                 }
3696         }
3697
3698         return 0;
3699 }
3700
3701 int
3702 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,      
3703                                bool overwrite, vector<boost::shared_ptr<AudioSource> >& srcs, InterThreadInfo& itt)
3704 {
3705         int ret = -1;
3706         boost::shared_ptr<Playlist> playlist;
3707         boost::shared_ptr<AudioFileSource> fsource;
3708         uint32_t x;
3709         char buf[PATH_MAX+1];
3710         string dir;
3711         uint32_t nchans;
3712         nframes_t position;
3713         nframes_t this_chunk;
3714         nframes_t to_do;
3715         vector<Sample*> buffers;
3716
3717         // any bigger than this seems to cause stack overflows in called functions
3718         const nframes_t chunk_size = (128 * 1024)/4;
3719
3720         g_atomic_int_set (&processing_prohibited, 1);
3721         
3722         /* call tree *MUST* hold route_lock */
3723         
3724         if ((playlist = track.diskstream()->playlist()) == 0) {
3725                 goto out;
3726         }
3727
3728         /* external redirects will be a problem */
3729
3730         if (track.has_external_redirects()) {
3731                 goto out;
3732         }
3733
3734         nchans = track.audio_diskstream()->n_channels();
3735         
3736         dir = discover_best_sound_dir ();
3737
3738         for (uint32_t chan_n=0; chan_n < nchans; ++chan_n) {
3739
3740                 for (x = 0; x < 99999; ++x) {
3741                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", dir.c_str(), playlist->name().c_str(), chan_n, x+1);
3742                         if (access (buf, F_OK) != 0) {
3743                                 break;
3744                         }
3745                 }
3746                 
3747                 if (x == 99999) {
3748                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
3749                         goto out;
3750                 }
3751                 
3752                 try {
3753                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createWritable (*this, buf, false, frame_rate()));
3754                 }
3755                 
3756                 catch (failed_constructor& err) {
3757                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
3758                         goto out;
3759                 }
3760
3761                 srcs.push_back (fsource);
3762         }
3763
3764         /* XXX need to flush all redirects */
3765         
3766         position = start;
3767         to_do = len;
3768
3769         /* create a set of reasonably-sized buffers */
3770
3771         for (vector<Sample*>::iterator i = _passthru_buffers.begin(); i != _passthru_buffers.end(); ++i) {
3772                 Sample* b;
3773 #ifdef NO_POSIX_MEMALIGN
3774                 b =  (Sample *) malloc(chunk_size * sizeof(Sample));
3775 #else
3776                 posix_memalign((void **)&b,16,chunk_size * 4);
3777 #endif                  
3778                 buffers.push_back (b);
3779         }
3780
3781         while (to_do && !itt.cancel) {
3782                 
3783                 this_chunk = min (to_do, chunk_size);
3784                 
3785                 if (track.export_stuff (buffers, nchans, start, this_chunk)) {
3786                         goto out;
3787                 }
3788
3789                 uint32_t n = 0;
3790                 for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
3791                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3792                         
3793                         if (afs) {
3794                                 if (afs->write (buffers[n], this_chunk) != this_chunk) {
3795                                         goto out;
3796                                 }
3797                         }
3798                 }
3799                 
3800                 start += this_chunk;
3801                 to_do -= this_chunk;
3802                 
3803                 itt.progress = (float) (1.0 - ((double) to_do / len));
3804
3805         }
3806
3807         if (!itt.cancel) {
3808                 
3809                 time_t now;
3810                 struct tm* xnow;
3811                 time (&now);
3812                 xnow = localtime (&now);
3813                 
3814                 for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3815                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3816
3817                         if (afs) {
3818                                 afs->update_header (position, *xnow, now);
3819                         }
3820                 }
3821                 
3822                 /* build peakfile for new source */
3823                 
3824                 for (vector<boost::shared_ptr<AudioSource> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
3825                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3826                         if (afs) {
3827                                 afs->build_peaks ();
3828                         }
3829                 }
3830
3831                 /* construct a region to represent the bounced material */
3832
3833                 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(), 
3834                                                                            region_name_from_path (srcs.front()->name(), true));
3835
3836                 ret = 0;
3837         }
3838                 
3839   out:
3840         if (ret) {
3841                 for (vector<boost::shared_ptr<AudioSource> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
3842                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
3843
3844                         if (afs) {
3845                                 afs->mark_for_remove ();
3846                         }
3847
3848                         (*src)->drop_references ();
3849                 }
3850         }
3851
3852         for (vector<Sample*>::iterator i = buffers.begin(); i != buffers.end(); ++i) {
3853                 free(*i);
3854         }
3855
3856         g_atomic_int_set (&processing_prohibited, 0);
3857
3858         itt.done = true;
3859
3860         return ret;
3861 }
3862
3863 vector<Sample*>&
3864 Session::get_silent_buffers (uint32_t howmany)
3865 {
3866         for (uint32_t i = 0; i < howmany; ++i) {
3867                 memset (_silent_buffers[i], 0, sizeof (Sample) * current_block_size);
3868         }
3869         return _silent_buffers;
3870 }
3871
3872 uint32_t 
3873 Session::ntracks () const
3874 {
3875         uint32_t n = 0;
3876         shared_ptr<RouteList> r = routes.reader ();
3877
3878         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3879                 if (dynamic_cast<AudioTrack*> ((*i).get())) {
3880                         ++n;
3881                 }
3882         }
3883
3884         return n;
3885 }
3886
3887 uint32_t 
3888 Session::nbusses () const
3889 {
3890         uint32_t n = 0;
3891         shared_ptr<RouteList> r = routes.reader ();
3892
3893         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3894                 if (dynamic_cast<AudioTrack*> ((*i).get()) == 0) {
3895                         ++n;
3896                 }
3897         }
3898
3899         return n;
3900 }
3901
3902 void
3903 Session::add_automation_list(AutomationList *al)
3904 {
3905         automation_lists[al->id()] = al;
3906 }
3907
3908 nframes_t
3909 Session::compute_initial_length ()
3910 {
3911         return _engine.frame_rate() * 60 * 5;
3912 }
3913