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