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