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