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