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