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