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