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