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