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