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