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