2 Copyright (C) 2006 Paul Davis
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.
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.
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.
24 #include <stdio.h> // for rename(), sigh
29 #include <pbd/convert.h>
30 #include <pbd/basename.h>
31 #include <pbd/mountpoint.h>
32 #include <pbd/stl_delete.h>
33 #include <pbd/strsplit.h>
34 #include <pbd/shortpath.h>
35 #include <pbd/enumwriter.h>
39 #include <glibmm/miscutils.h>
40 #include <glibmm/fileutils.h>
41 #include <glibmm/thread.h>
43 #include <ardour/audiofilesource.h>
44 #include <ardour/sndfile_helpers.h>
45 #include <ardour/sndfilesource.h>
46 #include <ardour/session.h>
47 #include <ardour/session_directory.h>
48 #include <ardour/source_factory.h>
49 #include <ardour/filename_extensions.h>
51 // if these headers come before sigc++ is included
52 // the parser throws ObjC++ errors. (nil is a keyword)
54 #include <ardour/coreaudiosource.h>
55 #include <AudioToolbox/ExtendedAudioFile.h>
56 #include <AudioToolbox/AudioFormat.h>
57 #endif // HAVE_COREAUDIO
61 using namespace ARDOUR;
65 ustring AudioFileSource::peak_dir = "";
66 ustring AudioFileSource::search_path;
68 sigc::signal<void> AudioFileSource::HeaderPositionOffsetChanged;
69 uint64_t AudioFileSource::header_position_offset = 0;
71 /* XXX maybe this too */
72 char AudioFileSource::bwf_serial_number[13] = "000000000000";
74 struct SizedSampleBuffer {
78 SizedSampleBuffer (nframes_t sz) : size (sz) {
79 buf = new Sample[size];
82 ~SizedSampleBuffer() {
87 Glib::StaticPrivate<SizedSampleBuffer> thread_interleave_buffer = GLIBMM_STATIC_PRIVATE_INIT;
89 /** Constructor used for existing internal-to-session files. File must exist. */
90 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags)
91 : AudioSource (s, path), _flags (flags),
94 _is_embedded = AudioFileSource::determine_embeddedness (path);
96 if (init (path, true)) {
97 throw failed_constructor ();
102 /** Constructor used for new internal-to-session files. File cannot exist. */
103 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags, SampleFormat samp_format, HeaderFormat hdr_format)
104 : AudioSource (s, path), _flags (flags),
107 _is_embedded = false;
109 if (init (path, false)) {
110 throw failed_constructor ();
114 /** Constructor used for existing internal-to-session files. File must exist. */
115 AudioFileSource::AudioFileSource (Session& s, const XMLNode& node, bool must_exist)
116 : AudioSource (s, node), _flags (Flag (Writable|CanRename))
117 /* _channel is set in set_state() or init() */
119 if (set_state (node)) {
120 throw failed_constructor ();
125 if (init (foo, must_exist)) {
126 throw failed_constructor ();
130 AudioFileSource::~AudioFileSource ()
133 unlink (_path.c_str());
134 unlink (peakpath.c_str());
139 AudioFileSource::determine_embeddedness (ustring path)
141 return (path.find("/") == 0);
145 AudioFileSource::removable () const
147 return (_flags & Removable) && ((_flags & RemoveAtDestroy) || ((_flags & RemovableIfEmpty) && length() == 0));
151 AudioFileSource::init (ustring pathstr, bool must_exist)
154 timeline_position = 0;
155 _peaks_built = false;
157 if (!find (pathstr, must_exist, file_is_new, _channel)) {
158 throw non_existent_source ();
161 if (file_is_new && must_exist) {
170 AudioFileSource::peak_path (ustring audio_path)
174 base = PBD::basename_nosuffix (audio_path);
176 base += (char) ('A' + _channel);
178 return _session.peak_path (base);
182 AudioFileSource::find_broken_peakfile (ustring peak_path, ustring audio_path)
186 /* check for the broken location in use by 2.0 for several months */
188 str = broken_peak_path (audio_path);
190 if (Glib::file_test (str, Glib::FILE_TEST_EXISTS)) {
194 /* it would be nice to rename it but the nature of
195 the bug means that we can't reliably use it.
201 /* all native files are mono, so we can just rename
204 ::rename (str.c_str(), peak_path.c_str());
208 /* Nasty band-aid for older sessions that were created before we
209 used libsndfile for all audio files.
213 str = old_peak_path (audio_path);
214 if (Glib::file_test (str, Glib::FILE_TEST_EXISTS)) {
223 AudioFileSource::broken_peak_path (ustring audio_path)
225 return _session.peak_path (audio_path);
229 AudioFileSource::old_peak_path (ustring audio_path)
231 /* XXX hardly bombproof! fix me */
233 struct stat stat_file;
234 struct stat stat_mount;
236 ustring mp = mountpoint (audio_path);
238 stat (audio_path.c_str(), &stat_file);
239 stat (mp.c_str(), &stat_mount);
243 snprintf (buf, sizeof (buf), "%u-%u-%d.peak", stat_mount.st_ino, stat_file.st_ino, _channel);
245 snprintf (buf, sizeof (buf), "%ld-%ld-%d.peak", stat_mount.st_ino, stat_file.st_ino, _channel);
248 ustring res = peak_dir;
250 res += peakfile_suffix;
256 AudioFileSource::get_soundfile_info (ustring path, SoundFileInfo& _info, string& error_msg)
258 #ifdef HAVE_COREAUDIO
259 if (CoreAudioSource::get_soundfile_info (path, _info, error_msg) == 0) {
262 #endif // HAVE_COREAUDIO
264 if (SndFileSource::get_soundfile_info (path, _info, error_msg) != 0) {
272 AudioFileSource::get_state ()
274 XMLNode& root (AudioSource::get_state());
276 root.add_property (X_("flags"), enum_2_string (_flags));
277 snprintf (buf, sizeof (buf), "%u", _channel);
278 root.add_property (X_("channel"), buf);
283 AudioFileSource::set_state (const XMLNode& node)
285 const XMLProperty* prop;
287 if (AudioSource::set_state (node)) {
291 if ((prop = node.property (X_("flags"))) != 0) {
292 _flags = Flag (string_2_enum (prop->value(), _flags));
298 if ((prop = node.property (X_("channel"))) != 0) {
299 _channel = atoi (prop->value());
304 if ((prop = node.property (X_("name"))) != 0) {
305 _is_embedded = AudioFileSource::determine_embeddedness (prop->value());
307 _is_embedded = false;
310 if ((prop = node.property (X_("destructive"))) != 0) {
311 /* old style, from the period when we had DestructiveFileSource */
312 _flags = Flag (_flags | Destructive);
319 AudioFileSource::mark_for_remove ()
321 // This operation is not allowed for sources for destructive tracks or embedded files.
322 // Fortunately mark_for_remove() is never called for embedded files. This function
323 // must be fixed if that ever happens.
324 if (_flags & Destructive) {
328 _flags = Flag (_flags | Removable | RemoveAtDestroy);
332 AudioFileSource::mark_streaming_write_completed ()
338 /* XXX notice that we're readers of _peaks_built
339 but we must hold a solid lock on PeaksReady.
342 Glib::Mutex::Lock lm (_lock);
345 PeaksReady (); /* EMIT SIGNAL */
350 AudioFileSource::mark_take (ustring id)
358 AudioFileSource::move_to_trash (const ustring& trash_dir_name)
361 cerr << "tried to move an embedded region to trash" << endl;
369 /* don't move the file across filesystems, just stick it in the
370 trash_dir_name directory on whichever filesystem it was already on
374 newpath = Glib::path_get_dirname (_path);
375 newpath = Glib::path_get_dirname (newpath);
377 newpath += string("/") + trash_dir_name + "/";
378 newpath += Glib::path_get_basename (_path);
380 /* the new path already exists, try versioning */
381 if (access (newpath.c_str(), F_OK) == 0) {
382 char buf[PATH_MAX+1];
386 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
389 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
390 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
394 if (version == 999) {
395 PBD::error << string_compose (
396 _("there are already 1000 files with names like %1; versioning discontinued"),
404 if (::rename (_path.c_str(), newpath.c_str()) != 0) {
405 PBD::error << string_compose (
406 _("cannot rename audio file source from %1 to %2 (%3)"),
407 _path, newpath, strerror (errno)) << endmsg;
411 if (::unlink (peakpath.c_str()) != 0) {
412 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
413 peakpath, _path, strerror (errno))
415 /* try to back out */
416 rename (newpath.c_str(), _path.c_str());
423 /* file can not be removed twice, since the operation is not idempotent */
424 _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
430 AudioFileSource::find (ustring& pathstr, bool must_exist, bool& isnew, uint16_t& chan)
432 ustring::size_type pos;
437 if (pathstr[0] != '/') {
439 /* non-absolute pathname: find pathstr in search path */
441 vector<ustring> dirs;
446 if (search_path.length() == 0) {
447 error << _("FileSource: search path not set") << endmsg;
451 split (search_path, dirs, ':');
455 for (vector<ustring>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
457 if (fullpath[fullpath.length()-1] != '/') {
463 /* i (paul) made a nasty design error by using ':' as a special character in
464 Ardour 0.99 .. this hack tries to make things sort of work.
467 if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
469 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
471 /* its a real file, no problem */
480 /* might be an older session using file:channel syntax. see if the version
481 without the :suffix exists
484 ustring shorter = pathstr.substr (0, pos);
487 if (fullpath[fullpath.length()-1] != '/') {
493 if (Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
494 chan = atoi (pathstr.substr (pos+1));
502 /* new derived file (e.g. for timefx) being created in a newer session */
509 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
518 error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, search_path) << endmsg;
521 } else if (cnt == 0) {
524 error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, search_path) << endmsg;
531 /* Current find() is unable to parse relative path names to yet non-existant
532 sources. QuickFix(tm) */
533 if (keeppath == "") {
535 error << "AudioFileSource::find(), keeppath = \"\", but the file must exist" << endl;
547 /* external files and/or very very old style sessions include full paths */
549 /* ugh, handle ':' situation */
551 if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
553 ustring shorter = pathstr.substr (0, pos);
555 if (Glib::file_test (shorter, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
556 chan = atoi (pathstr.substr (pos+1));
566 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
569 if (!Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
571 /* file does not exist or we cannot read it */
574 error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
578 if (errno != ENOENT) {
579 error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
602 AudioFileSource::set_search_path (ustring p)
608 AudioFileSource::set_header_position_offset (nframes_t offset)
610 header_position_offset = offset;
611 HeaderPositionOffsetChanged ();
615 AudioFileSource::set_timeline_position (int64_t pos)
617 timeline_position = pos;
621 AudioFileSource::set_allow_remove_if_empty (bool yn)
628 _flags = Flag (_flags | RemovableIfEmpty);
630 _flags = Flag (_flags & ~RemovableIfEmpty);
635 AudioFileSource::set_source_name (ustring newname, bool destructive)
637 Glib::Mutex::Lock lm (_lock);
638 ustring oldpath = _path;
639 ustring newpath = Session::change_audio_path_by_name (oldpath, _name, newname, destructive);
641 if (newpath.empty()) {
642 error << string_compose (_("programming error: %1"), "cannot generate a changed audio path") << endmsg;
646 // Test whether newpath exists, if yes notify the user but continue.
647 if (access(newpath.c_str(),F_OK) == 0) {
648 error << _("Programming error! Ardour tried to rename a file over another file! It's safe to continue working, but please report this to the developers.") << endmsg;
652 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
653 error << string_compose (_("cannot rename audio file %1 to %2"), _name, newpath) << endmsg;
657 _name = Glib::path_get_basename (newpath);
660 return rename_peakfile (peak_path (_path));
664 AudioFileSource::is_empty (Session& s, ustring path)
669 if (!get_soundfile_info (path, info, err)) {
670 /* dangerous: we can't get info, so assume that its not empty */
674 return info.length == 0;
678 AudioFileSource::setup_peakfile ()
680 if (!(_flags & NoPeakFile)) {
681 return initialize_peakfile (file_is_new, _path);
688 AudioFileSource::safe_file_extension(ustring file)
690 const char* suffixes[] = {
709 #ifdef HAVE_COREAUDIO
713 #endif // HAVE_COREAUDIO
716 for (size_t n = 0; n < sizeof(suffixes)/sizeof(suffixes[0]); ++n) {
717 if (file.rfind (suffixes[n]) == file.length() - strlen (suffixes[n])) {
726 AudioFileSource::mark_immutable ()
728 /* destructive sources stay writable, and their other flags don't
732 if (!(_flags & Destructive)) {
733 _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
739 AudioFileSource::get_interleave_buffer (nframes_t size)
741 SizedSampleBuffer* ssb;
743 if ((ssb = thread_interleave_buffer.get()) == 0) {
744 ssb = new SizedSampleBuffer (size);
745 thread_interleave_buffer.set (ssb);
748 if (ssb->size < size) {
749 ssb = new SizedSampleBuffer (size);
750 thread_interleave_buffer.set (ssb);