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