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