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