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