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