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