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