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