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