Use Session::_session_dir instead of Session::_path when calling Session::setup_raid_...
[ardour.git] / libs / ardour / session_state.cc
1 /*
2   Copyright (C) 1999-2002 Paul Davis 
3
4   This program is free software; you can redistribute it and/or modify
5   it under the terms of the GNU General Public License as published by
6   the Free Software Foundation; either version 2 of the License, or
7   (at your option) any later version.
8
9   This program is distributed in the hope that it will be useful,
10   but WITHOUT ANY WARRANTY; without even the implied warranty of
11   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12   GNU General Public License for more details.
13
14   You should have received a copy of the GNU General Public License
15   along with this program; if not, write to the Free Software
16   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17     
18 */
19
20 #define __STDC_FORMAT_MACROS 1
21 #include <stdint.h>
22
23 #include <algorithm>
24 #include <fstream>
25 #include <string>
26 #include <cerrno>
27
28 #include <sigc++/bind.h>
29
30 #include <cstdio> /* snprintf(3) ... grrr */
31 #include <cmath>
32 #include <unistd.h>
33 #include <sys/stat.h>
34 #include <climits>
35 #include <fcntl.h>
36 #include <poll.h>
37 #include <signal.h>
38 #include <sys/mman.h>
39 #include <sys/time.h>
40 #include <dirent.h>
41
42 #ifdef HAVE_SYS_VFS_H
43 #include <sys/vfs.h>
44 #else
45 #include <sys/param.h>
46 #include <sys/mount.h>
47 #endif
48
49 #include <glibmm.h>
50
51 #include <midi++/mmc.h>
52 #include <midi++/port.h>
53 #include <pbd/error.h>
54
55 #include <glibmm/thread.h>
56 #include <pbd/pathscanner.h>
57 #include <pbd/pthread_utils.h>
58 #include <pbd/search_path.h>
59 #include <pbd/stacktrace.h>
60
61 #include <ardour/audioengine.h>
62 #include <ardour/configuration.h>
63 #include <ardour/session.h>
64 #include <ardour/session_directory.h>
65 #include <ardour/session_utils.h>
66 #include <ardour/session_state_utils.h>
67 #include <ardour/buffer.h>
68 #include <ardour/audio_diskstream.h>
69 #include <ardour/midi_diskstream.h>
70 #include <ardour/utils.h>
71 #include <ardour/audioplaylist.h>
72 #include <ardour/midi_playlist.h>
73 #include <ardour/smf_source.h>
74 #include <ardour/audiofilesource.h>
75 #include <ardour/silentfilesource.h>
76 #include <ardour/sndfilesource.h>
77 #include <ardour/midi_source.h>
78 #include <ardour/sndfile_helpers.h>
79 #include <ardour/auditioner.h>
80 #include <ardour/export.h>
81 #include <ardour/io_processor.h>
82 #include <ardour/send.h>
83 #include <ardour/processor.h>
84 #include <ardour/bundle.h>
85 #include <ardour/slave.h>
86 #include <ardour/tempo.h>
87 #include <ardour/audio_track.h>
88 #include <ardour/midi_track.h>
89 #include <ardour/cycle_timer.h>
90 #include <ardour/utils.h>
91 #include <ardour/named_selection.h>
92 #include <ardour/version.h>
93 #include <ardour/location.h>
94 #include <ardour/audioregion.h>
95 #include <ardour/midi_region.h>
96 #include <ardour/crossfade.h>
97 #include <ardour/control_protocol_manager.h>
98 #include <ardour/region_factory.h>
99 #include <ardour/source_factory.h>
100 #include <ardour/playlist_factory.h>
101 #include <ardour/filename_extensions.h>
102 #include <ardour/directory_names.h>
103 #include <ardour/template_utils.h>
104
105 #include <control_protocol/control_protocol.h>
106
107 #include "i18n.h"
108 #include <locale.h>
109
110 using namespace std;
111 using namespace ARDOUR;
112 using namespace PBD;
113
114 void
115 Session::first_stage_init (string fullpath, string snapshot_name)
116 {
117         if (fullpath.length() == 0) {
118                 destroy ();
119                 throw failed_constructor();
120         }
121
122         char buf[PATH_MAX+1];
123         if (!realpath (fullpath.c_str(), buf) && (errno != ENOENT)) {
124                 error << string_compose(_("Could not use path %1 (%s)"), buf, strerror(errno)) << endmsg;
125                 destroy ();
126                 throw failed_constructor();
127         }
128
129         _path = string(buf);
130
131         if (_path[_path.length()-1] != '/') {
132                 _path += '/';
133         }
134
135         /* these two are just provisional settings. set_state()
136            will likely override them.
137         */
138
139         _name = _current_snapshot_name = snapshot_name;
140
141         _current_frame_rate = _engine.frame_rate ();
142         _tempo_map = new TempoMap (_current_frame_rate);
143         _tempo_map->StateChanged.connect (mem_fun (*this, &Session::tempo_map_changed));
144
145         g_atomic_int_set (&processing_prohibited, 0);
146         insert_cnt = 0;
147         _transport_speed = 0;
148         _last_transport_speed = 0;
149         auto_play_legal = false;
150         transport_sub_state = 0;
151         _transport_frame = 0;
152         last_stop_frame = 0;
153         end_location = new Location (0, 0, _("end"), Location::Flags ((Location::IsMark|Location::IsEnd)));
154         start_location = new Location (0, 0, _("start"), Location::Flags ((Location::IsMark|Location::IsStart)));
155         _end_location_is_free = true;
156         g_atomic_int_set (&_record_status, Disabled);
157         loop_changing = false;
158         play_loop = false;
159         _last_roll_location = 0;
160         _last_record_location = 0;
161         pending_locate_frame = 0;
162         pending_locate_roll = false;
163         pending_locate_flush = false;
164         dstream_buffer_size = 0;
165         state_tree = 0;
166         state_was_pending = false;
167         set_next_event ();
168         outbound_mtc_smpte_frame = 0;
169         next_quarter_frame_to_send = -1;
170         current_block_size = 0;
171         solo_update_disabled = false;
172         currently_soloing = false;
173         _have_captured = false;
174         _worst_output_latency = 0;
175         _worst_input_latency = 0;
176         _worst_track_latency = 0;
177         _state_of_the_state = StateOfTheState(CannotSave|InitialConnecting|Loading|Deletion);
178         _slave = 0;
179         butler_mixdown_buffer = 0;
180         butler_gain_buffer = 0;
181         mmc = 0;
182         session_send_mmc = false;
183         session_send_mtc = false;
184         post_transport_work = PostTransportWork (0);
185         g_atomic_int_set (&butler_should_do_transport_work, 0);
186         g_atomic_int_set (&butler_active, 0);
187         g_atomic_int_set (&_playback_load, 100);
188         g_atomic_int_set (&_capture_load, 100);
189         g_atomic_int_set (&_playback_load_min, 100);
190         g_atomic_int_set (&_capture_load_min, 100);
191         _play_range = false;
192         waiting_to_start = false;
193         _exporting = false;
194         _gain_automation_buffer = 0;
195         _pan_automation_buffer = 0;
196         _npan_buffers = 0;
197         pending_abort = false;
198         destructive_index = 0;
199         current_trans = 0;
200         first_file_data_format_reset = true;
201         first_file_header_format_reset = true;
202         butler_thread = (pthread_t) 0;
203         //midi_thread = (pthread_t) 0;
204
205         AudioDiskstream::allocate_working_buffers();
206
207         /* default short fade = 15ms */
208
209         Crossfade::set_short_xfade_length ((nframes_t) floor (Config->get_short_xfade_seconds() * frame_rate()));
210         SndFileSource::setup_standard_crossfades (frame_rate());
211
212         last_mmc_step.tv_sec = 0;
213         last_mmc_step.tv_usec = 0;
214         step_speed = 0.0;
215
216         /* click sounds are unset by default, which causes us to internal
217            waveforms for clicks.
218         */
219         
220         click_data = 0;
221         click_emphasis_data = 0;
222         click_length = 0;
223         click_emphasis_length = 0;
224         _clicking = false;
225
226         process_function = &Session::process_with_events;
227
228         if (Config->get_use_video_sync()) {
229                 waiting_for_sync_offset = true;
230         } else {
231                 waiting_for_sync_offset = false;
232         }
233
234         _current_frame_rate = 48000;
235         _base_frame_rate = 48000;
236
237         last_smpte_when = 0;
238         _smpte_offset = 0;
239         _smpte_offset_negative = true;
240         last_smpte_valid = false;
241
242         sync_time_vars ();
243
244         last_rr_session_dir = session_dirs.begin();
245         refresh_disk_space ();
246
247         // set_default_fade (0.2, 5.0); /* steepness, millisecs */
248
249         /* slave stuff */
250
251         average_slave_delta = 1800;
252         have_first_delta_accumulator = false;
253         delta_accumulator_cnt = 0;
254         slave_state = Stopped;
255
256         _engine.GraphReordered.connect (mem_fun (*this, &Session::graph_reordered));
257
258         /* These are all static "per-class" signals */
259
260         RegionFactory::CheckNewRegion.connect (mem_fun (*this, &Session::add_region));
261         SourceFactory::SourceCreated.connect (mem_fun (*this, &Session::add_source));
262         PlaylistFactory::PlaylistCreated.connect (mem_fun (*this, &Session::add_playlist));
263         Processor::ProcessorCreated.connect (mem_fun (*this, &Session::add_processor));
264         NamedSelection::NamedSelectionCreated.connect (mem_fun (*this, &Session::add_named_selection));
265         AutomationList::AutomationListCreated.connect (mem_fun (*this, &Session::add_automation_list));
266
267         Controllable::Destroyed.connect (mem_fun (*this, &Session::remove_controllable));
268
269         IO::MoreChannels.connect (mem_fun (*this, &Session::ensure_buffers));
270
271         /* stop IO objects from doing stuff until we're ready for them */
272
273         IO::disable_panners ();
274         IO::disable_ports ();
275         IO::disable_connecting ();
276 }
277
278 int
279 Session::second_stage_init (bool new_session)
280 {
281         AudioFileSource::set_peak_dir (_session_dir->peak_path().to_string());
282
283         if (!new_session) {
284                 if (load_state (_current_snapshot_name)) {
285                         return -1;
286                 }
287                 remove_empty_sounds ();
288         }
289
290         if (start_butler_thread()) {
291                 return -1;
292         }
293
294         /*if (start_midi_thread ()) {
295                 return -1;
296         }*/
297
298         // set_state() will call setup_raid_path(), but if it's a new session we need
299         // to call setup_raid_path() here.
300         if (state_tree) {
301                 if (set_state (*state_tree->root())) {
302                         return -1;
303                 }
304         } else {
305                 setup_raid_path(_path);
306         }
307
308         /* we can't save till after ::when_engine_running() is called,
309            because otherwise we save state with no connections made.
310            therefore, we reset _state_of_the_state because ::set_state()
311            will have cleared it.
312
313            we also have to include Loading so that any events that get
314            generated between here and the end of ::when_engine_running()
315            will be processed directly rather than queued.
316         */
317
318         _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave|Loading);
319
320         // set_auto_input (true);
321         _locations.changed.connect (mem_fun (this, &Session::locations_changed));
322         _locations.added.connect (mem_fun (this, &Session::locations_added));
323         setup_click_sounds (0);
324         setup_midi_control ();
325
326         /* Pay attention ... */
327
328         _engine.Halted.connect (mem_fun (*this, &Session::engine_halted));
329         _engine.Xrun.connect (mem_fun (*this, &Session::xrun_recovery));
330
331         try {
332                 when_engine_running();
333         }
334
335         /* handle this one in a different way than all others, so that its clear what happened */
336         
337         catch (AudioEngine::PortRegistrationFailure& err) {
338                 error << _("Unable to create all required ports")
339                       << endmsg;
340                 return -1;
341         }
342
343         catch (...) {
344                 return -1;
345         }
346
347         //send_full_time_code ();
348         _engine.transport_locate (0);
349         deliver_mmc (MIDI::MachineControl::cmdMmcReset, 0);
350         deliver_mmc (MIDI::MachineControl::cmdLocate, 0);
351
352         ControlProtocolManager::instance().set_session (*this);
353
354         if (new_session) {
355                 _end_location_is_free = true;
356         } else {
357                 _end_location_is_free = false;
358         }
359         
360         return 0;
361 }
362
363 string
364 Session::raid_path () const
365 {
366         SearchPath raid_search_path;
367
368         for (vector<space_and_path>::const_iterator i = session_dirs.begin(); i != session_dirs.end(); ++i) {
369                 raid_search_path += sys::path((*i).path);
370         }
371         
372         return raid_search_path.to_string ();
373 }
374
375 void
376 Session::setup_raid_path (string path)
377 {
378         if (path.empty()) {
379                 return;
380         }
381         
382         space_and_path sp;
383         string fspath;
384
385         session_dirs.clear ();
386
387         SearchPath search_path(path);
388         SearchPath sound_search_path;
389         SearchPath midi_search_path;
390
391         for (
392                         SearchPath::const_iterator i = search_path.begin();
393                         i != search_path.end();
394                         ++i
395                 )
396         {
397                 sp.path = (*i).to_string ();
398                 sp.blocks = 0; // not needed
399                 session_dirs.push_back (sp);
400
401                 SessionDirectory sdir(sp.path);
402
403                 sound_search_path += sdir.sound_path ();
404                 midi_search_path += sdir.midi_path ();
405         }
406
407         // set the AudioFileSource and SMFSource search path
408
409         AudioFileSource::set_search_path (sound_search_path.to_string ());
410         SMFSource::set_search_path (midi_search_path.to_string ());
411
412         // reset the round-robin soundfile path thingie
413         
414         last_rr_session_dir = session_dirs.begin();
415 }
416
417 void
418 Session::initialize_start_and_end_locations (nframes_t start, nframes_t end)
419 {
420         start_location->set_end (start);
421         _locations.add (start_location);
422
423         end_location->set_end (end);
424         _locations.add (end_location);
425 }
426
427 bool
428 Session::create_session_file ()
429 {
430         _state_of_the_state = Clean;
431
432         if (save_state (_current_snapshot_name)) {
433                 error << "Could not create new session file" << endmsg;
434                 return false;
435         }
436         return true;
437 }
438
439 bool
440 Session::create_session_file_from_template (const string& template_path)
441 {
442         sys::path session_file_path(_session_dir->root_path());
443
444         session_file_path /= _name + statefile_suffix;
445
446         try
447         {
448                 sys::copy_file (template_path, session_file_path);
449         }
450         catch(sys::filesystem_error& ex)
451         {
452                 error << string_compose (_("Could not use session template %1 to create new session (%2)."),
453                                 template_path, ex.what())
454                         << endmsg;
455                 return false;
456         }
457         return true;
458 }
459
460 int
461 Session::load_diskstreams (const XMLNode& node)
462 {
463         XMLNodeList          clist;
464         XMLNodeConstIterator citer;
465         
466         clist = node.children();
467
468         for (citer = clist.begin(); citer != clist.end(); ++citer) {
469
470                 try {
471                         /* diskstreams added automatically by DiskstreamCreated handler */
472                         if ((*citer)->name() == "AudioDiskstream" || (*citer)->name() == "DiskStream") {
473                                 boost::shared_ptr<AudioDiskstream> dstream (new AudioDiskstream (*this, **citer));
474                                 add_diskstream (dstream);
475                         } else if ((*citer)->name() == "MidiDiskstream") {
476                                 boost::shared_ptr<MidiDiskstream> dstream (new MidiDiskstream (*this, **citer));
477                                 add_diskstream (dstream);
478                         } else {
479                                 error << _("Session: unknown diskstream type in XML") << endmsg;
480                         }
481                 } 
482                 
483                 catch (failed_constructor& err) {
484                         error << _("Session: could not load diskstream via XML state") << endmsg;
485                         return -1;
486                 }
487         }
488
489         return 0;
490 }
491
492 void
493 Session::maybe_write_autosave()
494 {
495         if (dirty() && record_status() != Recording) {
496                 save_state("", true);
497         }
498 }
499
500 void
501 Session::remove_pending_capture_state ()
502 {
503         sys::path pending_state_file_path(_session_dir->root_path());
504
505         pending_state_file_path /= _current_snapshot_name + pending_suffix;
506
507         try
508         {
509                 sys::remove (pending_state_file_path);
510         }
511         catch(sys::filesystem_error& ex)
512         {
513                 error << string_compose(_("Could remove pending capture state at path \"%1\" (%2)"),
514                                 pending_state_file_path.to_string(), ex.what()) << endmsg;
515         }
516 }
517
518 /** Rename a state file.
519  * @param snapshot_name Snapshot name.
520  */
521 void
522 Session::rename_state (string old_name, string new_name)
523 {
524         if (old_name == _current_snapshot_name || old_name == _name) {
525                 /* refuse to rename the current snapshot or the "main" one */
526                 return;
527         }
528         
529         const string old_xml_path = _path + old_name + statefile_suffix;
530         const string new_xml_path = _path + new_name + statefile_suffix;
531
532         if (rename (old_xml_path.c_str(), new_xml_path.c_str()) != 0) {
533                 error << string_compose(_("could not rename snapshot %1 to %2"), old_name, new_name) << endmsg;
534         }
535 }
536
537 /** Remove a state file.
538  * @param snapshot_name Snapshot name.
539  */
540 void
541 Session::remove_state (string snapshot_name)
542 {
543         if (snapshot_name == _current_snapshot_name || snapshot_name == _name) {
544                 // refuse to remove the current snapshot or the "main" one
545                 return;
546         }
547
548         sys::path xml_path(_session_dir->root_path());
549
550         xml_path /= snapshot_name + statefile_suffix;
551
552         if (!create_backup_file (xml_path)) {
553                 // don't remove it if a backup can't be made
554                 // create_backup_file will log the error.
555                 return;
556         }
557
558         // and delete it
559         sys::remove (xml_path);
560 }
561
562 int
563 Session::save_state (string snapshot_name, bool pending)
564 {
565         XMLTree tree;
566         sys::path xml_path(_session_dir->root_path());
567
568         if (_state_of_the_state & CannotSave) {
569                 return 1;
570         }
571
572         if (!_engine.connected ()) {
573                 error << _("Ardour's audio engine is not connected and state saving would lose all I/O connections. Session not saved")
574                       << endmsg;
575                 return 1;
576         }
577
578         /* tell sources we're saving first, in case they write out to a new file
579          * which should be saved with the state rather than the old one */
580         for (SourceMap::const_iterator i = sources.begin(); i != sources.end(); ++i)
581                 i->second->session_saved();
582
583         tree.set_root (&get_state());
584
585         if (snapshot_name.empty()) {
586                 snapshot_name = _current_snapshot_name;
587         }
588
589         if (!pending) {
590
591                 /* proper save: use statefile_suffix (.ardour in English) */
592                 
593                 xml_path /= snapshot_name + statefile_suffix;
594
595                 /* make a backup copy of the old file */
596
597                 if (sys::exists(xml_path) && !create_backup_file (xml_path)) {
598                         // create_backup_file will log the error
599                         return -1;
600                 }
601
602         } else {
603
604                 /* pending save: use pending_suffix (.pending in English) */
605                 xml_path /= snapshot_name + pending_suffix;
606         }
607
608         sys::path tmp_path(_session_dir->root_path());
609
610         tmp_path /= snapshot_name + temp_suffix;
611
612         // cerr << "actually writing state to " << xml_path.to_string() << endl;
613
614         if (!tree.write (tmp_path.to_string())) {
615                 error << string_compose (_("state could not be saved to %1"), tmp_path.to_string()) << endmsg;
616                 sys::remove (tmp_path);
617                 return -1;
618
619         } else {
620
621                 if (rename (tmp_path.to_string().c_str(), xml_path.to_string().c_str()) != 0) {
622                         error << string_compose (_("could not rename temporary session file %1 to %2"),
623                                         tmp_path.to_string(), xml_path.to_string()) << endmsg;
624                         sys::remove (tmp_path);
625                         return -1;
626                 }
627         }
628
629         if (!pending) {
630
631                 save_history (snapshot_name);
632
633                 bool was_dirty = dirty();
634
635                 _state_of_the_state = StateOfTheState (_state_of_the_state & ~Dirty);
636
637                 if (was_dirty) {
638                         DirtyChanged (); /* EMIT SIGNAL */
639                 }
640
641                 StateSaved (snapshot_name); /* EMIT SIGNAL */
642         }
643
644         return 0;
645 }
646
647 int
648 Session::restore_state (string snapshot_name)
649 {
650         if (load_state (snapshot_name) == 0) {
651                 set_state (*state_tree->root());
652         }
653         
654         return 0;
655 }
656
657 int
658 Session::load_state (string snapshot_name)
659 {
660         if (state_tree) {
661                 delete state_tree;
662                 state_tree = 0;
663         }
664
665         state_was_pending = false;
666
667         /* check for leftover pending state from a crashed capture attempt */
668
669         sys::path xmlpath(_session_dir->root_path());
670         xmlpath /= snapshot_name + pending_suffix;
671
672         if (sys::exists (xmlpath)) {
673
674                 /* there is pending state from a crashed capture attempt */
675
676                 if (AskAboutPendingState()) {
677                         state_was_pending = true;
678                 } 
679         } 
680
681         if (!state_was_pending) {
682                 xmlpath = _session_dir->root_path();
683                 xmlpath /= snapshot_name + statefile_suffix;
684         }
685         
686         if (!sys::exists (xmlpath)) {
687                 error << string_compose(_("%1: session state information file \"%2\" doesn't exist!"), _name, xmlpath.to_string()) << endmsg;
688                 return 1;
689         }
690
691         state_tree = new XMLTree;
692
693         set_dirty();
694
695         if (!state_tree->read (xmlpath.to_string())) {
696                 error << string_compose(_("Could not understand ardour file %1"), xmlpath.to_string()) << endmsg;
697                 delete state_tree;
698                 state_tree = 0;
699                 return -1;
700         }
701
702         XMLNode& root (*state_tree->root());
703         
704         if (root.name() != X_("Session")) {
705                 error << string_compose (_("Session file %1 is not an Ardour session"), xmlpath.to_string()) << endmsg;
706                 delete state_tree;
707                 state_tree = 0;
708                 return -1;
709         }
710
711         const XMLProperty* prop;
712         bool is_old = false;
713
714         if ((prop = root.property ("version")) == 0) {
715                 /* no version implies very old version of Ardour */
716                 is_old = true;
717         } else {
718                 int major_version;
719                 major_version = atoi (prop->value().c_str()); // grab just the first number before the period
720                 if (major_version < 2) {
721                         is_old = true;
722                 }
723         }
724
725         if (is_old) {
726
727                 sys::path backup_path(_session_dir->root_path());
728
729                 backup_path /= snapshot_name + "-1" + statefile_suffix;
730
731                 info << string_compose (_("Copying old session file %1 to %2\nUse %2 with Ardour versions before 2.0 from now on"),
732                                         xmlpath.to_string(), backup_path.to_string()) 
733                      << endmsg;
734
735                 try
736                 {
737                         sys::copy_file (xmlpath, backup_path);
738                 }
739                 catch(sys::filesystem_error& ex)
740                 {
741                         error << string_compose (_("Unable to make backup of state file %1 (%2)"),
742                                         xmlpath.to_string(), ex.what())
743                                 << endmsg;
744                         return -1;
745                 }
746         }
747
748         return 0;
749 }
750
751 int
752 Session::load_options (const XMLNode& node)
753 {
754         XMLNode* child;
755         XMLProperty* prop;
756         LocaleGuard lg (X_("POSIX"));
757
758         Config->set_variables (node, ConfigVariableBase::Session);
759
760         if ((child = find_named_node (node, "end-marker-is-free")) != 0) {
761                 if ((prop = child->property ("val")) != 0) {
762                         _end_location_is_free = (prop->value() == "yes");
763                 }
764         }
765
766         return 0;
767 }
768
769 bool
770 Session::save_config_options_predicate (ConfigVariableBase::Owner owner) const
771 {
772         const ConfigVariableBase::Owner modified_by_session_or_user = (ConfigVariableBase::Owner)
773                 (ConfigVariableBase::Session|ConfigVariableBase::Interface);
774
775         return owner & modified_by_session_or_user;
776 }
777
778 XMLNode&
779 Session::get_options () const
780 {
781         XMLNode* child;
782         LocaleGuard lg (X_("POSIX"));
783
784         XMLNode& option_root = Config->get_variables (mem_fun (*this, &Session::save_config_options_predicate));
785
786         child = option_root.add_child ("end-marker-is-free");
787         child->add_property ("val", _end_location_is_free ? "yes" : "no");
788
789         return option_root;
790 }
791
792 XMLNode&
793 Session::get_state()
794 {
795         return state(true);
796 }
797
798 XMLNode&
799 Session::get_template()
800 {
801         /* if we don't disable rec-enable, diskstreams
802            will believe they need to store their capture
803            sources in their state node. 
804         */
805         
806         disable_record (false);
807
808         return state(false);
809 }
810
811 XMLNode&
812 Session::state(bool full_state)
813 {
814         XMLNode* node = new XMLNode("Session");
815         XMLNode* child;
816
817         // store libardour version, just in case
818         char buf[16];
819         snprintf(buf, sizeof(buf)-1, "%d.%d.%d", 
820                  libardour_major_version, libardour_minor_version, libardour_micro_version);
821         node->add_property("version", string(buf));
822                 
823         /* store configuration settings */
824
825         if (full_state) {
826         
827                 /* store the name */
828                 node->add_property ("name", _name);
829
830                 if (session_dirs.size() > 1) {
831
832                         string p;
833
834                         vector<space_and_path>::iterator i = session_dirs.begin();
835                         vector<space_and_path>::iterator next;
836
837                         ++i; /* skip the first one */
838                         next = i;
839                         ++next;
840
841                         while (i != session_dirs.end()) {
842
843                                 p += (*i).path;
844
845                                 if (next != session_dirs.end()) {
846                                         p += ':';
847                                 } else {
848                                         break;
849                                 }
850
851                                 ++next;
852                                 ++i;
853                         }
854                         
855                         child = node->add_child ("Path");
856                         child->add_content (p);
857                 }
858         }
859
860         /* save the ID counter */
861         
862         snprintf (buf, sizeof (buf), "%" PRIu64, ID::counter());
863         node->add_property ("id-counter", buf);
864
865         /* various options */
866
867         node->add_child_nocopy (get_options());
868
869         child = node->add_child ("Sources");
870
871         if (full_state) {
872                 Glib::Mutex::Lock sl (source_lock);
873
874                 for (SourceMap::iterator siter = sources.begin(); siter != sources.end(); ++siter) {
875                         
876                         /* Don't save information about AudioFileSources that are empty */
877                         
878                         boost::shared_ptr<AudioFileSource> fs;
879
880                         if ((fs = boost::dynamic_pointer_cast<AudioFileSource> (siter->second)) != 0) {
881
882                                 /* Don't save sources that are empty, unless they're destructive (which are OK
883                                    if they are empty, because we will re-use them every time.)
884                                 */
885
886                                 if (!fs->destructive()) {
887                                         if (fs->length() == 0) {
888                                                 continue;
889                                         }
890                                 }
891                         }
892                         
893                         child->add_child_nocopy (siter->second->get_state());
894                 }
895         }
896
897         child = node->add_child ("Regions");
898
899         if (full_state) { 
900                 Glib::Mutex::Lock rl (region_lock);
901
902                 for (RegionList::const_iterator i = regions.begin(); i != regions.end(); ++i) {
903                         
904                         /* only store regions not attached to playlists */
905
906                         if (i->second->playlist() == 0) {
907                                 child->add_child_nocopy (i->second->state (true));
908                         }
909                 }
910         }
911
912         child = node->add_child ("DiskStreams");
913
914         { 
915                 boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
916                 for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
917                         if (!(*i)->hidden()) {
918                                 child->add_child_nocopy ((*i)->get_state());
919                         }
920                 }
921         }
922
923         if (full_state) {
924                 node->add_child_nocopy (_locations.get_state());
925         } else {
926                 // for a template, just create a new Locations, populate it
927                 // with the default start and end, and get the state for that.
928                 Locations loc;
929                 Location* start = new Location(0, 0, _("start"), Location::Flags ((Location::IsMark|Location::IsStart)));
930                 Location* end = new Location(0, 0, _("end"), Location::Flags ((Location::IsMark|Location::IsEnd)));
931                 start->set_end(0);
932                 loc.add (start);
933                 end->set_end(compute_initial_length());
934                 loc.add (end);
935                 node->add_child_nocopy (loc.get_state());
936         }
937         
938         child = node->add_child ("Connections");
939         {
940                 Glib::Mutex::Lock lm (bundle_lock);
941                 for (BundleList::iterator i = _bundles.begin(); i != _bundles.end(); ++i) {
942                         if (!(*i)->dynamic()) {
943                                 child->add_child_nocopy ((*i)->get_state());
944                         }
945                 }
946         }
947
948         child = node->add_child ("Routes");
949         {
950                 boost::shared_ptr<RouteList> r = routes.reader ();
951                 
952                 RoutePublicOrderSorter cmp;
953                 RouteList public_order (*r);
954                 public_order.sort (cmp);
955                 
956                 for (RouteList::iterator i = public_order.begin(); i != public_order.end(); ++i) {
957                         if (!(*i)->is_hidden()) {
958                                 if (full_state) {
959                                         child->add_child_nocopy ((*i)->get_state());
960                                 } else {
961                                         child->add_child_nocopy ((*i)->get_template());
962                                 }
963                         }
964                 }
965         }
966
967         
968         child = node->add_child ("EditGroups");
969         for (list<RouteGroup *>::iterator i = edit_groups.begin(); i != edit_groups.end(); ++i) {
970                 child->add_child_nocopy ((*i)->get_state());
971         }
972
973         child = node->add_child ("MixGroups");
974         for (list<RouteGroup *>::iterator i = mix_groups.begin(); i != mix_groups.end(); ++i) {
975                 child->add_child_nocopy ((*i)->get_state());
976         }
977
978         child = node->add_child ("Playlists");
979         for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
980                 if (!(*i)->hidden()) {
981                         if (!(*i)->empty()) {
982                                 if (full_state) {
983                                         child->add_child_nocopy ((*i)->get_state());
984                                 } else {
985                                         child->add_child_nocopy ((*i)->get_template());
986                                 }
987                         }
988                 }
989         }
990
991         child = node->add_child ("UnusedPlaylists");
992         for (PlaylistList::iterator i = unused_playlists.begin(); i != unused_playlists.end(); ++i) {
993                 if (!(*i)->hidden()) {
994                         if (!(*i)->empty()) {
995                                 if (full_state) {
996                                         child->add_child_nocopy ((*i)->get_state());
997                                 } else {
998                                         child->add_child_nocopy ((*i)->get_template());
999                                 }
1000                         }
1001                 }
1002         }
1003         
1004         
1005         if (_click_io) {
1006                 child = node->add_child ("Click");
1007                 child->add_child_nocopy (_click_io->state (full_state));
1008         }
1009
1010         if (full_state) {
1011                 child = node->add_child ("NamedSelections");
1012                 for (NamedSelectionList::iterator i = named_selections.begin(); i != named_selections.end(); ++i) {
1013                         if (full_state) {
1014                                 child->add_child_nocopy ((*i)->get_state());
1015                         } 
1016                 }
1017         }
1018
1019         node->add_child_nocopy (_tempo_map->get_state());
1020
1021         node->add_child_nocopy (get_control_protocol_state());
1022
1023         if (_extra_xml) {
1024                 node->add_child_copy (*_extra_xml);
1025         }
1026
1027         return *node;
1028 }
1029
1030 XMLNode&
1031 Session::get_control_protocol_state ()
1032 {
1033         ControlProtocolManager& cpm (ControlProtocolManager::instance());
1034         return cpm.get_state();
1035 }
1036
1037 int
1038 Session::set_state (const XMLNode& node)
1039 {
1040         XMLNodeList nlist;
1041         XMLNode* child;
1042         const XMLProperty* prop;
1043         int ret = -1;
1044
1045         _state_of_the_state = StateOfTheState (_state_of_the_state|CannotSave);
1046         
1047         if (node.name() != X_("Session")){
1048                 fatal << _("programming error: Session: incorrect XML node sent to set_state()") << endmsg;
1049                 return -1;
1050         }
1051
1052         if ((prop = node.property ("name")) != 0) {
1053                 _name = prop->value ();
1054         }
1055
1056         setup_raid_path(_session_dir->root_path().to_string());
1057
1058         if ((prop = node.property (X_("id-counter"))) != 0) {
1059                 uint64_t x;
1060                 sscanf (prop->value().c_str(), "%" PRIu64, &x);
1061                 ID::init_counter (x);
1062         } else {
1063                 /* old sessions used a timebased counter, so fake
1064                    the startup ID counter based on a standard
1065                    timestamp.
1066                 */
1067                 time_t now;
1068                 time (&now);
1069                 ID::init_counter (now);
1070         }
1071
1072         
1073         IO::disable_ports ();
1074         IO::disable_connecting ();
1075
1076         /* Object loading order:
1077
1078         MIDI Control
1079         Path
1080         extra
1081         Options/Config
1082         Locations
1083         Sources
1084         AudioRegions
1085         AudioDiskstreams
1086         Connections
1087         Routes
1088         EditGroups
1089         MixGroups
1090         Click
1091         ControlProtocols
1092         */
1093
1094         if (use_config_midi_ports ()) {
1095         }
1096
1097         if ((child = find_named_node (node, "extra")) != 0) {
1098                 _extra_xml = new XMLNode (*child);
1099         }
1100
1101         if (((child = find_named_node (node, "Options")) != 0)) { /* old style */
1102                 load_options (*child);
1103         } else if ((child = find_named_node (node, "Config")) != 0) { /* new style */
1104                 load_options (*child);
1105         } else {
1106                 error << _("Session: XML state has no options section") << endmsg;
1107         }
1108
1109         if ((child = find_named_node (node, "Locations")) == 0) {
1110                 error << _("Session: XML state has no locations section") << endmsg;
1111                 goto out;
1112         } else if (_locations.set_state (*child)) {
1113                 goto out;
1114         }
1115
1116         Location* location;
1117
1118         if ((location = _locations.auto_loop_location()) != 0) {
1119                 set_auto_loop_location (location);
1120         }
1121
1122         if ((location = _locations.auto_punch_location()) != 0) {
1123                 set_auto_punch_location (location);
1124         }
1125
1126         if ((location = _locations.end_location()) == 0) {
1127                 _locations.add (end_location);
1128         } else {
1129                 delete end_location;
1130                 end_location = location;
1131         }
1132
1133         if ((location = _locations.start_location()) == 0) {
1134                 _locations.add (start_location);
1135         } else {
1136                 delete start_location;
1137                 start_location = location;
1138         }
1139
1140         AudioFileSource::set_header_position_offset (start_location->start());
1141
1142         if ((child = find_named_node (node, "Sources")) == 0) {
1143                 error << _("Session: XML state has no sources section") << endmsg;
1144                 goto out;
1145         } else if (load_sources (*child)) {
1146                 goto out;
1147         }
1148
1149         if ((child = find_named_node (node, "Regions")) == 0) {
1150                 error << _("Session: XML state has no Regions section") << endmsg;
1151                 goto out;
1152         } else if (load_regions (*child)) {
1153                 goto out;
1154         }
1155
1156         if ((child = find_named_node (node, "Playlists")) == 0) {
1157                 error << _("Session: XML state has no playlists section") << endmsg;
1158                 goto out;
1159         } else if (load_playlists (*child)) {
1160                 goto out;
1161         }
1162
1163         if ((child = find_named_node (node, "UnusedPlaylists")) == 0) {
1164                 // this is OK
1165         } else if (load_unused_playlists (*child)) {
1166                 goto out;
1167         }
1168         
1169         if ((child = find_named_node (node, "NamedSelections")) != 0) {
1170                 if (load_named_selections (*child)) {
1171                         goto out;
1172                 }
1173         }
1174
1175         if ((child = find_named_node (node, "DiskStreams")) == 0) {
1176                 error << _("Session: XML state has no diskstreams section") << endmsg;
1177                 goto out;
1178         } else if (load_diskstreams (*child)) {
1179                 goto out;
1180         }
1181
1182         if ((child = find_named_node (node, "Connections")) == 0) {
1183                 error << _("Session: XML state has no connections section") << endmsg;
1184                 goto out;
1185         } else if (load_bundles (*child)) {
1186                 goto out;
1187         }
1188
1189         if ((child = find_named_node (node, "EditGroups")) == 0) {
1190                 error << _("Session: XML state has no edit groups section") << endmsg;
1191                 goto out;
1192         } else if (load_edit_groups (*child)) {
1193                 goto out;
1194         }
1195
1196         if ((child = find_named_node (node, "MixGroups")) == 0) {
1197                 error << _("Session: XML state has no mix groups section") << endmsg;
1198                 goto out;
1199         } else if (load_mix_groups (*child)) {
1200                 goto out;
1201         }
1202
1203         if ((child = find_named_node (node, "TempoMap")) == 0) {
1204                 error << _("Session: XML state has no Tempo Map section") << endmsg;
1205                 goto out;
1206         } else if (_tempo_map->set_state (*child)) {
1207                 goto out;
1208         }
1209
1210         if ((child = find_named_node (node, "Routes")) == 0) {
1211                 error << _("Session: XML state has no routes section") << endmsg;
1212                 goto out;
1213         } else if (load_routes (*child)) {
1214                 goto out;
1215         }
1216
1217         if ((child = find_named_node (node, "Click")) == 0) {
1218                 warning << _("Session: XML state has no click section") << endmsg;
1219         } else if (_click_io) {
1220                 _click_io->set_state (*child);
1221         }
1222         
1223         if ((child = find_named_node (node, "ControlProtocols")) != 0) {
1224                 ControlProtocolManager::instance().set_protocol_states (*child);
1225         }
1226
1227         /* here beginneth the second phase ... */
1228
1229         StateReady (); /* EMIT SIGNAL */
1230
1231         _state_of_the_state = Clean;
1232
1233         if (state_was_pending) {
1234                 save_state (_current_snapshot_name);
1235                 remove_pending_capture_state ();
1236                 state_was_pending = false;
1237         }
1238
1239         return 0;
1240
1241   out:
1242         return ret;
1243 }
1244
1245 int
1246 Session::load_routes (const XMLNode& node)
1247 {
1248         XMLNodeList nlist;
1249         XMLNodeConstIterator niter;
1250         RouteList new_routes;
1251
1252         nlist = node.children();
1253
1254         set_dirty();
1255
1256         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1257
1258                 boost::shared_ptr<Route> route (XMLRouteFactory (**niter));
1259
1260                 if (route == 0) {
1261                         error << _("Session: cannot create Route from XML description.")                              << endmsg;
1262                         return -1;
1263                 }
1264
1265                 new_routes.push_back (route);
1266         }
1267
1268         add_routes (new_routes);
1269
1270         return 0;
1271 }
1272
1273 boost::shared_ptr<Route>
1274 Session::XMLRouteFactory (const XMLNode& node)
1275 {
1276         if (node.name() != "Route") {
1277                 return boost::shared_ptr<Route> ((Route*) 0);
1278         }
1279
1280         bool has_diskstream = (node.property ("diskstream") != 0 || node.property ("diskstream-id") != 0);
1281         
1282         DataType type = DataType::AUDIO;
1283         const XMLProperty* prop = node.property("default-type");
1284         if (prop)
1285                 type = DataType(prop->value());
1286         
1287         assert(type != DataType::NIL);
1288
1289         if (has_diskstream) {
1290                 if (type == DataType::AUDIO) {
1291                         boost::shared_ptr<Route> ret (new AudioTrack (*this, node));
1292                         return ret;
1293                 } else {
1294                         boost::shared_ptr<Route> ret (new MidiTrack (*this, node));
1295                         return ret;
1296                 }
1297         } else {
1298                 boost::shared_ptr<Route> ret (new Route (*this, node));
1299                 return ret;
1300         }
1301 }
1302
1303 int
1304 Session::load_regions (const XMLNode& node)
1305 {
1306         XMLNodeList nlist;
1307         XMLNodeConstIterator niter;
1308         boost::shared_ptr<Region> region;
1309
1310         nlist = node.children();
1311
1312         set_dirty();
1313
1314         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1315                 if ((region = XMLRegionFactory (**niter, false)) == 0) {
1316                         error << _("Session: cannot create Region from XML description.") << endmsg;
1317                 }
1318         }
1319
1320         return 0;
1321 }
1322
1323 boost::shared_ptr<Region>
1324 Session::XMLRegionFactory (const XMLNode& node, bool full)
1325 {
1326         const XMLProperty* type = node.property("type");
1327
1328         try {
1329         
1330         if ( !type || type->value() == "audio" ) {
1331
1332                 return boost::shared_ptr<Region>(XMLAudioRegionFactory (node, full));
1333         
1334         } else if (type->value() == "midi") {
1335                 
1336                 return boost::shared_ptr<Region>(XMLMidiRegionFactory (node, full));
1337
1338         }
1339         
1340         } catch (failed_constructor& err) {
1341                 return boost::shared_ptr<Region> ();
1342         }
1343
1344         return boost::shared_ptr<Region> ();
1345 }
1346
1347 boost::shared_ptr<AudioRegion>
1348 Session::XMLAudioRegionFactory (const XMLNode& node, bool full)
1349 {
1350         const XMLProperty* prop;
1351         boost::shared_ptr<Source> source;
1352         boost::shared_ptr<AudioSource> as;
1353         SourceList sources;
1354         uint32_t nchans = 1;
1355         char buf[128];
1356         
1357         if (node.name() != X_("Region")) {
1358                 return boost::shared_ptr<AudioRegion>();
1359         }
1360
1361         if ((prop = node.property (X_("channels"))) != 0) {
1362                 nchans = atoi (prop->value().c_str());
1363         }
1364
1365         if ((prop = node.property ("name")) == 0) {
1366                 cerr << "no name for this region\n";
1367                 abort ();
1368         }
1369         
1370         if ((prop = node.property (X_("source-0"))) == 0) {
1371                 if ((prop = node.property ("source")) == 0) {
1372                         error << _("Session: XMLNode describing a AudioRegion is incomplete (no source)") << endmsg;
1373                         return boost::shared_ptr<AudioRegion>();
1374                 }
1375         }
1376
1377         PBD::ID s_id (prop->value());
1378
1379         if ((source = source_by_id (s_id)) == 0) {
1380                 error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), s_id) << endmsg;
1381                 return boost::shared_ptr<AudioRegion>();
1382         }
1383         
1384         as = boost::dynamic_pointer_cast<AudioSource>(source);
1385         if (!as) {
1386                 error << string_compose(_("Session: XMLNode describing a AudioRegion references a non-audio source id =%1"), s_id) << endmsg;
1387                 return boost::shared_ptr<AudioRegion>();
1388         }
1389
1390         sources.push_back (as);
1391
1392         /* pickup other channels */
1393
1394         for (uint32_t n=1; n < nchans; ++n) {
1395                 snprintf (buf, sizeof(buf), X_("source-%d"), n);
1396                 if ((prop = node.property (buf)) != 0) {
1397                         
1398                         PBD::ID id2 (prop->value());
1399                         
1400                         if ((source = source_by_id (id2)) == 0) {
1401                                 error << string_compose(_("Session: XMLNode describing a AudioRegion references an unknown source id =%1"), id2) << endmsg;
1402                                 return boost::shared_ptr<AudioRegion>();
1403                         }
1404                         
1405                         as = boost::dynamic_pointer_cast<AudioSource>(source);
1406                         if (!as) {
1407                                 error << string_compose(_("Session: XMLNode describing a AudioRegion references a non-audio source id =%1"), id2) << endmsg;
1408                                 return boost::shared_ptr<AudioRegion>();
1409                         }
1410                         sources.push_back (as);
1411                 }
1412         }
1413         
1414         try {
1415                 boost::shared_ptr<AudioRegion> region (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, node)));
1416
1417                 /* a final detail: this is the one and only place that we know how long missing files are */
1418
1419                 if (region->whole_file()) {
1420                         for (SourceList::iterator sx = sources.begin(); sx != sources.end(); ++sx) {
1421                                 boost::shared_ptr<SilentFileSource> sfp = boost::dynamic_pointer_cast<SilentFileSource> (*sx);
1422                                 if (sfp) {
1423                                         sfp->set_length (region->length());
1424                                 }
1425                         }
1426                 }
1427
1428                 return region;
1429                                                        
1430         }
1431
1432         catch (failed_constructor& err) {
1433                 return boost::shared_ptr<AudioRegion>();
1434         }
1435 }
1436
1437 boost::shared_ptr<MidiRegion>
1438 Session::XMLMidiRegionFactory (const XMLNode& node, bool full)
1439 {
1440         const XMLProperty* prop;
1441         boost::shared_ptr<Source> source;
1442         boost::shared_ptr<MidiSource> ms;
1443         SourceList sources;
1444         uint32_t nchans = 1;
1445         
1446         if (node.name() != X_("Region")) {
1447                 return boost::shared_ptr<MidiRegion>();
1448         }
1449
1450         if ((prop = node.property (X_("channels"))) != 0) {
1451                 nchans = atoi (prop->value().c_str());
1452         }
1453         
1454         if ((prop = node.property ("name")) == 0) {
1455                 cerr << "no name for this region\n";
1456                 abort ();
1457         }
1458
1459         // Multiple midi channels?  that's just crazy talk
1460         assert(nchans == 1);
1461
1462         if ((prop = node.property (X_("source-0"))) == 0) {
1463                 if ((prop = node.property ("source")) == 0) {
1464                         error << _("Session: XMLNode describing a MidiRegion is incomplete (no source)") << endmsg;
1465                         return boost::shared_ptr<MidiRegion>();
1466                 }
1467         }
1468
1469         PBD::ID s_id (prop->value());
1470
1471         if ((source = source_by_id (s_id)) == 0) {
1472                 error << string_compose(_("Session: XMLNode describing a MidiRegion references an unknown source id =%1"), s_id) << endmsg;
1473                 return boost::shared_ptr<MidiRegion>();
1474         }
1475
1476         ms = boost::dynamic_pointer_cast<MidiSource>(source);
1477         if (!ms) {
1478                 error << string_compose(_("Session: XMLNode describing a MidiRegion references a non-midi source id =%1"), s_id) << endmsg;
1479                 return boost::shared_ptr<MidiRegion>();
1480         }
1481
1482         sources.push_back (ms);
1483
1484         try {
1485                 boost::shared_ptr<MidiRegion> region (boost::dynamic_pointer_cast<MidiRegion> (RegionFactory::create (sources, node)));
1486                 /* a final detail: this is the one and only place that we know how long missing files are */
1487
1488                 if (region->whole_file()) {
1489                         for (SourceList::iterator sx = sources.begin(); sx != sources.end(); ++sx) {
1490                                 boost::shared_ptr<SilentFileSource> sfp = boost::dynamic_pointer_cast<SilentFileSource> (*sx);
1491                                 if (sfp) {
1492                                         sfp->set_length (region->length());
1493                                 }
1494                         }
1495                 }
1496
1497                 return region;
1498         }
1499
1500         catch (failed_constructor& err) {
1501                 return boost::shared_ptr<MidiRegion>();
1502         }
1503 }
1504
1505 XMLNode&
1506 Session::get_sources_as_xml ()
1507
1508 {
1509         XMLNode* node = new XMLNode (X_("Sources"));
1510         Glib::Mutex::Lock lm (source_lock);
1511
1512         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
1513                 node->add_child_nocopy (i->second->get_state());
1514         }
1515
1516         return *node;
1517 }
1518
1519 string
1520 Session::path_from_region_name (DataType type, string name, string identifier)
1521 {
1522         char buf[PATH_MAX+1];
1523         uint32_t n;
1524         SessionDirectory sdir(get_best_session_directory_for_new_source());
1525         string sound_dir = ((type == DataType::AUDIO)
1526                 ? sdir.sound_path().to_string()
1527                 : sdir.midi_path().to_string());
1528
1529         string ext = ((type == DataType::AUDIO) ? ".wav" : ".mid");
1530
1531         for (n = 0; n < 999999; ++n) {
1532                 if (identifier.length()) {
1533                         snprintf (buf, sizeof(buf), "%s/%s%s%" PRIu32 "%s", sound_dir.c_str(), name.c_str(), 
1534                                   identifier.c_str(), n, ext.c_str());
1535                 } else {
1536                         snprintf (buf, sizeof(buf), "%s/%s-%" PRIu32 "%s", sound_dir.c_str(), name.c_str(),
1537                                         n, ext.c_str());
1538                 }
1539
1540                 if (!Glib::file_test (buf, Glib::FILE_TEST_EXISTS)) {
1541                         return buf;
1542                 }
1543         }
1544
1545         error << string_compose (_("cannot create new file from region name \"%1\" with ident = \"%2\": too many existing files with similar names"),
1546                                  name, identifier)
1547               << endmsg;
1548
1549         return "";
1550 }
1551         
1552
1553 int
1554 Session::load_sources (const XMLNode& node)
1555 {
1556         XMLNodeList nlist;
1557         XMLNodeConstIterator niter;
1558         boost::shared_ptr<Source> source;
1559
1560         nlist = node.children();
1561
1562         set_dirty();
1563
1564         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1565
1566                 try {
1567                         if ((source = XMLSourceFactory (**niter)) == 0) {
1568                                 error << _("Session: cannot create Source from XML description.") << endmsg;
1569                         }
1570                 }
1571
1572                 catch (non_existent_source& err) {
1573                         warning << _("A sound file is missing. It will be replaced by silence.") << endmsg;
1574                         source = SourceFactory::createSilent (*this, **niter, max_frames, _current_frame_rate);
1575                 }
1576         }
1577
1578         return 0;
1579 }
1580
1581 boost::shared_ptr<Source>
1582 Session::XMLSourceFactory (const XMLNode& node)
1583 {
1584         if (node.name() != "Source") {
1585                 return boost::shared_ptr<Source>();
1586         }
1587
1588         try {
1589                 return SourceFactory::create (*this, node);
1590         }
1591
1592         catch (failed_constructor& err) {
1593                 error << _("Found a sound file that cannot be used by Ardour. Talk to the progammers.") << endmsg;
1594                 return boost::shared_ptr<Source>();
1595         }
1596 }
1597
1598 int
1599 Session::save_template (string template_name)
1600 {
1601         XMLTree tree;
1602
1603         if (_state_of_the_state & CannotSave) {
1604                 return -1;
1605         }
1606
1607         sys::path user_template_dir(user_template_directory());
1608
1609         try
1610         {
1611                 sys::create_directories (user_template_dir);
1612         }
1613         catch(sys::filesystem_error& ex)
1614         {
1615                 error << string_compose(_("Could not create mix templates directory \"%1\" (%2)"),
1616                                 user_template_dir.to_string(), ex.what()) << endmsg;
1617                 return -1;
1618         }
1619
1620         tree.set_root (&get_template());
1621
1622         sys::path template_file_path(user_template_dir);
1623         template_file_path /= template_name + template_suffix;
1624
1625         if (sys::exists (template_file_path))
1626         {
1627                 warning << string_compose(_("Template \"%1\" already exists - new version not created"),
1628                                 template_file_path.to_string()) << endmsg;
1629                 return -1;
1630         }
1631
1632         if (!tree.write (template_file_path.to_string())) {
1633                 error << _("mix template not saved") << endmsg;
1634                 return -1;
1635         }
1636
1637         return 0;
1638 }
1639
1640 void
1641 Session::refresh_disk_space ()
1642 {
1643 #if HAVE_SYS_VFS_H
1644         struct statfs statfsbuf;
1645         vector<space_and_path>::iterator i;
1646         Glib::Mutex::Lock lm (space_lock);
1647         double scale;
1648
1649         /* get freespace on every FS that is part of the session path */
1650
1651         _total_free_4k_blocks = 0;
1652         
1653         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
1654                 statfs ((*i).path.c_str(), &statfsbuf);
1655
1656                 scale = statfsbuf.f_bsize/4096.0;
1657
1658                 (*i).blocks = (uint32_t) floor (statfsbuf.f_bavail * scale);
1659                 _total_free_4k_blocks += (*i).blocks;
1660         }
1661 #endif
1662 }
1663
1664 string
1665 Session::get_best_session_directory_for_new_source ()
1666 {
1667         vector<space_and_path>::iterator i;
1668         string result = _session_dir->root_path().to_string();
1669
1670         /* handle common case without system calls */
1671
1672         if (session_dirs.size() == 1) {
1673                 return result;
1674         }
1675
1676         /* OK, here's the algorithm we're following here:
1677            
1678         We want to select which directory to use for 
1679         the next file source to be created. Ideally,
1680         we'd like to use a round-robin process so as to
1681         get maximum performance benefits from splitting
1682         the files across multiple disks.
1683
1684         However, in situations without much diskspace, an
1685         RR approach may end up filling up a filesystem
1686         with new files while others still have space.
1687         Its therefore important to pay some attention to
1688         the freespace in the filesystem holding each
1689         directory as well. However, if we did that by
1690         itself, we'd keep creating new files in the file
1691         system with the most space until it was as full
1692         as all others, thus negating any performance
1693         benefits of this RAID-1 like approach.
1694
1695         So, we use a user-configurable space threshold. If
1696         there are at least 2 filesystems with more than this
1697         much space available, we use RR selection between them. 
1698         If not, then we pick the filesystem with the most space.
1699
1700         This gets a good balance between the two
1701         approaches.  
1702         */
1703         
1704         refresh_disk_space ();
1705         
1706         int free_enough = 0;
1707
1708         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
1709                 if ((*i).blocks * 4096 >= Config->get_disk_choice_space_threshold()) {
1710                         free_enough++;
1711                 }
1712         }
1713
1714         if (free_enough >= 2) {
1715                 /* use RR selection process, ensuring that the one
1716                    picked works OK.
1717                 */
1718
1719                 i = last_rr_session_dir;
1720
1721                 do {
1722                         if (++i == session_dirs.end()) {
1723                                 i = session_dirs.begin();
1724                         }
1725
1726                         if ((*i).blocks * 4096 >= Config->get_disk_choice_space_threshold()) {
1727                                 if (create_session_directory ((*i).path)) {
1728                                         result = (*i).path;
1729                                         last_rr_session_dir = i;
1730                                         return result;
1731                                 }
1732                         }
1733
1734                 } while (i != last_rr_session_dir);
1735
1736         } else {
1737
1738                 /* pick FS with the most freespace (and that
1739                    seems to actually work ...)
1740                 */
1741                 
1742                 vector<space_and_path> sorted;
1743                 space_and_path_ascending_cmp cmp;
1744
1745                 sorted = session_dirs;
1746                 sort (sorted.begin(), sorted.end(), cmp);
1747                 
1748                 for (i = sorted.begin(); i != sorted.end(); ++i) {
1749                         if (create_session_directory ((*i).path)) {
1750                                 result = (*i).path;
1751                                 last_rr_session_dir = i;
1752                                 return result;
1753                         }
1754                 }
1755         }
1756
1757         return result;
1758 }
1759
1760 int
1761 Session::load_playlists (const XMLNode& node)
1762 {
1763         XMLNodeList nlist;
1764         XMLNodeConstIterator niter;
1765         boost::shared_ptr<Playlist> playlist;
1766
1767         nlist = node.children();
1768
1769         set_dirty();
1770
1771         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1772                 
1773                 if ((playlist = XMLPlaylistFactory (**niter)) == 0) {
1774                         error << _("Session: cannot create Playlist from XML description.") << endmsg;
1775                 }
1776         }
1777
1778         return 0;
1779 }
1780
1781 int
1782 Session::load_unused_playlists (const XMLNode& node)
1783 {
1784         XMLNodeList nlist;
1785         XMLNodeConstIterator niter;
1786         boost::shared_ptr<Playlist> playlist;
1787
1788         nlist = node.children();
1789
1790         set_dirty();
1791
1792         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1793                 
1794                 if ((playlist = XMLPlaylistFactory (**niter)) == 0) {
1795                         error << _("Session: cannot create Playlist from XML description.") << endmsg;
1796                         continue;
1797                 }
1798
1799                 // now manually untrack it
1800
1801                 track_playlist (false, boost::weak_ptr<Playlist> (playlist));
1802         }
1803
1804         return 0;
1805 }
1806
1807 boost::shared_ptr<Playlist>
1808 Session::XMLPlaylistFactory (const XMLNode& node)
1809 {
1810         try {
1811                 return PlaylistFactory::create (*this, node);
1812         }
1813
1814         catch (failed_constructor& err) {
1815                 return boost::shared_ptr<Playlist>();
1816         }
1817 }
1818
1819 int
1820 Session::load_named_selections (const XMLNode& node)
1821 {
1822         XMLNodeList nlist;
1823         XMLNodeConstIterator niter;
1824         NamedSelection *ns;
1825
1826         nlist = node.children();
1827
1828         set_dirty();
1829
1830         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1831                 
1832                 if ((ns = XMLNamedSelectionFactory (**niter)) == 0) {
1833                         error << _("Session: cannot create Named Selection from XML description.") << endmsg;
1834                 }
1835         }
1836
1837         return 0;
1838 }
1839
1840 NamedSelection *
1841 Session::XMLNamedSelectionFactory (const XMLNode& node)
1842 {
1843         try {
1844                 return new NamedSelection (*this, node);
1845         }
1846
1847         catch (failed_constructor& err) {
1848                 return 0;
1849         }
1850 }
1851
1852 string
1853 Session::automation_dir () const
1854 {
1855         string res = _path;
1856         res += "automation/";
1857         return res;
1858 }
1859
1860 int
1861 Session::load_bundles (const XMLNode& node)
1862 {
1863         XMLNodeList nlist = node.children();
1864         XMLNodeConstIterator niter;
1865
1866         set_dirty();
1867
1868         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1869                 if ((*niter)->name() == "InputConnection") {
1870                         add_bundle (new ARDOUR::InputBundle (**niter));
1871                 } else if ((*niter)->name() == "OutputConnection") {
1872                         add_bundle (new ARDOUR::OutputBundle (**niter));
1873                 } else {
1874                         error << string_compose(_("Unknown node \"%1\" found in Connections list from state file"), (*niter)->name()) << endmsg;
1875                         return -1;
1876                 }
1877         }
1878
1879         return 0;
1880 }                               
1881
1882 int
1883 Session::load_edit_groups (const XMLNode& node)
1884 {
1885         return load_route_groups (node, true);
1886 }
1887
1888 int
1889 Session::load_mix_groups (const XMLNode& node)
1890 {
1891         return load_route_groups (node, false);
1892 }
1893
1894 int
1895 Session::load_route_groups (const XMLNode& node, bool edit)
1896 {
1897         XMLNodeList nlist = node.children();
1898         XMLNodeConstIterator niter;
1899         RouteGroup* rg;
1900
1901         set_dirty();
1902
1903         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
1904                 if ((*niter)->name() == "RouteGroup") {
1905                         if (edit) {
1906                                 rg = add_edit_group ("");
1907                                 rg->set_state (**niter);
1908                         } else {
1909                                 rg = add_mix_group ("");
1910                                 rg->set_state (**niter);
1911                         }
1912                 }
1913         }
1914         
1915         return 0;
1916 }                               
1917
1918 void
1919 Session::auto_save()
1920 {
1921         save_state (_current_snapshot_name);
1922 }
1923
1924 RouteGroup *
1925 Session::add_edit_group (string name)
1926 {
1927         RouteGroup* rg = new RouteGroup (*this, name);
1928         edit_groups.push_back (rg);
1929         edit_group_added (rg); /* EMIT SIGNAL */
1930         set_dirty();
1931         return rg;
1932 }
1933
1934 RouteGroup *
1935 Session::add_mix_group (string name)
1936 {
1937         RouteGroup* rg = new RouteGroup (*this, name, RouteGroup::Relative);
1938         mix_groups.push_back (rg);
1939         mix_group_added (rg); /* EMIT SIGNAL */
1940         set_dirty();
1941         return rg;
1942 }
1943
1944 void
1945 Session::remove_edit_group (RouteGroup& rg)
1946 {
1947         list<RouteGroup*>::iterator i;
1948
1949         if ((i = find (edit_groups.begin(), edit_groups.end(), &rg)) != edit_groups.end()) {
1950                 (*i)->apply (&Route::drop_edit_group, this);
1951                 edit_groups.erase (i);
1952                 edit_group_removed (); /* EMIT SIGNAL */
1953         }
1954
1955         delete &rg;
1956 }
1957
1958 void
1959 Session::remove_mix_group (RouteGroup& rg)
1960 {
1961         list<RouteGroup*>::iterator i;
1962
1963         if ((i = find (mix_groups.begin(), mix_groups.end(), &rg)) != mix_groups.end()) {
1964                 (*i)->apply (&Route::drop_mix_group, this);
1965                 mix_groups.erase (i);
1966                 mix_group_removed (); /* EMIT SIGNAL */
1967         }
1968
1969         delete &rg;
1970 }
1971
1972 RouteGroup *
1973 Session::mix_group_by_name (string name)
1974 {
1975         list<RouteGroup *>::iterator i;
1976
1977         for (i = mix_groups.begin(); i != mix_groups.end(); ++i) {
1978                 if ((*i)->name() == name) {
1979                         return* i;
1980                 }
1981         }
1982         return 0;
1983 }
1984
1985 RouteGroup *
1986 Session::edit_group_by_name (string name)
1987 {
1988         list<RouteGroup *>::iterator i;
1989
1990         for (i = edit_groups.begin(); i != edit_groups.end(); ++i) {
1991                 if ((*i)->name() == name) {
1992                         return* i;
1993                 }
1994         }
1995         return 0;
1996 }
1997
1998 void
1999 Session::begin_reversible_command (const string& name)
2000 {
2001         current_trans = new UndoTransaction;
2002         current_trans->set_name (name);
2003 }
2004
2005 void
2006 Session::commit_reversible_command (Command *cmd)
2007 {
2008         struct timeval now;
2009
2010         if (cmd) {
2011                 current_trans->add_command (cmd);
2012         }
2013
2014         gettimeofday (&now, 0);
2015         current_trans->set_timestamp (now);
2016
2017         _history.add (current_trans);
2018 }
2019
2020 Session::GlobalRouteBooleanState 
2021 Session::get_global_route_boolean (bool (Route::*method)(void) const)
2022 {
2023         GlobalRouteBooleanState s;
2024         boost::shared_ptr<RouteList> r = routes.reader ();
2025
2026         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2027                 if (!(*i)->is_hidden()) {
2028                         RouteBooleanState v;
2029                         
2030                         v.first =* i;
2031                         Route* r = (*i).get();
2032                         v.second = (r->*method)();
2033                         
2034                         s.push_back (v);
2035                 }
2036         }
2037
2038         return s;
2039 }
2040
2041 Session::GlobalRouteMeterState
2042 Session::get_global_route_metering ()
2043 {
2044         GlobalRouteMeterState s;
2045         boost::shared_ptr<RouteList> r = routes.reader ();
2046
2047         for (RouteList::iterator i = r->begin(); i != r->end(); ++i) {
2048                 if (!(*i)->is_hidden()) {
2049                         RouteMeterState v;
2050                         
2051                         v.first =* i;
2052                         v.second = (*i)->meter_point();
2053                         
2054                         s.push_back (v);
2055                 }
2056         }
2057
2058         return s;
2059 }
2060
2061 void
2062 Session::set_global_route_metering (GlobalRouteMeterState s, void* arg) 
2063 {
2064         for (GlobalRouteMeterState::iterator i = s.begin(); i != s.end(); ++i) {
2065
2066                 boost::shared_ptr<Route> r = (i->first.lock());
2067
2068                 if (r) {
2069                         r->set_meter_point (i->second, arg);
2070                 }
2071         }
2072 }
2073
2074 void
2075 Session::set_global_route_boolean (GlobalRouteBooleanState s, void (Route::*method)(bool, void*), void* arg)
2076 {
2077         for (GlobalRouteBooleanState::iterator i = s.begin(); i != s.end(); ++i) {
2078
2079                 boost::shared_ptr<Route> r = (i->first.lock());
2080
2081                 if (r) {
2082                         Route* rp = r.get();
2083                         (rp->*method) (i->second, arg);
2084                 }
2085         }
2086 }
2087
2088 void
2089 Session::set_global_mute (GlobalRouteBooleanState s, void* src)
2090 {
2091         set_global_route_boolean (s, &Route::set_mute, src);
2092 }
2093
2094 void
2095 Session::set_global_solo (GlobalRouteBooleanState s, void* src)
2096 {
2097         set_global_route_boolean (s, &Route::set_solo, src);
2098 }
2099
2100 void
2101 Session::set_global_record_enable (GlobalRouteBooleanState s, void* src)
2102 {
2103         set_global_route_boolean (s, &Route::set_record_enable, src);
2104 }
2105
2106 #if 0
2107 UndoAction
2108 Session::global_mute_memento (void* src)
2109 {
2110         return sigc::bind (mem_fun (*this, &Session::set_global_mute), get_global_route_boolean (&Route::muted), src);
2111 }
2112
2113 UndoAction
2114 Session::global_metering_memento (void* src)
2115 {
2116         return sigc::bind (mem_fun (*this, &Session::set_global_route_metering), get_global_route_metering (), src);
2117 }
2118
2119 UndoAction
2120 Session::global_solo_memento (void* src)
2121 {
2122         return sigc::bind (mem_fun (*this, &Session::set_global_solo), get_global_route_boolean (&Route::soloed), src);
2123 }
2124
2125 UndoAction
2126 Session::global_record_enable_memento (void* src)
2127 {
2128         return sigc::bind (mem_fun (*this, &Session::set_global_record_enable), get_global_route_boolean (&Route::record_enabled), src);
2129 }
2130 #endif
2131
2132 static bool
2133 accept_all_non_peak_files (const string& path, void *arg)
2134 {
2135         return (path.length() > 5 && path.find (peakfile_suffix) != (path.length() - 5));
2136 }
2137
2138 static bool
2139 accept_all_state_files (const string& path, void *arg)
2140 {
2141         return (path.length() > 7 && path.find (".ardour") == (path.length() - 7));
2142 }
2143
2144 int 
2145 Session::find_all_sources (string path, set<string>& result)
2146 {
2147         XMLTree tree;
2148         XMLNode* node;
2149
2150         if (!tree.read (path)) {
2151                 return -1;
2152         }
2153
2154         if ((node = find_named_node (*tree.root(), "Sources")) == 0) {
2155                 return -2;
2156         }
2157
2158         XMLNodeList nlist;
2159         XMLNodeConstIterator niter;
2160
2161         nlist = node->children();
2162
2163         set_dirty();
2164
2165         for (niter = nlist.begin(); niter != nlist.end(); ++niter) {
2166                 
2167                 XMLProperty* prop;
2168
2169                 if ((prop = (*niter)->property (X_("name"))) == 0) {
2170                         continue;
2171                 }
2172
2173                 if (prop->value()[0] == '/') {
2174                         /* external file, ignore */
2175                         continue;
2176                 }
2177
2178                 sys::path source_path = _session_dir->sound_path ();
2179
2180                 source_path /= prop->value ();
2181
2182                 result.insert (source_path.to_string ());
2183         }
2184
2185         return 0;
2186 }
2187
2188 int
2189 Session::find_all_sources_across_snapshots (set<string>& result, bool exclude_this_snapshot)
2190 {
2191         PathScanner scanner;
2192         vector<string*>* state_files;
2193         string ripped;
2194         string this_snapshot_path;
2195
2196         result.clear ();
2197
2198         ripped = _path;
2199
2200         if (ripped[ripped.length()-1] == '/') {
2201                 ripped = ripped.substr (0, ripped.length() - 1);
2202         }
2203
2204         state_files = scanner (ripped, accept_all_state_files, (void *) 0, false, true);
2205         
2206         if (state_files == 0) {
2207                 /* impossible! */
2208                 return 0;
2209         }
2210
2211         this_snapshot_path = _path;
2212         this_snapshot_path += _current_snapshot_name;
2213         this_snapshot_path += statefile_suffix;
2214
2215         for (vector<string*>::iterator i = state_files->begin(); i != state_files->end(); ++i) {
2216
2217                 if (exclude_this_snapshot && **i == this_snapshot_path) {
2218                         continue;
2219                 }
2220
2221                 if (find_all_sources (**i, result) < 0) {
2222                         return -1;
2223                 }
2224         }
2225
2226         return 0;
2227 }
2228
2229 struct RegionCounter {
2230     typedef std::map<PBD::ID,boost::shared_ptr<AudioSource> > AudioSourceList;
2231     AudioSourceList::iterator iter;
2232     boost::shared_ptr<Region> region;
2233     uint32_t count;
2234     
2235     RegionCounter() : count (0) {}
2236 };
2237
2238 int
2239 Session::cleanup_sources (Session::cleanup_report& rep)
2240 {
2241         // FIXME: needs adaptation to midi
2242         
2243         vector<boost::shared_ptr<Source> > dead_sources;
2244         vector<boost::shared_ptr<Playlist> > playlists_tbd;
2245         PathScanner scanner;
2246         string sound_path;
2247         vector<space_and_path>::iterator i;
2248         vector<space_and_path>::iterator nexti;
2249         vector<string*>* soundfiles;
2250         vector<string> unused;
2251         set<string> all_sources;
2252         bool used;
2253         string spath;
2254         int ret = -1;
2255                 
2256         _state_of_the_state = (StateOfTheState) (_state_of_the_state | InCleanup);
2257         
2258         /* step 1: consider deleting all unused playlists */
2259
2260         for (PlaylistList::iterator x = unused_playlists.begin(); x != unused_playlists.end(); ++x) {
2261                 int status;
2262
2263                 status = AskAboutPlaylistDeletion (*x);
2264
2265                 switch (status) {
2266                 case -1:
2267                         ret = 0;
2268                         goto out;
2269                         break;
2270
2271                 case 0:
2272                         playlists_tbd.push_back (*x);
2273                         break;
2274
2275                 default:
2276                         /* leave it alone */
2277                         break;
2278                 }
2279         }
2280
2281         /* now delete any that were marked for deletion */
2282
2283         for (vector<boost::shared_ptr<Playlist> >::iterator x = playlists_tbd.begin(); x != playlists_tbd.end(); ++x) {
2284                 (*x)->drop_references ();
2285         }
2286
2287         playlists_tbd.clear ();
2288
2289         /* step 2: find all un-used sources */
2290
2291         rep.paths.clear ();
2292         rep.space = 0;
2293
2294         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ) {
2295                 
2296                 SourceMap::iterator tmp;
2297
2298                 tmp = i;
2299                 ++tmp;
2300
2301                 /* do not bother with files that are zero size, otherwise we remove the current "nascent"
2302                    capture files.
2303                 */
2304
2305                 if (!i->second->used() && i->second->length() > 0) {
2306                         dead_sources.push_back (i->second);
2307                         i->second->GoingAway();
2308                 } 
2309
2310                 i = tmp;
2311         }
2312
2313         /* build a list of all the possible sound directories for the session */
2314
2315         for (i = session_dirs.begin(); i != session_dirs.end(); ) {
2316
2317                 nexti = i;
2318                 ++nexti;
2319
2320                 SessionDirectory sdir ((*i).path);
2321                 sound_path += sdir.sound_path().to_string();
2322
2323                 if (nexti != session_dirs.end()) {
2324                         sound_path += ':';
2325                 }
2326
2327                 i = nexti;
2328         }
2329
2330         /* now do the same thing for the files that ended up in the sounds dir(s) 
2331            but are not referenced as sources in any snapshot.
2332         */
2333
2334         soundfiles = scanner (sound_path, accept_all_non_peak_files, (void *) 0, false, true);
2335
2336         if (soundfiles == 0) {
2337                 return 0;
2338         }
2339
2340         /* find all sources, but don't use this snapshot because the
2341            state file on disk still references sources we may have already
2342            dropped.
2343         */
2344         
2345         find_all_sources_across_snapshots (all_sources, true);
2346
2347         /*  add our current source list
2348          */
2349         
2350         for (SourceMap::iterator i = sources.begin(); i != sources.end(); ++i) {
2351                 boost::shared_ptr<AudioFileSource> fs;
2352                 
2353                 if ((fs = boost::dynamic_pointer_cast<AudioFileSource> (i->second)) != 0) {
2354                         all_sources.insert (fs->path());
2355                 } 
2356         }
2357
2358         char tmppath1[PATH_MAX+1];
2359         char tmppath2[PATH_MAX+1];
2360         
2361         for (vector<string*>::iterator x = soundfiles->begin(); x != soundfiles->end(); ++x) {
2362
2363                 used = false;
2364                 spath = **x;
2365
2366                 for (set<string>::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
2367
2368                         realpath(spath.c_str(), tmppath1);
2369                         realpath((*i).c_str(),  tmppath2);
2370
2371                         if (strcmp(tmppath1, tmppath2) == 0) {
2372                                 used = true;
2373                                 break;
2374                         }
2375                 }
2376
2377                 if (!used) {
2378                         unused.push_back (spath);
2379                 }
2380         }
2381
2382         /* now try to move all unused files into the "dead_sounds" directory(ies) */
2383
2384         for (vector<string>::iterator x = unused.begin(); x != unused.end(); ++x) {
2385                 struct stat statbuf;
2386
2387                 rep.paths.push_back (*x);
2388                 if (stat ((*x).c_str(), &statbuf) == 0) {
2389                         rep.space += statbuf.st_size;
2390                 }
2391
2392                 string newpath;
2393                 
2394                 /* don't move the file across filesystems, just
2395                    stick it in the `dead_sound_dir_name' directory
2396                    on whichever filesystem it was already on.
2397                 */
2398
2399                 if ((*x).find ("/sounds/") != string::npos) {
2400
2401                         /* old school, go up 1 level */
2402
2403                         newpath = Glib::path_get_dirname (*x);      // "sounds" 
2404                         newpath = Glib::path_get_dirname (newpath); // "session-name"
2405
2406                 } else {
2407
2408                         /* new school, go up 4 levels */
2409                         
2410                         newpath = Glib::path_get_dirname (*x);      // "audiofiles" 
2411                         newpath = Glib::path_get_dirname (newpath); // "session-name"
2412                         newpath = Glib::path_get_dirname (newpath); // "interchange"
2413                         newpath = Glib::path_get_dirname (newpath); // "session-dir"
2414                 }
2415
2416                 newpath += '/';
2417                 newpath += dead_sound_dir_name;
2418
2419                 if (g_mkdir_with_parents (newpath.c_str(), 0755) < 0) {
2420                         error << string_compose(_("Session: cannot create session peakfile dir \"%1\" (%2)"), newpath, strerror (errno)) << endmsg;
2421                         return -1;
2422                 }
2423
2424                 newpath += '/';
2425                 newpath += Glib::path_get_basename ((*x));
2426                 
2427                 if (access (newpath.c_str(), F_OK) == 0) {
2428                         
2429                         /* the new path already exists, try versioning */
2430                         
2431                         char buf[PATH_MAX+1];
2432                         int version = 1;
2433                         string newpath_v;
2434                         
2435                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
2436                         newpath_v = buf;
2437
2438                         while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
2439                                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
2440                                 newpath_v = buf;
2441                         }
2442                         
2443                         if (version == 999) {
2444                                 error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
2445                                                   newpath)
2446                                       << endmsg;
2447                         } else {
2448                                 newpath = newpath_v;
2449                         }
2450                         
2451                 } else {
2452                         
2453                         /* it doesn't exist, or we can't read it or something */
2454                         
2455                 }
2456
2457                 if (::rename ((*x).c_str(), newpath.c_str()) != 0) {
2458                         error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
2459                                           (*x), newpath, strerror (errno))
2460                               << endmsg;
2461                         goto out;
2462                 }
2463
2464                 /* see if there an easy to find peakfile for this file, and remove it.
2465                  */
2466
2467                 string peakpath = (*x).substr (0, (*x).find_last_of ('.'));
2468                 peakpath += peakfile_suffix;
2469
2470                 if (access (peakpath.c_str(), W_OK) == 0) {
2471                         if (::unlink (peakpath.c_str()) != 0) {
2472                                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
2473                                                   peakpath, _path, strerror (errno))
2474                                       << endmsg;
2475                                 /* try to back out */
2476                                 rename (newpath.c_str(), _path.c_str());
2477                                 goto out;
2478                         }
2479                 }
2480         }
2481
2482         ret = 0;
2483
2484         /* dump the history list */
2485
2486         _history.clear ();
2487
2488         /* save state so we don't end up a session file
2489            referring to non-existent sources.
2490         */
2491         
2492         save_state ("");
2493
2494   out:
2495         _state_of_the_state = (StateOfTheState) (_state_of_the_state & ~InCleanup);
2496         return ret;
2497 }
2498
2499 int
2500 Session::cleanup_trash_sources (Session::cleanup_report& rep)
2501 {
2502         // FIXME: needs adaptation for MIDI
2503         
2504         vector<space_and_path>::iterator i;
2505         string dead_sound_dir;
2506         struct dirent* dentry;
2507         struct stat statbuf;
2508         DIR* dead;
2509
2510         rep.paths.clear ();
2511         rep.space = 0;
2512
2513         for (i = session_dirs.begin(); i != session_dirs.end(); ++i) {
2514                 
2515                 dead_sound_dir = (*i).path;
2516                 dead_sound_dir += dead_sound_dir_name;
2517
2518                 if ((dead = opendir (dead_sound_dir.c_str())) == 0) {
2519                         continue;
2520                 }
2521
2522                 while ((dentry = readdir (dead)) != 0) {
2523
2524                         /* avoid '.' and '..' */
2525                         
2526                         if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') || 
2527                             (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
2528                                 continue;
2529                         }
2530
2531                         string fullpath;
2532
2533                         fullpath = dead_sound_dir;
2534                         fullpath += '/';
2535                         fullpath += dentry->d_name;
2536
2537                         if (stat (fullpath.c_str(), &statbuf)) {
2538                                 continue;
2539                         }
2540
2541                         if (!S_ISREG (statbuf.st_mode)) {
2542                                 continue;
2543                         }
2544
2545                         if (unlink (fullpath.c_str())) {
2546                                 error << string_compose (_("cannot remove dead sound file %1 (%2)"),
2547                                                   fullpath, strerror (errno))
2548                                       << endmsg;
2549                         }
2550
2551                         rep.paths.push_back (dentry->d_name);
2552                         rep.space += statbuf.st_size;
2553                 }
2554
2555                 closedir (dead);
2556                 
2557         }
2558
2559         return 0;
2560 }
2561
2562 void
2563 Session::set_dirty ()
2564 {
2565         bool was_dirty = dirty();
2566
2567         _state_of_the_state = StateOfTheState (_state_of_the_state | Dirty);
2568
2569         if (!was_dirty) {
2570                 DirtyChanged(); /* EMIT SIGNAL */
2571         }
2572 }
2573
2574
2575 void
2576 Session::set_clean ()
2577 {
2578         bool was_dirty = dirty();
2579         
2580         _state_of_the_state = Clean;
2581
2582         if (was_dirty) {
2583                 DirtyChanged(); /* EMIT SIGNAL */
2584         }
2585 }
2586
2587 void
2588 Session::set_deletion_in_progress ()
2589 {
2590         _state_of_the_state = StateOfTheState (_state_of_the_state | Deletion);
2591 }
2592
2593 void
2594 Session::add_controllable (boost::shared_ptr<Controllable> c)
2595 {
2596         /* this adds a controllable to the list managed by the Session.
2597            this is a subset of those managed by the Controllable class
2598            itself, and represents the only ones whose state will be saved
2599            as part of the session.
2600         */
2601
2602         Glib::Mutex::Lock lm (controllables_lock);
2603         controllables.insert (c);
2604 }
2605         
2606 struct null_deleter { void operator()(void const *) const {} };
2607
2608 void
2609 Session::remove_controllable (Controllable* c)
2610 {
2611         if (_state_of_the_state | Deletion) {
2612                 return;
2613         }
2614
2615         Glib::Mutex::Lock lm (controllables_lock);
2616
2617         Controllables::iterator x = controllables.find(
2618                  boost::shared_ptr<Controllable>(c, null_deleter()));
2619
2620         if (x != controllables.end()) {
2621                 controllables.erase (x);
2622         }
2623 }       
2624
2625 boost::shared_ptr<Controllable>
2626 Session::controllable_by_id (const PBD::ID& id)
2627 {
2628         Glib::Mutex::Lock lm (controllables_lock);
2629         
2630         for (Controllables::iterator i = controllables.begin(); i != controllables.end(); ++i) {
2631                 if ((*i)->id() == id) {
2632                         return *i;
2633                 }
2634         }
2635
2636         return boost::shared_ptr<Controllable>();
2637 }
2638
2639 void 
2640 Session::add_instant_xml (XMLNode& node)
2641 {
2642         Stateful::add_instant_xml (node, _path);
2643         Config->add_instant_xml (node);
2644 }
2645
2646 XMLNode*
2647 Session::instant_xml (const string& node_name)
2648 {
2649         return Stateful::instant_xml (node_name, _path);
2650 }
2651
2652 int 
2653 Session::save_history (string snapshot_name)
2654 {
2655     XMLTree tree;
2656     string xml_path;
2657     string bak_path;
2658
2659     tree.set_root (&_history.get_state (Config->get_saved_history_depth()));
2660
2661     if (snapshot_name.empty()) {
2662         snapshot_name = _current_snapshot_name;
2663     }
2664
2665     xml_path = _path + snapshot_name + ".history"; 
2666
2667     bak_path = xml_path + ".bak";
2668
2669     if ((access (xml_path.c_str(), F_OK) == 0) &&
2670         (rename (xml_path.c_str(), bak_path.c_str())))
2671     {
2672         error << _("could not backup old history file, current history not saved.") << endmsg;
2673         return -1;
2674     }
2675
2676     if (!tree.write (xml_path))
2677     {
2678         error << string_compose (_("history could not be saved to %1"), xml_path) << endmsg;
2679
2680         /* don't leave a corrupt file lying around if it is
2681          * possible to fix.
2682          */
2683
2684         if (unlink (xml_path.c_str())) {
2685                 error << string_compose (_("could not remove corrupt history file %1"), xml_path) << endmsg;
2686         } else {
2687                 if (rename (bak_path.c_str(), xml_path.c_str())) 
2688                 {
2689                         error << string_compose (_("could not restore history file from backup %1"), bak_path) << endmsg;
2690                 }
2691         }
2692
2693         return -1;
2694     }
2695
2696     return 0;
2697 }
2698
2699 int
2700 Session::restore_history (string snapshot_name)
2701 {
2702     XMLTree tree;
2703     string xmlpath;
2704
2705     if (snapshot_name.empty()) {
2706             snapshot_name = _current_snapshot_name;
2707     }
2708
2709     /* read xml */
2710     xmlpath = _path + snapshot_name + ".history";
2711     cerr << string_compose(_("Loading history from '%1'."), xmlpath) << endmsg;
2712
2713     if (access (xmlpath.c_str(), F_OK)) {
2714             info << string_compose (_("%1: no history file \"%2\" for this session."), _name, xmlpath) << endmsg;
2715             return 1;
2716     }
2717
2718     if (!tree.read (xmlpath)) {
2719             error << string_compose (_("Could not understand session history file \"%1\""), xmlpath) << endmsg;
2720             return -1;
2721     }
2722
2723     /* replace history */
2724     _history.clear();
2725
2726     for (XMLNodeConstIterator it  = tree.root()->children().begin(); it != tree.root()->children().end(); it++) {
2727             
2728             XMLNode *t = *it;
2729             UndoTransaction* ut = new UndoTransaction ();
2730             struct timeval tv;
2731             
2732             ut->set_name(t->property("name")->value());
2733             stringstream ss(t->property("tv_sec")->value());
2734             ss >> tv.tv_sec;
2735             ss.str(t->property("tv_usec")->value());
2736             ss >> tv.tv_usec;
2737             ut->set_timestamp(tv);
2738             
2739             for (XMLNodeConstIterator child_it  = t->children().begin();
2740                  child_it != t->children().end();
2741                  child_it++)
2742             {
2743                     XMLNode *n = *child_it;
2744                     Command *c;
2745         
2746                     if (n->name() == "MementoCommand" ||
2747                         n->name() == "MementoUndoCommand" ||
2748                         n->name() == "MementoRedoCommand") {
2749
2750                             if ((c = memento_command_factory(n))) {
2751                                     ut->add_command(c);
2752                             }
2753                             
2754                     } else if (n->name() == X_("GlobalRouteStateCommand")) {
2755
2756                             if ((c = global_state_command_factory (*n))) {
2757                                     ut->add_command (c);
2758                             }
2759                             
2760                     } else {
2761
2762                             error << string_compose(_("Couldn't figure out how to make a Command out of a %1 XMLNode."), n->name()) << endmsg;
2763                     }
2764             }
2765
2766             _history.add (ut);
2767     }
2768
2769     return 0;
2770 }
2771
2772 void
2773 Session::config_changed (const char* parameter_name)
2774 {
2775 #define PARAM_IS(x) (!strcmp (parameter_name, (x)))
2776
2777         if (PARAM_IS ("seamless-loop")) {
2778                 
2779         } else if (PARAM_IS ("rf-speed")) {
2780                 
2781         } else if (PARAM_IS ("auto-loop")) {
2782                 
2783         } else if (PARAM_IS ("auto-input")) {
2784
2785                 if (Config->get_monitoring_model() == HardwareMonitoring && transport_rolling()) {
2786                         /* auto-input only makes a difference if we're rolling */
2787                         
2788                         boost::shared_ptr<DiskstreamList> dsl = diskstreams.reader();
2789                         
2790                         for (DiskstreamList::iterator i = dsl->begin(); i != dsl->end(); ++i) {
2791                                 if ((*i)->record_enabled ()) {
2792                                         (*i)->monitor_input (!Config->get_auto_input());
2793                                 }
2794                         }
2795                 }
2796
2797         } else if (PARAM_IS ("punch-in")) {
2798
2799                 Location* location;
2800                 
2801                 if ((location = _locations.auto_punch_location()) != 0) {
2802                         
2803                         if (Config->get_punch_in ()) {
2804                                 replace_event (Event::PunchIn, location->start());
2805                         } else {
2806                                 remove_event (location->start(), Event::PunchIn);
2807                         }
2808                 }
2809                 
2810         } else if (PARAM_IS ("punch-out")) {
2811
2812                 Location* location;
2813                 
2814                 if ((location = _locations.auto_punch_location()) != 0) {
2815                         
2816                         if (Config->get_punch_out()) {
2817                                 replace_event (Event::PunchOut, location->end());
2818                         } else {
2819                                 clear_events (Event::PunchOut);
2820                         }
2821                 }
2822
2823         } else if (PARAM_IS ("edit-mode")) {
2824
2825                 Glib::Mutex::Lock lm (playlist_lock);
2826                 
2827                 for (PlaylistList::iterator i = playlists.begin(); i != playlists.end(); ++i) {
2828                         (*i)->set_edit_mode (Config->get_edit_mode ());
2829                 }
2830
2831         } else if (PARAM_IS ("use-video-sync")) {
2832
2833                 waiting_for_sync_offset = Config->get_use_video_sync();
2834
2835         } else if (PARAM_IS ("mmc-control")) {
2836
2837                 //poke_midi_thread ();
2838
2839         } else if (PARAM_IS ("mmc-device-id") || PARAM_IS ("mmc-receive-id")) {
2840
2841                 if (mmc) {
2842                         mmc->set_receive_device_id (Config->get_mmc_receive_device_id());
2843                 }
2844
2845         } else if (PARAM_IS ("mmc-send-id")) {
2846
2847                 if (mmc) {
2848                         mmc->set_send_device_id (Config->get_mmc_send_device_id());
2849                 }
2850
2851         } else if (PARAM_IS ("midi-control")) {
2852                 
2853                 //poke_midi_thread ();
2854
2855         } else if (PARAM_IS ("raid-path")) {
2856
2857                 setup_raid_path (Config->get_raid_path());
2858
2859         } else if (PARAM_IS ("smpte-format")) {
2860
2861                 sync_time_vars ();
2862
2863         } else if (PARAM_IS ("video-pullup")) {
2864
2865                 sync_time_vars ();
2866
2867         } else if (PARAM_IS ("seamless-loop")) {
2868
2869                 if (play_loop && transport_rolling()) {
2870                         // to reset diskstreams etc
2871                         request_play_loop (true);
2872                 }
2873
2874         } else if (PARAM_IS ("rf-speed")) {
2875
2876                 cumulative_rf_motion = 0;
2877                 reset_rf_scale (0);
2878
2879         } else if (PARAM_IS ("click-sound")) {
2880
2881                 setup_click_sounds (1);
2882
2883         } else if (PARAM_IS ("click-emphasis-sound")) {
2884
2885                 setup_click_sounds (-1);
2886
2887         } else if (PARAM_IS ("clicking")) {
2888
2889                 if (Config->get_clicking()) {
2890                         if (_click_io && click_data) { // don't require emphasis data
2891                                 _clicking = true;
2892                         }
2893                 } else {
2894                         _clicking = false;
2895                 }
2896
2897         } else if (PARAM_IS ("send-mtc")) {
2898                 
2899                 /* only set the internal flag if we have
2900                    a port.
2901                 */
2902                 
2903                 if (_mtc_port != 0) {
2904                         session_send_mtc = Config->get_send_mtc();
2905                         if (session_send_mtc) {
2906                                 /* mark us ready to send */
2907                                 next_quarter_frame_to_send = 0;
2908                         }
2909                 } else {
2910                         session_send_mtc = false;
2911                 }
2912
2913         } else if (PARAM_IS ("send-mmc")) {
2914                 
2915                 /* only set the internal flag if we have
2916                    a port.
2917                 */
2918                 
2919                 if (_mmc_port != 0) {
2920                         session_send_mmc = Config->get_send_mmc();
2921                 } else {
2922                         mmc = 0;
2923                         session_send_mmc = false; 
2924                 }
2925
2926         } else if (PARAM_IS ("midi-feedback")) {
2927                 
2928                 /* only set the internal flag if we have
2929                    a port.
2930                 */
2931                 
2932                 if (_mtc_port != 0) {
2933                         session_midi_feedback = Config->get_midi_feedback();
2934                 }
2935
2936         } else if (PARAM_IS ("jack-time-master")) {
2937
2938                 engine().reset_timebase ();
2939
2940         } else if (PARAM_IS ("native-file-header-format")) {
2941
2942                 if (!first_file_header_format_reset) {
2943                         reset_native_file_format ();
2944                 }
2945
2946                 first_file_header_format_reset = false;
2947
2948         } else if (PARAM_IS ("native-file-data-format")) {
2949
2950                 if (!first_file_data_format_reset) {
2951                         reset_native_file_format ();
2952                 }
2953
2954                 first_file_data_format_reset = false;
2955
2956         } else if (PARAM_IS ("slave-source")) {
2957                 set_slave_source (Config->get_slave_source());
2958         } else if (PARAM_IS ("remote-model")) {
2959                 set_remote_control_ids ();
2960         }  else if (PARAM_IS ("denormal-model")) {
2961                 setup_fpu ();
2962         }
2963
2964         set_dirty ();
2965                    
2966 #undef PARAM_IS
2967
2968 }