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