1382fa3f0aefe748281396120a4a98b6d981ea45
[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         // We need to disconnect the routes inputs and outputs 
2093
2094         route->disconnect_inputs (0);
2095         route->disconnect_outputs (0);
2096         
2097         update_latency_compensation (false, false);
2098         set_dirty();
2099
2100         /* get rid of it from the dead wood collection in the route list manager */
2101
2102         /* XXX i think this is unsafe as it currently stands, but i am not sure. (pd, october 2nd, 2006) */
2103
2104         routes.flush ();
2105
2106         /* try to cause everyone to drop their references */
2107
2108         route->drop_references ();
2109
2110         /* save the new state of the world */
2111
2112         if (save_state (_current_snapshot_name)) {
2113                 save_history (_current_snapshot_name);
2114         }
2115 }       
2116
2117 void
2118 Session::route_mute_changed (void* src)
2119 {
2120         set_dirty ();
2121 }
2122
2123 void
2124 Session::route_solo_changed (void* src, boost::weak_ptr<Route> wpr)
2125 {      
2126         if (solo_update_disabled) {
2127                 // We know already
2128                 return;
2129         }
2130         
2131         bool is_track;
2132         boost::shared_ptr<Route> route = wpr.lock ();
2133
2134         if (!route) {
2135                 /* should not happen */
2136                 error << string_compose (_("programming error: %1"), X_("invalid route weak ptr passed to route_solo_changed")) << endmsg;
2137                 return;
2138         }
2139
2140         is_track = (boost::dynamic_pointer_cast<AudioTrack>(route) != 0);
2141         
2142         shared_ptr<RouteList> r = routes.reader ();
2143
2144         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2145                 
2146                 /* soloing a track mutes all other tracks, soloing a bus mutes all other busses */
2147                 
2148                 if (is_track) {
2149                         
2150                         /* don't mess with busses */
2151                         
2152                         if (dynamic_cast<Track*>((*i).get()) == 0) {
2153                                 continue;
2154                         }
2155                         
2156                 } else {
2157                         
2158                         /* don't mess with tracks */
2159                         
2160                         if (dynamic_cast<Track*>((*i).get()) != 0) {
2161                                 continue;
2162                         }
2163                 }
2164                 
2165                 if ((*i) != route &&
2166                     ((*i)->mix_group () == 0 ||
2167                      (*i)->mix_group () != route->mix_group () ||
2168                      !route->mix_group ()->is_active())) {
2169                         
2170                         if ((*i)->soloed()) {
2171                                 
2172                                 /* if its already soloed, and solo latching is enabled,
2173                                    then leave it as it is.
2174                                 */
2175                                 
2176                                 if (Config->get_solo_latched()) {
2177                                         continue;
2178                                 } 
2179                         }
2180                         
2181                         /* do it */
2182
2183                         solo_update_disabled = true;
2184                         (*i)->set_solo (false, src);
2185                         solo_update_disabled = false;
2186                 }
2187         }
2188         
2189         bool something_soloed = false;
2190         bool same_thing_soloed = false;
2191         bool signal = false;
2192
2193         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2194                 if ((*i)->soloed()) {
2195                         something_soloed = true;
2196                         if (dynamic_cast<Track*>((*i).get())) {
2197                                 if (is_track) {
2198                                         same_thing_soloed = true;
2199                                         break;
2200                                 }
2201                         } else {
2202                                 if (!is_track) {
2203                                         same_thing_soloed = true;
2204                                         break;
2205                                 }
2206                         }
2207                         break;
2208                 }
2209         }
2210         
2211         if (something_soloed != currently_soloing) {
2212                 signal = true;
2213                 currently_soloing = something_soloed;
2214         }
2215         
2216         modify_solo_mute (is_track, same_thing_soloed);
2217
2218         if (signal) {
2219                 SoloActive (currently_soloing); /* EMIT SIGNAL */
2220         }
2221
2222         SoloChanged (); /* EMIT SIGNAL */
2223
2224         set_dirty();
2225 }
2226
2227 void
2228 Session::update_route_solo_state ()
2229 {
2230         bool mute = false;
2231         bool is_track = false;
2232         bool signal = false;
2233
2234         /* caller must hold RouteLock */
2235
2236         /* this is where we actually implement solo by changing
2237            the solo mute setting of each track.
2238         */
2239         
2240         shared_ptr<RouteList> r = routes.reader ();
2241
2242         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2243                 if ((*i)->soloed()) {
2244                         mute = true;
2245                         if (dynamic_cast<Track*>((*i).get())) {
2246                                 is_track = true;
2247                         }
2248                         break;
2249                 }
2250         }
2251
2252         if (mute != currently_soloing) {
2253                 signal = true;
2254                 currently_soloing = mute;
2255         }
2256
2257         if (!is_track && !mute) {
2258
2259                 /* nothing is soloed */
2260
2261                 for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2262                         (*i)->set_solo_mute (false);
2263                 }
2264                 
2265                 if (signal) {
2266                         SoloActive (false);
2267                 }
2268
2269                 return;
2270         }
2271
2272         modify_solo_mute (is_track, mute);
2273
2274         if (signal) {
2275                 SoloActive (currently_soloing);
2276         }
2277 }
2278
2279 void
2280 Session::modify_solo_mute (bool is_track, bool mute)
2281 {
2282         shared_ptr<RouteList> r = routes.reader ();
2283
2284         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2285                 
2286                 if (is_track) {
2287                         
2288                         /* only alter track solo mute */
2289                         
2290                         if (dynamic_cast<Track*>((*i).get())) {
2291                                 if ((*i)->soloed()) {
2292                                         (*i)->set_solo_mute (!mute);
2293                                 } else {
2294                                         (*i)->set_solo_mute (mute);
2295                                 }
2296                         }
2297
2298                 } else {
2299
2300                         /* only alter bus solo mute */
2301
2302                         if (!dynamic_cast<Track*>((*i).get())) {
2303
2304                                 if ((*i)->soloed()) {
2305
2306                                         (*i)->set_solo_mute (false);
2307
2308                                 } else {
2309
2310                                         /* don't mute master or control outs
2311                                            in response to another bus solo
2312                                         */
2313                                         
2314                                         if ((*i) != _master_out &&
2315                                             (*i) != _control_out) {
2316                                                 (*i)->set_solo_mute (mute);
2317                                         }
2318                                 }
2319                         }
2320
2321                 }
2322         }
2323 }       
2324
2325
2326 void
2327 Session::catch_up_on_solo ()
2328 {
2329         /* this is called after set_state() to catch the full solo
2330            state, which can't be correctly determined on a per-route
2331            basis, but needs the global overview that only the session
2332            has.
2333         */
2334         update_route_solo_state();
2335 }       
2336                 
2337 shared_ptr<Route>
2338 Session::route_by_name (string name)
2339 {
2340         shared_ptr<RouteList> r = routes.reader ();
2341
2342         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2343                 if ((*i)->name() == name) {
2344                         return *i;
2345                 }
2346         }
2347
2348         return shared_ptr<Route> ((Route*) 0);
2349 }
2350
2351 shared_ptr<Route>
2352 Session::route_by_id (PBD::ID id)
2353 {
2354         shared_ptr<RouteList> r = routes.reader ();
2355
2356         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2357                 if ((*i)->id() == id) {
2358                         return *i;
2359                 }
2360         }
2361
2362         return shared_ptr<Route> ((Route*) 0);
2363 }
2364
2365 shared_ptr<Route>
2366 Session::route_by_remote_id (uint32_t id)
2367 {
2368         shared_ptr<RouteList> r = routes.reader ();
2369
2370         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2371                 if ((*i)->remote_control_id() == id) {
2372                         return *i;
2373                 }
2374         }
2375
2376         return shared_ptr<Route> ((Route*) 0);
2377 }
2378
2379 void
2380 Session::find_current_end ()
2381 {
2382         if (_state_of_the_state & Loading) {
2383                 return;
2384         }
2385
2386         nframes_t max = get_maximum_extent ();
2387
2388         if (max > end_location->end()) {
2389                 end_location->set_end (max);
2390                 set_dirty();
2391                 DurationChanged(); /* EMIT SIGNAL */
2392         }
2393 }
2394
2395 nframes_t
2396 Session::get_maximum_extent () const
2397 {
2398         nframes_t max = 0;
2399         nframes_t me; 
2400
2401         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2402
2403         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
2404                 boost::shared_ptr<Playlist> pl = (*i)->playlist();
2405                 if ((me = pl->get_maximum_extent()) > max) {
2406                         max = me;
2407                 }
2408         }
2409
2410         return max;
2411 }
2412
2413 boost::shared_ptr<Diskstream>
2414 Session::diskstream_by_name (string name)
2415 {
2416         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2417
2418         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2419                 if ((*i)->name() == name) {
2420                         return *i;
2421                 }
2422         }
2423
2424         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2425 }
2426
2427 boost::shared_ptr<Diskstream>
2428 Session::diskstream_by_id (const PBD::ID& id)
2429 {
2430         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2431
2432         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2433                 if ((*i)->id() == id) {
2434                         return *i;
2435                 }
2436         }
2437
2438         return boost::shared_ptr<Diskstream>((Diskstream*) 0);
2439 }
2440
2441 /* Region management */
2442
2443 string
2444 Session::new_region_name (string old)
2445 {
2446         string::size_type last_period;
2447         uint32_t number;
2448         string::size_type len = old.length() + 64;
2449         char buf[len];
2450
2451         if ((last_period = old.find_last_of ('.')) == string::npos) {
2452                 
2453                 /* no period present - add one explicitly */
2454
2455                 old += '.';
2456                 last_period = old.length() - 1;
2457                 number = 0;
2458
2459         } else {
2460
2461                 number = atoi (old.substr (last_period+1).c_str());
2462
2463         }
2464
2465         while (number < (UINT_MAX-1)) {
2466
2467                 RegionList::const_iterator i;
2468                 string sbuf;
2469
2470                 number++;
2471
2472                 snprintf (buf, len, "%s%" PRIu32, old.substr (0, last_period + 1).c_str(), number);
2473                 sbuf = buf;
2474
2475                 for (i = regions.begin(); i != regions.end(); ++i) {
2476                         if (i->second->name() == sbuf) {
2477                                 break;
2478                         }
2479                 }
2480                 
2481                 if (i == regions.end()) {
2482                         break;
2483                 }
2484         }
2485
2486         if (number != (UINT_MAX-1)) {
2487                 return buf;
2488         } 
2489
2490         error << string_compose (_("cannot create new name for region \"%1\""), old) << endmsg;
2491         return old;
2492 }
2493
2494 int
2495 Session::region_name (string& result, string base, bool newlevel) const
2496 {
2497         char buf[16];
2498         string subbase;
2499
2500         assert(base.find("/") == string::npos);
2501
2502         if (base == "") {
2503                 
2504                 Glib::Mutex::Lock lm (region_lock);
2505
2506                 snprintf (buf, sizeof (buf), "%d", (int)regions.size() + 1);
2507
2508                 
2509                 result = "region.";
2510                 result += buf;
2511
2512         } else {
2513
2514                 /* XXX this is going to be slow. optimize me later */
2515                 
2516                 if (newlevel) {
2517                         subbase = base;
2518                 } else {
2519                         string::size_type pos;
2520
2521                         pos = base.find_last_of ('.');
2522
2523                         /* pos may be npos, but then we just use entire base */
2524
2525                         subbase = base.substr (0, pos);
2526
2527                 }
2528
2529                 bool name_taken = true;
2530                 
2531                 {
2532                         Glib::Mutex::Lock lm (region_lock);
2533                         
2534                         for (int n = 1; n < 5000; ++n) {
2535                                 
2536                                 result = subbase;
2537                                 snprintf (buf, sizeof (buf), ".%d", n);
2538                                 result += buf;
2539                                 
2540                                 name_taken = false;
2541                                 
2542                                 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
2543                                         if (i->second->name() == result) {
2544                                                 name_taken = true;
2545                                                 break;
2546                                         }
2547                                 }
2548                                 
2549                                 if (!name_taken) {
2550                                         break;
2551                                 }
2552                         }
2553                 }
2554                         
2555                 if (name_taken) {
2556                         fatal << string_compose(_("too many regions with names like %1"), base) << endmsg;
2557                         /*NOTREACHED*/
2558                 }
2559         }
2560         return 0;
2561 }       
2562
2563 void
2564 Session::add_region (boost::shared_ptr<Region> region)
2565 {
2566         boost::shared_ptr<Region> other;
2567         bool added = false;
2568
2569         { 
2570                 Glib::Mutex::Lock lm (region_lock);
2571
2572                 RegionList::iterator x;
2573
2574                 for (x = regions.begin(); x != regions.end(); ++x) {
2575
2576                         other = x->second;
2577
2578                         if (region->region_list_equivalent (other)) {
2579                                 break;
2580                         }
2581                 }
2582
2583                 if (x == regions.end()) {
2584
2585                         pair<RegionList::key_type,RegionList::mapped_type> entry;
2586
2587                         entry.first = region->id();
2588                         entry.second = region;
2589
2590                         pair<RegionList::iterator,bool> x = regions.insert (entry);
2591
2592
2593                         if (!x.second) {
2594                                 return;
2595                         }
2596
2597                         added = true;
2598                 } 
2599
2600         }
2601
2602         /* mark dirty because something has changed even if we didn't
2603            add the region to the region list.
2604         */
2605         
2606         set_dirty();
2607         
2608         if (added) {
2609                 region->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_region), boost::weak_ptr<Region>(region)));
2610                 region->StateChanged.connect (sigc::bind (mem_fun (*this, &Session::region_changed), boost::weak_ptr<Region>(region)));
2611                 RegionAdded (region); /* EMIT SIGNAL */
2612         }
2613 }
2614
2615 void
2616 Session::region_changed (Change what_changed, boost::weak_ptr<Region> weak_region)
2617 {
2618         boost::shared_ptr<Region> region (weak_region.lock ());
2619
2620         if (!region) {
2621                 return;
2622         }
2623
2624         if (what_changed & Region::HiddenChanged) {
2625                 /* relay hidden changes */
2626                 RegionHiddenChange (region);
2627         }
2628 }
2629
2630 void
2631 Session::remove_region (boost::weak_ptr<Region> weak_region)
2632 {
2633         RegionList::iterator i;
2634         boost::shared_ptr<Region> region (weak_region.lock ());
2635
2636         if (!region) {
2637                 return;
2638         }
2639
2640         bool removed = false;
2641
2642         { 
2643                 Glib::Mutex::Lock lm (region_lock);
2644
2645                 if ((i = regions.find (region->id())) != regions.end()) {
2646                         regions.erase (i);
2647                         removed = true;
2648                 }
2649         }
2650
2651         /* mark dirty because something has changed even if we didn't
2652            remove the region from the region list.
2653         */
2654
2655         set_dirty();
2656
2657         if (removed) {
2658                  RegionRemoved(region); /* EMIT SIGNAL */
2659         }
2660 }
2661
2662 boost::shared_ptr<Region>
2663 Session::find_whole_file_parent (boost::shared_ptr<Region const> child)
2664 {
2665         RegionList::iterator i;
2666         boost::shared_ptr<Region> region;
2667         
2668         Glib::Mutex::Lock lm (region_lock);
2669
2670         for (i = regions.begin(); i != regions.end(); ++i) {
2671
2672                 region = i->second;
2673
2674                 if (region->whole_file()) {
2675
2676                         if (child->source_equivalent (region)) {
2677                                 return region;
2678                         }
2679                 }
2680         } 
2681
2682         return boost::shared_ptr<Region> ();
2683 }       
2684
2685 void
2686 Session::find_equivalent_playlist_regions (boost::shared_ptr<Region> region, vector<boost::shared_ptr<Region> >& result)
2687 {
2688         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i)
2689                 (*i)->get_region_list_equivalent_regions (region, result);
2690 }
2691
2692 int
2693 Session::destroy_region (boost::shared_ptr<Region> region)
2694 {
2695         vector<boost::shared_ptr<Source> > srcs;
2696                 
2697         {
2698                 boost::shared_ptr<AudioRegion> aregion;
2699                 
2700                 if ((aregion = boost::dynamic_pointer_cast<AudioRegion> (region)) == 0) {
2701                         return 0;
2702                 }
2703                 
2704                 if (aregion->playlist()) {
2705                         aregion->playlist()->destroy_region (region);
2706                 }
2707                 
2708                 for (uint32_t n = 0; n < aregion->n_channels(); ++n) {
2709                         srcs.push_back (aregion->source (n));
2710                 }
2711         }
2712
2713         region->drop_references ();
2714
2715         for (vector<boost::shared_ptr<Source> >::iterator i = srcs.begin(); i != srcs.end(); ++i) {
2716
2717                 if (!(*i)->used()) {
2718                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*i);
2719                         
2720                         if (afs) {
2721                                 (afs)->mark_for_remove ();
2722                         }
2723                         
2724                         (*i)->drop_references ();
2725                         
2726                         cerr << "source was not used by any playlist\n";
2727                 }
2728         }
2729
2730         return 0;
2731 }
2732
2733 int
2734 Session::destroy_regions (list<boost::shared_ptr<Region> > regions)
2735 {
2736         for (list<boost::shared_ptr<Region> >::iterator i = regions.begin(); i != regions.end(); ++i) {
2737                 destroy_region (*i);
2738         }
2739         return 0;
2740 }
2741
2742 int
2743 Session::remove_last_capture ()
2744 {
2745         list<boost::shared_ptr<Region> > r;
2746         
2747         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2748         
2749         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2750                 list<boost::shared_ptr<Region> >& l = (*i)->last_capture_regions();
2751                 
2752                 if (!l.empty()) {
2753                         r.insert (r.end(), l.begin(), l.end());
2754                         l.clear ();
2755                 }
2756         }
2757
2758         destroy_regions (r);
2759
2760         save_state (_current_snapshot_name);
2761
2762         return 0;
2763 }
2764
2765 int
2766 Session::remove_region_from_region_list (boost::shared_ptr<Region> r)
2767 {
2768         remove_region (r);
2769         return 0;
2770 }
2771
2772 /* Source Management */
2773 void
2774 Session::add_source (boost::shared_ptr<Source> source)
2775 {
2776         pair<SourceMap::key_type, SourceMap::mapped_type> entry;
2777         pair<SourceMap::iterator,bool> result;
2778
2779         entry.first = source->id();
2780         entry.second = source;
2781         
2782         {
2783                 Glib::Mutex::Lock lm (source_lock);
2784                 result = sources.insert (entry);
2785         }
2786
2787         if (result.second) {
2788                 source->GoingAway.connect (sigc::bind (mem_fun (this, &Session::remove_source), boost::weak_ptr<Source> (source)));
2789                 set_dirty();
2790         }
2791 }
2792
2793 void
2794 Session::remove_source (boost::weak_ptr<Source> src)
2795 {
2796         SourceMap::iterator i;
2797         boost::shared_ptr<Source> source = src.lock();
2798
2799         if (!source) {
2800                 return;
2801         } 
2802
2803         { 
2804                 Glib::Mutex::Lock lm (source_lock);
2805
2806                 if ((i = sources.find (source->id())) != sources.end()) {
2807                         sources.erase (i);
2808                 } 
2809         }
2810         
2811         if (!_state_of_the_state & InCleanup) {
2812                 
2813                 /* save state so we don't end up with a session file
2814                    referring to non-existent sources.
2815                 */
2816                 
2817                 save_state (_current_snapshot_name);
2818         }
2819 }
2820
2821 boost::shared_ptr<Source>
2822 Session::source_by_id (const PBD::ID& id)
2823 {
2824         Glib::Mutex::Lock lm (source_lock);
2825         SourceMap::iterator i;
2826         boost::shared_ptr<Source> source;
2827
2828         if ((i = sources.find (id)) != sources.end()) {
2829                 source = i->second;
2830         }
2831
2832         return source;
2833 }
2834
2835
2836 boost::shared_ptr<Source>
2837 Session::source_by_path_and_channel (const Glib::ustring& path, uint16_t chn)
2838 {
2839         Glib::Mutex::Lock lm (source_lock);
2840
2841         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2842                 cerr << "comparing " << path << " with " << i->second->name() << endl;
2843                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(i->second);
2844
2845                 if (afs && afs->path() == path && chn == afs->channel()) {
2846                         return afs;
2847                 } 
2848                        
2849         }
2850         return boost::shared_ptr<Source>();
2851 }
2852
2853 Glib::ustring
2854 Session::peak_path (Glib::ustring base) const
2855 {
2856         sys::path peakfile_path(_session_dir->peak_path());
2857         peakfile_path /= basename_nosuffix (base) + peakfile_suffix;
2858         return peakfile_path.to_string();
2859 }
2860
2861 string
2862 Session::change_audio_path_by_name (string path, string oldname, string newname, bool destructive)
2863 {
2864         string look_for;
2865         string old_basename = PBD::basename_nosuffix (oldname);
2866         string new_legalized = legalize_for_path (newname);
2867
2868         /* note: we know (or assume) the old path is already valid */
2869
2870         if (destructive) {
2871                 
2872                 /* destructive file sources have a name of the form:
2873
2874                     /path/to/Tnnnn-NAME(%[LR])?.wav
2875                   
2876                     the task here is to replace NAME with the new name.
2877                 */
2878                 
2879                 /* find last slash */
2880
2881                 string dir;
2882                 string prefix;
2883                 string::size_type slash;
2884                 string::size_type dash;
2885
2886                 if ((slash = path.find_last_of ('/')) == string::npos) {
2887                         return "";
2888                 }
2889
2890                 dir = path.substr (0, slash+1);
2891
2892                 /* '-' is not a legal character for the NAME part of the path */
2893
2894                 if ((dash = path.find_last_of ('-')) == string::npos) {
2895                         return "";
2896                 }
2897
2898                 prefix = path.substr (slash+1, dash-(slash+1));
2899
2900                 path = dir;
2901                 path += prefix;
2902                 path += '-';
2903                 path += new_legalized;
2904                 path += ".wav";  /* XXX gag me with a spoon */
2905                 
2906         } else {
2907                 
2908                 /* non-destructive file sources have a name of the form:
2909
2910                     /path/to/NAME-nnnnn(%[LR])?.wav
2911                   
2912                     the task here is to replace NAME with the new name.
2913                 */
2914                 
2915                 string dir;
2916                 string suffix;
2917                 string::size_type slash;
2918                 string::size_type dash;
2919                 string::size_type postfix;
2920
2921                 /* find last slash */
2922
2923                 if ((slash = path.find_last_of ('/')) == string::npos) {
2924                         return "";
2925                 }
2926
2927                 dir = path.substr (0, slash+1);
2928
2929                 /* '-' is not a legal character for the NAME part of the path */
2930
2931                 if ((dash = path.find_last_of ('-')) == string::npos) {
2932                         return "";
2933                 }
2934
2935                 suffix = path.substr (dash+1);
2936                 
2937                 // Suffix is now everything after the dash. Now we need to eliminate
2938                 // the nnnnn part, which is done by either finding a '%' or a '.'
2939
2940                 postfix = suffix.find_last_of ("%");
2941                 if (postfix == string::npos) {
2942                         postfix = suffix.find_last_of ('.');
2943                 }
2944
2945                 if (postfix != string::npos) {
2946                         suffix = suffix.substr (postfix);
2947                 } else {
2948                         error << "Logic error in Session::change_audio_path_by_name(), please report to the developers" << endl;
2949                         return "";
2950                 }
2951
2952                 const uint32_t limit = 10000;
2953                 char buf[PATH_MAX+1];
2954
2955                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
2956
2957                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
2958
2959                         if (access (buf, F_OK) != 0) {
2960                                 path = buf;
2961                                 break;
2962                         }
2963                         path = "";
2964                 }
2965
2966                 if (path == "") {
2967                         error << "FATAL ERROR! Could not find a " << endl;
2968                 }
2969
2970         }
2971
2972         return path;
2973 }
2974
2975 string
2976 Session::audio_path_from_name (string name, uint32_t nchan, uint32_t chan, bool destructive)
2977 {
2978         string spath;
2979         uint32_t cnt;
2980         char buf[PATH_MAX+1];
2981         const uint32_t limit = 10000;
2982         string legalized;
2983
2984         buf[0] = '\0';
2985         legalized = legalize_for_path (name);
2986
2987         /* find a "version" of the file name that doesn't exist in
2988            any of the possible directories.
2989         */
2990
2991         for (cnt = (destructive ? ++destructive_index : 1); cnt <= limit; ++cnt) {
2992
2993                 vector<space_and_path>::iterator i;
2994                 uint32_t existing = 0;
2995
2996                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2997
2998                         SessionDirectory sdir((*i).path);
2999
3000                         spath = sdir.sound_path().to_string();
3001
3002                         if (destructive) {
3003                                 if (nchan < 2) {
3004                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3005                                 } else if (nchan == 2) {
3006                                         if (chan == 0) {
3007                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%L.wav", spath.c_str(), cnt, legalized.c_str());
3008                                         } else {
3009                                                 snprintf (buf, sizeof(buf), "%s/T%04d-%s%%R.wav", spath.c_str(), cnt, legalized.c_str());
3010                                         }
3011                                 } else if (nchan < 26) {
3012                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s%%%c.wav", spath.c_str(), cnt, legalized.c_str(), 'a' + chan);
3013                                 } else {
3014                                         snprintf (buf, sizeof(buf), "%s/T%04d-%s.wav", spath.c_str(), cnt, legalized.c_str());
3015                                 }
3016
3017                         } else {
3018
3019                                 spath += '/';
3020                                 spath += legalized;
3021
3022                                 if (nchan < 2) {
3023                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3024                                 } else if (nchan == 2) {
3025                                         if (chan == 0) {
3026                                                 snprintf (buf, sizeof(buf), "%s-%u%%L.wav", spath.c_str(), cnt);
3027                                         } else {
3028                                                 snprintf (buf, sizeof(buf), "%s-%u%%R.wav", spath.c_str(), cnt);
3029                                         }
3030                                 } else if (nchan < 26) {
3031                                         snprintf (buf, sizeof(buf), "%s-%u%%%c.wav", spath.c_str(), cnt, 'a' + chan);
3032                                 } else {
3033                                         snprintf (buf, sizeof(buf), "%s-%u.wav", spath.c_str(), cnt);
3034                                 }
3035                         }
3036
3037                         if (sys::exists(buf)) {
3038                                 existing++;
3039                         } 
3040
3041                 }
3042
3043                 if (existing == 0) {
3044                         break;
3045                 }
3046
3047                 if (cnt > limit) {
3048                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3049                         destroy ();
3050                         throw failed_constructor();
3051                 }
3052         }
3053
3054         /* we now have a unique name for the file, but figure out where to
3055            actually put it.
3056         */
3057
3058         string foo = buf;
3059
3060         SessionDirectory sdir(get_best_session_directory_for_new_source ());
3061
3062         spath = sdir.sound_path().to_string();
3063         spath += '/';
3064
3065         string::size_type pos = foo.find_last_of ('/');
3066         
3067         if (pos == string::npos) {
3068                 spath += foo;
3069         } else {
3070                 spath += foo.substr (pos + 1);
3071         }
3072
3073         return spath;
3074 }
3075
3076 boost::shared_ptr<AudioFileSource>
3077 Session::create_audio_source_for_session (AudioDiskstream& ds, uint32_t chan, bool destructive)
3078 {
3079         string spath = audio_path_from_name (ds.name(), ds.n_channels().n_audio(), chan, destructive);
3080         return boost::dynamic_pointer_cast<AudioFileSource> (
3081                 SourceFactory::createWritable (DataType::AUDIO, *this, spath, destructive, frame_rate()));
3082 }
3083
3084 // FIXME: _terrible_ code duplication
3085 string
3086 Session::change_midi_path_by_name (string path, string oldname, string newname, bool destructive)
3087 {
3088         string look_for;
3089         string old_basename = PBD::basename_nosuffix (oldname);
3090         string new_legalized = legalize_for_path (newname);
3091
3092         /* note: we know (or assume) the old path is already valid */
3093
3094         if (destructive) {
3095                 
3096                 /* destructive file sources have a name of the form:
3097
3098                     /path/to/Tnnnn-NAME(%[LR])?.wav
3099                   
3100                     the task here is to replace NAME with the new name.
3101                 */
3102                 
3103                 /* find last slash */
3104
3105                 string dir;
3106                 string prefix;
3107                 string::size_type slash;
3108                 string::size_type dash;
3109
3110                 if ((slash = path.find_last_of ('/')) == string::npos) {
3111                         return "";
3112                 }
3113
3114                 dir = path.substr (0, slash+1);
3115
3116                 /* '-' is not a legal character for the NAME part of the path */
3117
3118                 if ((dash = path.find_last_of ('-')) == string::npos) {
3119                         return "";
3120                 }
3121
3122                 prefix = path.substr (slash+1, dash-(slash+1));
3123
3124                 path = dir;
3125                 path += prefix;
3126                 path += '-';
3127                 path += new_legalized;
3128                 path += ".mid";  /* XXX gag me with a spoon */
3129                 
3130         } else {
3131                 
3132                 /* non-destructive file sources have a name of the form:
3133
3134                     /path/to/NAME-nnnnn(%[LR])?.wav
3135                   
3136                     the task here is to replace NAME with the new name.
3137                 */
3138                 
3139                 string dir;
3140                 string suffix;
3141                 string::size_type slash;
3142                 string::size_type dash;
3143                 string::size_type postfix;
3144
3145                 /* find last slash */
3146
3147                 if ((slash = path.find_last_of ('/')) == string::npos) {
3148                         return "";
3149                 }
3150
3151                 dir = path.substr (0, slash+1);
3152
3153                 /* '-' is not a legal character for the NAME part of the path */
3154
3155                 if ((dash = path.find_last_of ('-')) == string::npos) {
3156                         return "";
3157                 }
3158
3159                 suffix = path.substr (dash+1);
3160                 
3161                 // Suffix is now everything after the dash. Now we need to eliminate
3162                 // the nnnnn part, which is done by either finding a '%' or a '.'
3163
3164                 postfix = suffix.find_last_of ("%");
3165                 if (postfix == string::npos) {
3166                         postfix = suffix.find_last_of ('.');
3167                 }
3168
3169                 if (postfix != string::npos) {
3170                         suffix = suffix.substr (postfix);
3171                 } else {
3172                         error << "Logic error in Session::change_midi_path_by_name(), please report to the developers" << endl;
3173                         return "";
3174                 }
3175
3176                 const uint32_t limit = 10000;
3177                 char buf[PATH_MAX+1];
3178
3179                 for (uint32_t cnt = 1; cnt <= limit; ++cnt) {
3180
3181                         snprintf (buf, sizeof(buf), "%s%s-%u%s", dir.c_str(), newname.c_str(), cnt, suffix.c_str());
3182
3183                         if (access (buf, F_OK) != 0) {
3184                                 path = buf;
3185                                 break;
3186                         }
3187                         path = "";
3188                 }
3189
3190                 if (path == "") {
3191                         error << "FATAL ERROR! Could not find a " << endl;
3192                 }
3193
3194         }
3195
3196         return path;
3197 }
3198
3199 string
3200 Session::midi_path_from_name (string name)
3201 {
3202         string spath;
3203         uint32_t cnt;
3204         char buf[PATH_MAX+1];
3205         const uint32_t limit = 10000;
3206         string legalized;
3207
3208         buf[0] = '\0';
3209         legalized = legalize_for_path (name);
3210
3211         /* find a "version" of the file name that doesn't exist in
3212            any of the possible directories.
3213         */
3214
3215         for (cnt = 1; cnt <= limit; ++cnt) {
3216
3217                 vector<space_and_path>::iterator i;
3218                 uint32_t existing = 0;
3219
3220                 for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
3221
3222                         SessionDirectory sdir((*i).path);
3223                 
3224                         sys::path p = sdir.midi_path();
3225
3226                         p /= legalized;
3227
3228                         spath = p.to_string();
3229
3230                         snprintf (buf, sizeof(buf), "%s-%u.mid", spath.c_str(), cnt);
3231
3232                         if (sys::exists (buf)) {
3233                                 existing++;
3234                         } 
3235                 }
3236
3237                 if (existing == 0) {
3238                         break;
3239                 }
3240
3241                 if (cnt > limit) {
3242                         error << string_compose(_("There are already %1 recordings for %2, which I consider too many."), limit, name) << endmsg;
3243                         throw failed_constructor();
3244                 }
3245         }
3246
3247         /* we now have a unique name for the file, but figure out where to
3248            actually put it.
3249         */
3250
3251         string foo = buf;
3252
3253         SessionDirectory sdir(get_best_session_directory_for_new_source ());
3254
3255         spath = sdir.midi_path().to_string();
3256         spath += '/';
3257
3258         string::size_type pos = foo.find_last_of ('/');
3259         
3260         if (pos == string::npos) {
3261                 spath += foo;
3262         } else {
3263                 spath += foo.substr (pos + 1);
3264         }
3265
3266         return spath;
3267 }
3268
3269 boost::shared_ptr<MidiSource>
3270 Session::create_midi_source_for_session (MidiDiskstream& ds)
3271 {
3272         string mpath = midi_path_from_name (ds.name());
3273         
3274         return boost::dynamic_pointer_cast<SMFSource> (SourceFactory::createWritable (DataType::MIDI, *this, mpath, false, frame_rate()));
3275 }
3276
3277
3278 /* Playlist management */
3279
3280 boost::shared_ptr<Playlist>
3281 Session::playlist_by_name (string name)
3282 {
3283         Glib::Mutex::Lock lm (playlist_lock);
3284         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3285                 if ((*i)->name() == name) {
3286                         return* i;
3287                 }
3288         }
3289         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3290                 if ((*i)->name() == name) {
3291                         return* i;
3292                 }
3293         }
3294
3295         return boost::shared_ptr<Playlist>();
3296 }
3297
3298 void
3299 Session::add_playlist (boost::shared_ptr<Playlist> playlist)
3300 {
3301         if (playlist->hidden()) {
3302                 return;
3303         }
3304
3305         { 
3306                 Glib::Mutex::Lock lm (playlist_lock);
3307                 if (find (playlists.begin(), playlists.end(), playlist) == playlists.end()) {
3308                         playlists.insert (playlists.begin(), playlist);
3309                         playlist->InUse.connect (sigc::bind (mem_fun (*this, &Session::track_playlist), boost::weak_ptr<Playlist>(playlist)));
3310                         playlist->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_playlist), boost::weak_ptr<Playlist>(playlist)));
3311                 }
3312         }
3313
3314         set_dirty();
3315
3316         PlaylistAdded (playlist); /* EMIT SIGNAL */
3317 }
3318
3319 void
3320 Session::get_playlists (vector<boost::shared_ptr<Playlist> >& s)
3321 {
3322         { 
3323                 Glib::Mutex::Lock lm (playlist_lock);
3324                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
3325                         s.push_back (*i);
3326                 }
3327                 for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
3328                         s.push_back (*i);
3329                 }
3330         }
3331 }
3332
3333 void
3334 Session::track_playlist (bool inuse, boost::weak_ptr<Playlist> wpl)
3335 {
3336         boost::shared_ptr<Playlist> pl(wpl.lock());
3337
3338         if (!pl) {
3339                 return;
3340         }
3341
3342         PlaylistList::iterator x;
3343
3344         if (pl->hidden()) {
3345                 /* its not supposed to be visible */
3346                 return;
3347         }
3348
3349         { 
3350                 Glib::Mutex::Lock lm (playlist_lock);
3351
3352                 if (!inuse) {
3353
3354                         unused_playlists.insert (pl);
3355                         
3356                         if ((x = playlists.find (pl)) != playlists.end()) {
3357                                 playlists.erase (x);
3358                         }
3359
3360                         
3361                 } else {
3362
3363                         playlists.insert (pl);
3364                         
3365                         if ((x = unused_playlists.find (pl)) != unused_playlists.end()) {
3366                                 unused_playlists.erase (x);
3367                         }
3368                 }
3369         }
3370 }
3371
3372 void
3373 Session::remove_playlist (boost::weak_ptr<Playlist> weak_playlist)
3374 {
3375         if (_state_of_the_state & Deletion) {
3376                 return;
3377         }
3378
3379         boost::shared_ptr<Playlist> playlist (weak_playlist.lock());
3380
3381         if (!playlist) {
3382                 return;
3383         }
3384
3385         { 
3386                 Glib::Mutex::Lock lm (playlist_lock);
3387
3388                 PlaylistList::iterator i;
3389
3390                 i = find (playlists.begin(), playlists.end(), playlist);
3391                 if (i != playlists.end()) {
3392                         playlists.erase (i);
3393                 }
3394
3395                 i = find (unused_playlists.begin(), unused_playlists.end(), playlist);
3396                 if (i != unused_playlists.end()) {
3397                         unused_playlists.erase (i);
3398                 }
3399                 
3400         }
3401
3402         set_dirty();
3403
3404         PlaylistRemoved (playlist); /* EMIT SIGNAL */
3405 }
3406
3407 void 
3408 Session::set_audition (boost::shared_ptr<Region> r)
3409 {
3410         pending_audition_region = r;
3411         post_transport_work = PostTransportWork (post_transport_work | PostTransportAudition);
3412         schedule_butler_transport_work ();
3413 }
3414
3415 void
3416 Session::audition_playlist ()
3417 {
3418         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3419         ev->region.reset ();
3420         queue_event (ev);
3421 }
3422
3423 void
3424 Session::non_realtime_set_audition ()
3425 {
3426         if (!pending_audition_region) {
3427                 auditioner->audition_current_playlist ();
3428         } else {
3429                 auditioner->audition_region (pending_audition_region);
3430                 pending_audition_region.reset ();
3431         }
3432         AuditionActive (true); /* EMIT SIGNAL */
3433 }
3434
3435 void
3436 Session::audition_region (boost::shared_ptr<Region> r)
3437 {
3438         Event* ev = new Event (Event::Audition, Event::Add, Event::Immediate, 0, 0.0);
3439         ev->region = r;
3440         queue_event (ev);
3441 }
3442
3443 void
3444 Session::cancel_audition ()
3445 {
3446         if (auditioner->active()) {
3447                 auditioner->cancel_audition ();
3448                 AuditionActive (false); /* EMIT SIGNAL */
3449         }
3450 }
3451
3452 bool
3453 Session::RoutePublicOrderSorter::operator() (boost::shared_ptr<Route> a, boost::shared_ptr<Route> b)
3454 {
3455         return a->order_key(N_("signal")) < b->order_key(N_("signal"));
3456 }
3457
3458 void
3459 Session::remove_empty_sounds ()
3460 {
3461         vector<string> audio_filenames;
3462
3463         get_files_in_directory (_session_dir->sound_path(), audio_filenames);
3464         
3465         Glib::Mutex::Lock lm (source_lock);
3466
3467         TapeFileMatcher tape_file_matcher;
3468
3469         remove_if (audio_filenames.begin(), audio_filenames.end(),
3470                         sigc::mem_fun (tape_file_matcher, &TapeFileMatcher::matches));
3471
3472         for (vector<string>::iterator i = audio_filenames.begin(); i != audio_filenames.end(); ++i) {
3473
3474                 sys::path audio_file_path (_session_dir->sound_path());
3475
3476                 audio_file_path /= *i;
3477                         
3478                 if (AudioFileSource::is_empty (*this, audio_file_path.to_string())) {
3479
3480                         try
3481                         {
3482                                 sys::remove (audio_file_path);
3483                                 const string peakfile = peak_path (audio_file_path.to_string());
3484                                 sys::remove (peakfile);
3485                         }
3486                         catch (const sys::filesystem_error& err)
3487                         {
3488                                 error << err.what() << endmsg; 
3489                         }
3490                 }
3491         }
3492 }
3493
3494 bool
3495 Session::is_auditioning () const
3496 {
3497         /* can be called before we have an auditioner object */
3498         if (auditioner) {
3499                 return auditioner->active();
3500         } else {
3501                 return false;
3502         }
3503 }
3504
3505 void
3506 Session::set_all_solo (bool yn)
3507 {
3508         shared_ptr<RouteList> r = routes.reader ();
3509         
3510         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3511                 if (!(*i)->is_hidden()) {
3512                         (*i)->set_solo (yn, this);
3513                 }
3514         }
3515
3516         set_dirty();
3517 }
3518                 
3519 void
3520 Session::set_all_mute (bool yn)
3521 {
3522         shared_ptr<RouteList> r = routes.reader ();
3523         
3524         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3525                 if (!(*i)->is_hidden()) {
3526                         (*i)->set_mute (yn, this);
3527                 }
3528         }
3529
3530         set_dirty();
3531 }
3532                 
3533 uint32_t
3534 Session::n_diskstreams () const
3535 {
3536         uint32_t n = 0;
3537
3538         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3539
3540         for (DiskstreamList::const_iterator i = dsl->begin(); i != dsl->end(); ++i) {
3541                 if (!(*i)->hidden()) {
3542                         n++;
3543                 }
3544         }
3545         return n;
3546 }
3547
3548 void
3549 Session::graph_reordered ()
3550 {
3551         /* don't do this stuff if we are setting up connections
3552            from a set_state() call or creating new tracks.
3553         */
3554
3555         if (_state_of_the_state & InitialConnecting) {
3556                 return;
3557         }
3558         
3559         /* every track/bus asked for this to be handled but it was deferred because
3560            we were connecting. do it now.
3561         */
3562
3563         request_input_change_handling ();
3564
3565         resort_routes ();
3566
3567         /* force all diskstreams to update their capture offset values to 
3568            reflect any changes in latencies within the graph.
3569         */
3570         
3571         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3572
3573         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3574                 (*i)->set_capture_offset ();
3575         }
3576 }
3577
3578 void
3579 Session::record_disenable_all ()
3580 {
3581         record_enable_change_all (false);
3582 }
3583
3584 void
3585 Session::record_enable_all ()
3586 {
3587         record_enable_change_all (true);
3588 }
3589
3590 void
3591 Session::record_enable_change_all (bool yn)
3592 {
3593         shared_ptr<RouteList> r = routes.reader ();
3594         
3595         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3596                 Track* at;
3597
3598                 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3599                         at->set_record_enable (yn, this);
3600                 }
3601         }
3602         
3603         /* since we don't keep rec-enable state, don't mark session dirty */
3604 }
3605
3606 void
3607 Session::add_processor (Processor* processor)
3608 {
3609         Send* send;
3610         PortInsert* port_insert;
3611         PluginInsert* plugin_insert;
3612
3613         if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3614                 _port_inserts.insert (_port_inserts.begin(), port_insert);
3615         } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3616                 _plugin_inserts.insert (_plugin_inserts.begin(), plugin_insert);
3617         } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3618                 _sends.insert (_sends.begin(), send);
3619         } else {
3620                 fatal << _("programming error: unknown type of Insert created!") << endmsg;
3621                 /*NOTREACHED*/
3622         }
3623
3624         processor->GoingAway.connect (sigc::bind (mem_fun (*this, &Session::remove_processor), processor));
3625
3626         set_dirty();
3627 }
3628
3629 void
3630 Session::remove_processor (Processor* processor)
3631 {
3632         Send* send;
3633         PortInsert* port_insert;
3634         PluginInsert* plugin_insert;
3635         
3636         if ((port_insert = dynamic_cast<PortInsert *> (processor)) != 0) {
3637                 list<PortInsert*>::iterator x = find (_port_inserts.begin(), _port_inserts.end(), port_insert);
3638                 if (x != _port_inserts.end()) {
3639                         insert_bitset[port_insert->bit_slot()] = false;
3640                         _port_inserts.erase (x);
3641                 }
3642         } else if ((plugin_insert = dynamic_cast<PluginInsert *> (processor)) != 0) {
3643                 _plugin_inserts.remove (plugin_insert);
3644         } else if ((send = dynamic_cast<Send *> (processor)) != 0) {
3645                 list<Send*>::iterator x = find (_sends.begin(), _sends.end(), send);
3646                 if (x != _sends.end()) {
3647                         send_bitset[send->bit_slot()] = false;
3648                         _sends.erase (x);
3649                 }
3650         } else {
3651                 fatal << _("programming error: unknown type of Insert deleted!") << endmsg;
3652                 /*NOTREACHED*/
3653         }
3654
3655         set_dirty();
3656 }
3657
3658 nframes_t
3659 Session::available_capture_duration ()
3660 {
3661         float sample_bytes_on_disk = 4.0; // keep gcc happy
3662
3663         switch (Config->get_native_file_data_format()) {
3664         case FormatFloat:
3665                 sample_bytes_on_disk = 4.0;
3666                 break;
3667
3668         case FormatInt24:
3669                 sample_bytes_on_disk = 3.0;
3670                 break;
3671
3672         case FormatInt16:
3673                 sample_bytes_on_disk = 2.0;
3674                 break;
3675
3676         default: 
3677                 /* impossible, but keep some gcc versions happy */
3678                 fatal << string_compose (_("programming error: %1"),
3679                                          X_("illegal native file data format"))
3680                       << endmsg;
3681                 /*NOTREACHED*/
3682         }
3683
3684         double scale = 4096.0 / sample_bytes_on_disk;
3685
3686         if (_total_free_4k_blocks * scale > (double) max_frames) {
3687                 return max_frames;
3688         }
3689         
3690         return (nframes_t) floor (_total_free_4k_blocks * scale);
3691 }
3692
3693 void
3694 Session::add_bundle (shared_ptr<Bundle> bundle)
3695 {
3696         {
3697                 Glib::Mutex::Lock guard (bundle_lock);
3698                 _bundles.push_back (bundle);
3699         }
3700         
3701         BundleAdded (bundle); /* EMIT SIGNAL */
3702
3703         set_dirty();
3704 }
3705
3706 void
3707 Session::remove_bundle (shared_ptr<Bundle> bundle)
3708 {
3709         bool removed = false;
3710
3711         {
3712                 Glib::Mutex::Lock guard (bundle_lock);
3713                 BundleList::iterator i = find (_bundles.begin(), _bundles.end(), bundle);
3714                 
3715                 if (i != _bundles.end()) {
3716                         _bundles.erase (i);
3717                         removed = true;
3718                 }
3719         }
3720
3721         if (removed) {
3722                  BundleRemoved (bundle); /* EMIT SIGNAL */
3723         }
3724
3725         set_dirty();
3726 }
3727
3728 shared_ptr<Bundle>
3729 Session::bundle_by_name (string name) const
3730 {
3731         Glib::Mutex::Lock lm (bundle_lock);
3732
3733         for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3734                 if ((*i)->name() == name) {
3735                         return* i;
3736                 }
3737         }
3738
3739         return boost::shared_ptr<Bundle> ();
3740 }
3741
3742 boost::shared_ptr<Bundle>
3743 Session::bundle_by_ports (std::vector<std::string> const & wanted_ports) const
3744 {
3745         Glib::Mutex::Lock lm (bundle_lock);
3746
3747         for (BundleList::const_iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
3748                 if ((*i)->nchannels() != wanted_ports.size()) {
3749                         continue;
3750                 }
3751
3752                 bool match = true;
3753                 for (uint32_t j = 0; j < (*i)->nchannels(); ++j) {
3754                         Bundle::PortList const p = (*i)->channel_ports (j);
3755                         if (p.empty() || p[0] != wanted_ports[j]) {
3756                                 /* not this bundle */
3757                                 match = false;
3758                                 break;
3759                         }
3760                 }
3761
3762                 if (match) {
3763                         /* matched bundle */
3764                         return *i;
3765                 }
3766         }
3767
3768         return boost::shared_ptr<Bundle> ();
3769 }
3770
3771 void
3772 Session::tempo_map_changed (Change ignored)
3773 {
3774         clear_clicks ();
3775         set_dirty ();
3776 }
3777
3778 /** Ensures that all buffers (scratch, send, silent, etc) are allocated for
3779  * the given count with the current block size.
3780  */
3781 void
3782 Session::ensure_buffers (ChanCount howmany)
3783 {
3784         if (current_block_size == 0)
3785                 return; // too early? (is this ok?)
3786
3787         // We need at least 2 MIDI scratch buffers to mix/merge
3788         if (howmany.n_midi() < 2)
3789                 howmany.set_midi(2);
3790
3791         // FIXME: JACK needs to tell us maximum MIDI buffer size
3792         // Using nasty assumption (max # events == nframes) for now
3793         _scratch_buffers->ensure_buffers(howmany, current_block_size);
3794         _mix_buffers->ensure_buffers(howmany, current_block_size);
3795         _silent_buffers->ensure_buffers(howmany, current_block_size);
3796         
3797         allocate_pan_automation_buffers (current_block_size, howmany.n_audio(), false);
3798 }
3799
3800 uint32_t
3801 Session::next_insert_id ()
3802 {
3803         /* this doesn't really loop forever. just think about it */
3804
3805         while (true) {
3806                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < insert_bitset.size(); ++n) {
3807                         if (!insert_bitset[n]) {
3808                                 insert_bitset[n] = true;
3809                                 return n;
3810                                 
3811                         }
3812                 }
3813                 
3814                 /* none available, so resize and try again */
3815
3816                 insert_bitset.resize (insert_bitset.size() + 16, false);
3817         }
3818 }
3819
3820 uint32_t
3821 Session::next_send_id ()
3822 {
3823         /* this doesn't really loop forever. just think about it */
3824
3825         while (true) {
3826                 for (boost::dynamic_bitset<uint32_t>::size_type n = 0; n < send_bitset.size(); ++n) {
3827                         if (!send_bitset[n]) {
3828                                 send_bitset[n] = true;
3829                                 return n;
3830                                 
3831                         }
3832                 }
3833                 
3834                 /* none available, so resize and try again */
3835
3836                 send_bitset.resize (send_bitset.size() + 16, false);
3837         }
3838 }
3839
3840 void
3841 Session::mark_send_id (uint32_t id)
3842 {
3843         if (id >= send_bitset.size()) {
3844                 send_bitset.resize (id+16, false);
3845         }
3846         if (send_bitset[id]) {
3847                 warning << string_compose (_("send ID %1 appears to be in use already"), id) << endmsg;
3848         }
3849         send_bitset[id] = true;
3850 }
3851
3852 void
3853 Session::mark_insert_id (uint32_t id)
3854 {
3855         if (id >= insert_bitset.size()) {
3856                 insert_bitset.resize (id+16, false);
3857         }
3858         if (insert_bitset[id]) {
3859                 warning << string_compose (_("insert ID %1 appears to be in use already"), id) << endmsg;
3860         }
3861         insert_bitset[id] = true;
3862 }
3863
3864 /* Named Selection management */
3865
3866 NamedSelection *
3867 Session::named_selection_by_name (string name)
3868 {
3869         Glib::Mutex::Lock lm (named_selection_lock);
3870         for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
3871                 if ((*i)->name == name) {
3872                         return* i;
3873                 }
3874         }
3875         return 0;
3876 }
3877
3878 void
3879 Session::add_named_selection (NamedSelection* named_selection)
3880 {
3881         { 
3882                 Glib::Mutex::Lock lm (named_selection_lock);
3883                 named_selections.insert (named_selections.begin(), named_selection);
3884         }
3885
3886         for (list<boost::shared_ptr<Playlist> >::iterator i = named_selection->playlists.begin(); i != named_selection->playlists.end(); ++i) {
3887                 add_playlist (*i);
3888         }
3889
3890         set_dirty();
3891
3892         NamedSelectionAdded (); /* EMIT SIGNAL */
3893 }
3894
3895 void
3896 Session::remove_named_selection (NamedSelection* named_selection)
3897 {
3898         bool removed = false;
3899
3900         { 
3901                 Glib::Mutex::Lock lm (named_selection_lock);
3902
3903                 NamedSelectionList::iterator i = find (named_selections.begin(), named_selections.end(), named_selection);
3904
3905                 if (i != named_selections.end()) {
3906                         delete (*i);
3907                         named_selections.erase (i);
3908                         set_dirty();
3909                         removed = true;
3910                 }
3911         }
3912
3913         if (removed) {
3914                  NamedSelectionRemoved (); /* EMIT SIGNAL */
3915         }
3916 }
3917
3918 void
3919 Session::reset_native_file_format ()
3920 {
3921         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
3922
3923         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
3924                 (*i)->reset_write_sources (false);
3925         }
3926 }
3927
3928 bool
3929 Session::route_name_unique (string n) const
3930 {
3931         shared_ptr<RouteList> r = routes.reader ();
3932         
3933         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
3934                 if ((*i)->name() == n) {
3935                         return false;
3936                 }
3937         }
3938         
3939         return true;
3940 }
3941
3942 uint32_t
3943 Session::n_playlists () const
3944 {
3945         Glib::Mutex::Lock lm (playlist_lock);
3946         return playlists.size();
3947 }
3948
3949 void
3950 Session::allocate_pan_automation_buffers (nframes_t nframes, uint32_t howmany, bool force)
3951 {
3952         if (!force && howmany <= _npan_buffers) {
3953                 return;
3954         }
3955
3956         if (_pan_automation_buffer) {
3957
3958                 for (uint32_t i = 0; i < _npan_buffers; ++i) {
3959                         delete [] _pan_automation_buffer[i];
3960                 }
3961
3962                 delete [] _pan_automation_buffer;
3963         }
3964
3965         _pan_automation_buffer = new pan_t*[howmany];
3966         
3967         for (uint32_t i = 0; i < howmany; ++i) {
3968                 _pan_automation_buffer[i] = new pan_t[nframes];
3969         }
3970
3971         _npan_buffers = howmany;
3972 }
3973
3974 int
3975 Session::freeze (InterThreadInfo& itt)
3976 {
3977         shared_ptr<RouteList> r = routes.reader ();
3978
3979         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
3980
3981                 Track *at;
3982
3983                 if ((at = dynamic_cast<Track*>((*i).get())) != 0) {
3984                         /* XXX this is wrong because itt.progress will keep returning to zero at the start
3985                            of every track.
3986                         */
3987                         at->freeze (itt);
3988                 }
3989         }
3990
3991         return 0;
3992 }
3993
3994 int
3995 Session::write_one_audio_track (AudioTrack& track, nframes_t start, nframes_t len,      
3996                                bool overwrite, vector<boost::shared_ptr<Source> >& srcs, InterThreadInfo& itt)
3997 {
3998         int ret = -1;
3999         boost::shared_ptr<Playlist> playlist;
4000         boost::shared_ptr<AudioFileSource> fsource;
4001         uint32_t x;
4002         char buf[PATH_MAX+1];
4003         ChanCount nchans(track.audio_diskstream()->n_channels());
4004         nframes_t position;
4005         nframes_t this_chunk;
4006         nframes_t to_do;
4007         BufferSet buffers;
4008         SessionDirectory sdir(get_best_session_directory_for_new_source ());
4009         const string sound_dir = sdir.sound_path().to_string();
4010
4011         // any bigger than this seems to cause stack overflows in called functions
4012         const nframes_t chunk_size = (128 * 1024)/4;
4013
4014         g_atomic_int_set (&processing_prohibited, 1);
4015         
4016         /* call tree *MUST* hold route_lock */
4017         
4018         if ((playlist = track.diskstream()->playlist()) == 0) {
4019                 goto out;
4020         }
4021
4022         /* external redirects will be a problem */
4023
4024         if (track.has_external_redirects()) {
4025                 goto out;
4026         }
4027
4028         for (uint32_t chan_n=0; chan_n < nchans.n_audio(); ++chan_n) {
4029
4030                 for (x = 0; x < 99999; ++x) {
4031                         snprintf (buf, sizeof(buf), "%s/%s-%d-bounce-%" PRIu32 ".wav", sound_dir.c_str(), playlist->name().c_str(), chan_n, x+1);
4032                         if (access (buf, F_OK) != 0) {
4033                                 break;
4034                         }
4035                 }
4036                 
4037                 if (x == 99999) {
4038                         error << string_compose (_("too many bounced versions of playlist \"%1\""), playlist->name()) << endmsg;
4039                         goto out;
4040                 }
4041                 
4042                 try {
4043                         fsource = boost::dynamic_pointer_cast<AudioFileSource> (
4044                                 SourceFactory::createWritable (DataType::AUDIO, *this, buf, false, frame_rate()));
4045                 }
4046                 
4047                 catch (failed_constructor& err) {
4048                         error << string_compose (_("cannot create new audio file \"%1\" for %2"), buf, track.name()) << endmsg;
4049                         goto out;
4050                 }
4051
4052                 srcs.push_back (fsource);
4053         }
4054
4055         /* XXX need to flush all redirects */
4056         
4057         position = start;
4058         to_do = len;
4059
4060         /* create a set of reasonably-sized buffers */
4061         buffers.ensure_buffers(nchans, chunk_size);
4062         buffers.set_count(nchans);
4063
4064         for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4065                 boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4066                 if (afs)
4067                         afs->prepare_for_peakfile_writes ();
4068         }
4069                         
4070         while (to_do && !itt.cancel) {
4071                 
4072                 this_chunk = min (to_do, chunk_size);
4073                 
4074                 if (track.export_stuff (buffers, start, this_chunk)) {
4075                         goto out;
4076                 }
4077
4078                 uint32_t n = 0;
4079                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src, ++n) {
4080                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4081                         
4082                         if (afs) {
4083                                 if (afs->write (buffers.get_audio(n).data(), this_chunk) != this_chunk) {
4084                                         goto out;
4085                                 }
4086                         }
4087                 }
4088                 
4089                 start += this_chunk;
4090                 to_do -= this_chunk;
4091                 
4092                 itt.progress = (float) (1.0 - ((double) to_do / len));
4093
4094         }
4095
4096         if (!itt.cancel) {
4097                 
4098                 time_t now;
4099                 struct tm* xnow;
4100                 time (&now);
4101                 xnow = localtime (&now);
4102                 
4103                 for (vector<boost::shared_ptr<Source> >::iterator src=srcs.begin(); src != srcs.end(); ++src) {
4104                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4105                         
4106                         if (afs) {
4107                                 afs->update_header (position, *xnow, now);
4108                                 afs->flush_header ();
4109                         }
4110                 }
4111                 
4112                 /* construct a region to represent the bounced material */
4113
4114                 boost::shared_ptr<Region> aregion = RegionFactory::create (srcs, 0, srcs.front()->length(), 
4115                                                                            region_name_from_path (srcs.front()->name(), true));
4116
4117                 ret = 0;
4118         }
4119                 
4120   out:
4121         if (ret) {
4122                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4123                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4124
4125                         if (afs) {
4126                                 afs->mark_for_remove ();
4127                         }
4128
4129                         (*src)->drop_references ();
4130                 }
4131
4132         } else {
4133                 for (vector<boost::shared_ptr<Source> >::iterator src = srcs.begin(); src != srcs.end(); ++src) {
4134                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource>(*src);
4135                         
4136                         if (afs)
4137                                 afs->done_with_peakfile_writes ();
4138                 }
4139         }
4140
4141         g_atomic_int_set (&processing_prohibited, 0);
4142
4143         return ret;
4144 }
4145
4146 BufferSet&
4147 Session::get_silent_buffers (ChanCount count)
4148 {
4149         assert(_silent_buffers->available() >= count);
4150         _silent_buffers->set_count(count);
4151
4152         for (DataType::iterator t = DataType::begin(); t != DataType::end(); ++t) {
4153                 for (size_t i=0; i < count.get(*t); ++i) {
4154                         _silent_buffers->get(*t, i).clear();
4155                 }
4156         }
4157         
4158         return *_silent_buffers;
4159 }
4160
4161 BufferSet&
4162 Session::get_scratch_buffers (ChanCount count)
4163 {
4164         assert(_scratch_buffers->available() >= count);
4165         _scratch_buffers->set_count(count);
4166         return *_scratch_buffers;
4167 }
4168
4169 BufferSet&
4170 Session::get_mix_buffers (ChanCount count)
4171 {
4172         assert(_mix_buffers->available() >= count);
4173         _mix_buffers->set_count(count);
4174         return *_mix_buffers;
4175 }
4176
4177 uint32_t 
4178 Session::ntracks () const
4179 {
4180         uint32_t n = 0;
4181         shared_ptr<RouteList> r = routes.reader ();
4182
4183         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4184                 if (dynamic_cast<Track*> ((*i).get())) {
4185                         ++n;
4186                 }
4187         }
4188
4189         return n;
4190 }
4191
4192 uint32_t 
4193 Session::nbusses () const
4194 {
4195         uint32_t n = 0;
4196         shared_ptr<RouteList> r = routes.reader ();
4197
4198         for (RouteList::const_iterator i = r->begin(); i != r->end(); ++i) {
4199                 if (dynamic_cast<Track*> ((*i).get()) == 0) {
4200                         ++n;
4201                 }
4202         }
4203
4204         return n;
4205 }
4206
4207 void
4208 Session::add_automation_list(AutomationList *al)
4209 {
4210         automation_lists[al->id()] = al;
4211 }
4212
4213 nframes_t
4214 Session::compute_initial_length ()
4215 {
4216         return _engine.frame_rate() * 60 * 5;
4217 }
4218
4219 void
4220 Session::sync_order_keys ()
4221 {
4222         if (!Config->get_sync_all_route_ordering()) {
4223                 /* leave order keys as they are */
4224                 return;
4225         }
4226
4227         boost::shared_ptr<RouteList> r = routes.reader ();
4228
4229         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
4230                 (*i)->sync_order_keys ();
4231         }
4232
4233         Route::SyncOrderKeys (); // EMIT SIGNAL
4234 }
4235
4236 void
4237 Session::foreach_bundle (sigc::slot<void, boost::shared_ptr<Bundle> > sl)
4238 {
4239         Glib::Mutex::Lock lm (bundle_lock);
4240         for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
4241                 sl (*i);
4242         }
4243 }
4244