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