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