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