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