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