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