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