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