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