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