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