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