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