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