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