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