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