Use sys::path and SessionDirectory in Session::create_session_file_from_template...
[ardour.git] / libs / ardour / audiofilesource.cc
1 /*
2     Copyright (C) 2006 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <vector>
21
22 #include <sys/time.h>
23 #include <sys/stat.h>
24 #include <unistd.h>
25 #include <fcntl.h>
26 #include <errno.h>
27
28 #include <pbd/mountpoint.h>
29 #include <pbd/pathscanner.h>
30 #include <pbd/stl_delete.h>
31 #include <pbd/strsplit.h>
32 #include <pbd/shortpath.h>
33 #include <pbd/enumwriter.h>
34
35 #include <sndfile.h>
36
37 #include <glibmm/miscutils.h>
38 #include <glibmm/fileutils.h>
39
40 #include <ardour/audiofilesource.h>
41 #include <ardour/sndfile_helpers.h>
42 #include <ardour/sndfilesource.h>
43 #include <ardour/session.h>
44 #include <ardour/source_factory.h>
45 #include <ardour/filename_extensions.h>
46
47 // if these headers come before sigc++ is included
48 // the parser throws ObjC++ errors. (nil is a keyword)
49 #ifdef HAVE_COREAUDIO 
50 #include <ardour/coreaudiosource.h>
51 #include <AudioToolbox/ExtendedAudioFile.h>
52 #include <AudioToolbox/AudioFormat.h>
53 #endif // HAVE_COREAUDIO
54
55 #include "i18n.h"
56
57 using namespace ARDOUR;
58 using namespace PBD;
59 using namespace Glib;
60
61 ustring AudioFileSource::peak_dir = "";
62 ustring AudioFileSource::search_path;
63
64 sigc::signal<void> AudioFileSource::HeaderPositionOffsetChanged;
65 uint64_t           AudioFileSource::header_position_offset = 0;
66
67 /* XXX maybe this too */
68 char   AudioFileSource::bwf_serial_number[13] = "000000000000";
69
70 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags)
71         : AudioSource (s, path), _flags (flags),
72           _channel (0)
73 {
74         /* constructor used for existing external to session files. file must exist already */
75         _is_embedded = AudioFileSource::determine_embeddedness (path);
76
77         if (init (path, true)) {
78                 throw failed_constructor ();
79         }
80
81 }
82
83 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags, SampleFormat samp_format, HeaderFormat hdr_format)
84         : AudioSource (s, path), _flags (flags),
85           _channel (0)
86 {
87         /* constructor used for new internal-to-session files. file cannot exist */
88         _is_embedded = false;
89
90         if (init (path, false)) {
91                 throw failed_constructor ();
92         }
93 }
94
95 AudioFileSource::AudioFileSource (Session& s, const XMLNode& node, bool must_exist)
96         : AudioSource (s, node), _flags (Flag (Writable|CanRename))
97           /* _channel is set in set_state() or init() */
98 {
99         /* constructor used for existing internal-to-session files. file must exist */
100
101         if (set_state (node)) {
102                 throw failed_constructor ();
103         }
104
105         string foo = _name;
106         
107         if (init (foo, must_exist)) {
108                 throw failed_constructor ();
109         }
110 }
111
112 AudioFileSource::~AudioFileSource ()
113 {
114         if (removable()) {
115                 unlink (_path.c_str());
116                 unlink (peakpath.c_str());
117         }
118 }
119
120 bool
121 AudioFileSource::determine_embeddedness (ustring path)
122 {
123         return (path.find("/") == 0);
124 }
125
126 bool
127 AudioFileSource::removable () const
128 {
129         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || ((_flags & RemovableIfEmpty) && length() == 0));
130 }
131
132 int
133 AudioFileSource::init (ustring pathstr, bool must_exist)
134 {
135         bool is_new = false;
136
137         _length = 0;
138         timeline_position = 0;
139         _peaks_built = false;
140         file_is_new = false;
141
142         if (!find (pathstr, must_exist, is_new, _channel)) {
143                 throw non_existent_source ();
144         }
145
146         if (is_new && must_exist) {
147                 return -1;
148         }
149
150         return 0;
151 }
152
153
154 ustring
155 AudioFileSource::peak_path (ustring audio_path)
156 {
157         return _session.peak_path_from_audio_path (audio_path);
158 }
159
160 ustring
161 AudioFileSource::old_peak_path (ustring audio_path)
162 {
163         /* XXX hardly bombproof! fix me */
164
165         struct stat stat_file;
166         struct stat stat_mount;
167
168         ustring mp = mountpoint (audio_path);
169
170         stat (audio_path.c_str(), &stat_file);
171         stat (mp.c_str(), &stat_mount);
172
173         char buf[32];
174 #ifdef __APPLE__
175         snprintf (buf, sizeof (buf), "%u-%u-%d", stat_mount.st_ino, stat_file.st_ino, _channel);
176 #else
177         snprintf (buf, sizeof (buf), "%ld-%ld-%d", stat_mount.st_ino, stat_file.st_ino, _channel);
178 #endif
179
180         ustring res = peak_dir;
181         res += buf;
182         res += peakfile_suffix;
183
184         return res;
185 }
186
187 bool
188 AudioFileSource::get_soundfile_info (ustring path, SoundFileInfo& _info, string& error_msg)
189 {
190 #ifdef HAVE_COREAUDIO
191         if (CoreAudioSource::get_soundfile_info (path, _info, error_msg) == 0) {
192                 return true;
193         }
194 #endif // HAVE_COREAUDIO
195
196         if (SndFileSource::get_soundfile_info (path, _info, error_msg) != 0) {
197                 return true;
198         }
199
200         return false;
201 }
202
203 XMLNode&
204 AudioFileSource::get_state ()
205 {
206         XMLNode& root (AudioSource::get_state());
207         char buf[32];
208         root.add_property (X_("flags"), enum_2_string (_flags));
209         snprintf (buf, sizeof (buf), "%u", _channel);
210         root.add_property (X_("channel"), buf);
211         return root;
212 }
213
214 int
215 AudioFileSource::set_state (const XMLNode& node)
216 {
217         const XMLProperty* prop;
218
219         if (AudioSource::set_state (node)) {
220                 return -1;
221         }
222
223         if ((prop = node.property (X_("flags"))) != 0) {
224                 _flags = Flag (string_2_enum (prop->value(), _flags));
225         } else {
226                 _flags = Flag (0);
227
228         }
229
230         if ((prop = node.property (X_("channel"))) != 0) {
231                 _channel = atoi (prop->value().c_str());
232         } else {
233                 _channel = 0;
234         }
235
236         if ((prop = node.property (X_("name"))) != 0) {
237                 _is_embedded = AudioFileSource::determine_embeddedness (prop->value());
238         } else {
239                 _is_embedded = false;
240         }
241
242         if ((prop = node.property (X_("destructive"))) != 0) {
243                 /* old style, from the period when we had DestructiveFileSource */
244                 _flags = Flag (_flags | Destructive);
245         }
246
247         return 0;
248 }
249
250 void
251 AudioFileSource::mark_for_remove ()
252 {
253         // This operation is not allowed for sources for destructive tracks or embedded files.
254         // Fortunately mark_for_remove() is never called for embedded files. This function
255         // must be fixed if that ever happens.
256         if (_flags & Destructive) {
257                 return;
258         }
259
260         _flags = Flag (_flags | Removable | RemoveAtDestroy);
261 }
262
263 void
264 AudioFileSource::mark_streaming_write_completed ()
265 {
266         if (!writable()) {
267                 return;
268         }
269
270         Glib::Mutex::Lock lm (_lock);
271
272         if (_peaks_built) {
273                 PeaksReady (); /* EMIT SIGNAL */
274         }
275 }
276
277 void
278 AudioFileSource::mark_take (ustring id)
279 {
280         if (writable()) {
281                 _take_id = id;
282         }
283 }
284
285 int
286 AudioFileSource::move_to_trash (const ustring& trash_dir_name)
287 {
288         if (is_embedded()) {
289                 cerr << "tried to move an embedded region to trash" << endl;
290                 return -1;
291         }
292
293         ustring newpath;
294
295         if (!writable()) {
296                 return -1;
297         }
298
299         /* don't move the file across filesystems, just
300            stick it in the `trash_dir_name' directory
301            on whichever filesystem it was already on.
302         */
303         
304         newpath = Glib::path_get_dirname (_path);
305         newpath = Glib::path_get_dirname (newpath); 
306
307         cerr << "from " << _path << " dead dir looks like " << newpath << endl;
308
309         newpath += '/';
310         newpath += trash_dir_name;
311         newpath += '/';
312         newpath += Glib::path_get_basename (_path);
313
314         if (access (newpath.c_str(), F_OK) == 0) {
315
316                 /* the new path already exists, try versioning */
317                 
318                 char buf[PATH_MAX+1];
319                 int version = 1;
320                 ustring newpath_v;
321
322                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
323                 newpath_v = buf;
324
325                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
326                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
327                         newpath_v = buf;
328                 }
329                 
330                 if (version == 999) {
331                         error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
332                                           newpath)
333                               << endmsg;
334                 } else {
335                         newpath = newpath_v;
336                 }
337
338         } else {
339
340                 /* it doesn't exist, or we can't read it or something */
341
342         }
343
344         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
345                 error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
346                                   _path, newpath, strerror (errno))
347                       << endmsg;
348                 return -1;
349         }
350
351         if (::unlink (peakpath.c_str()) != 0) {
352                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
353                                   peakpath, _path, strerror (errno))
354                       << endmsg;
355                 /* try to back out */
356                 rename (newpath.c_str(), _path.c_str());
357                 return -1;
358         }
359             
360         _path = newpath;
361         peakpath = "";
362         
363         /* file can not be removed twice, since the operation is not idempotent */
364
365         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
366
367         return 0;
368 }
369
370 bool
371 AudioFileSource::find (ustring& pathstr, bool must_exist, bool& isnew, uint16_t& chan)
372 {
373         ustring::size_type pos;
374         bool ret = false;
375
376         isnew = false;
377
378         if (pathstr[0] != '/') {
379
380                 /* non-absolute pathname: find pathstr in search path */
381
382                 vector<ustring> dirs;
383                 int cnt;
384                 ustring fullpath;
385                 ustring keeppath;
386
387                 if (search_path.length() == 0) {
388                         error << _("FileSource: search path not set") << endmsg;
389                         goto out;
390                 }
391
392                 split (search_path, dirs, ':');
393
394                 cnt = 0;
395                 
396                 for (vector<ustring>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
397
398                         fullpath = *i;
399                         if (fullpath[fullpath.length()-1] != '/') {
400                                 fullpath += '/';
401                         }
402
403                         fullpath += pathstr;
404
405                         /* i (paul) made a nasty design error by using ':' as a special character in
406                            Ardour 0.99 .. this hack tries to make things sort of work.
407                         */
408                         
409                         if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
410                                 
411                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
412
413                                         /* its a real file, no problem */
414                                         
415                                         keeppath = fullpath;
416                                         ++cnt;
417
418                                 } else {
419                                         
420                                         if (must_exist) {
421                                                 
422                                                 /* might be an older session using file:channel syntax. see if the version
423                                                    without the :suffix exists
424                                                  */
425                                                 
426                                                 ustring shorter = pathstr.substr (0, pos);
427                                                 fullpath = *i;
428
429                                                 if (fullpath[fullpath.length()-1] != '/') {
430                                                         fullpath += '/';
431                                                 }
432
433                                                 fullpath += shorter;
434
435                                                 if (Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
436                                                         chan = atoi (pathstr.substr (pos+1).c_str());
437                                                         pathstr = shorter;
438                                                         keeppath = fullpath;
439                                                         ++cnt;
440                                                 } 
441                                                 
442                                         } else {
443                                                 
444                                                 /* new derived file (e.g. for timefx) being created in a newer session */
445                                                 
446                                         }
447                                 }
448
449                         } else {
450
451                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
452                                         keeppath = fullpath;
453                                         ++cnt;
454                                 } 
455                         }
456                 }
457
458                 if (cnt > 1) {
459
460                         error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, search_path) << endmsg;
461                         goto out;
462
463                 } else if (cnt == 0) {
464
465                         if (must_exist) {
466                                 error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, search_path) << endmsg;
467                                 goto out;
468                         } else {
469                                 isnew = true;
470                         }
471                 }
472
473                 _name = pathstr;
474                 _path = keeppath;
475                 ret = true;
476
477         } else {
478                 
479                 /* external files and/or very very old style sessions include full paths */
480
481                 /* ugh, handle ':' situation */
482
483                 if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
484                         
485                         ustring shorter = pathstr.substr (0, pos);
486
487                         if (Glib::file_test (shorter, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
488                                 chan = atoi (pathstr.substr (pos+1).c_str());
489                                 pathstr = shorter;
490                         }
491                 }
492                 
493                 _path = pathstr;
494
495                 if (is_embedded()) {
496                         _name = pathstr;
497                 } else {
498                         _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
499                 }
500
501                 if (!Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
502
503                         /* file does not exist or we cannot read it */
504                         
505                         if (must_exist) {
506                                 error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
507                                 goto out;
508                         }
509                         
510                         if (errno != ENOENT) {
511                                 error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
512                                 goto out;
513                         }
514                         
515                         /* a new file */
516
517                         isnew = true;
518                         ret = true;
519
520                 } else {
521                         
522                         /* already exists */
523
524                         ret = true;
525
526                 }
527         }
528         
529   out:
530         return ret;
531 }
532
533 void
534 AudioFileSource::set_search_path (ustring p)
535 {
536         search_path = p;
537 }
538
539 void
540 AudioFileSource::set_header_position_offset (nframes_t offset)
541 {
542         header_position_offset = offset;
543         HeaderPositionOffsetChanged ();
544 }
545
546 void 
547 AudioFileSource::handle_header_position_change ()
548 {
549         if (writable()) {
550                 set_header_timeline_position ();
551                 flush_header ();
552         }
553 }
554
555 void
556 AudioFileSource::set_timeline_position (int64_t pos)
557 {
558         timeline_position = pos;
559 }
560
561 void
562 AudioFileSource::set_allow_remove_if_empty (bool yn)
563 {
564         if (!writable()) {
565                 return;
566         }
567
568         if (yn) {
569                 _flags = Flag (_flags | RemovableIfEmpty);
570         } else {
571                 _flags = Flag (_flags & ~RemovableIfEmpty);
572         }
573 }
574
575 int
576 AudioFileSource::set_source_name (ustring newname, bool destructive)
577 {
578         Glib::Mutex::Lock lm (_lock);
579         ustring oldpath = _path;
580         ustring newpath = Session::change_audio_path_by_name (oldpath, _name, newname, destructive);
581
582         if (newpath.empty()) {
583                 error << string_compose (_("programming error: %1"), "cannot generate a changed audio path") << endmsg;
584                 return -1;
585         }
586
587         // Test whether newpath exists, if yes notify the user but continue. 
588         if (access(newpath.c_str(),F_OK) == 0) {
589                 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;
590                 return -1;
591         }
592
593         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
594                 error << string_compose (_("cannot rename audio file %1 to %2"), _name, newpath) << endmsg;
595                 return -1;
596         }
597
598         _name = Glib::path_get_basename (newpath);
599         _path = newpath;
600
601         return rename_peakfile (peak_path (_path));
602 }
603
604 bool
605 AudioFileSource::is_empty (Session& s, ustring path)
606 {
607         bool ret = false;
608         
609         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable (DataType::AUDIO, s, path, 0, NoPeakFile, false));
610
611         if (afs) {
612                 ret = (afs->length() == 0);
613         }
614
615         return ret;
616 }
617
618 int
619 AudioFileSource::setup_peakfile ()
620 {
621         if (!(_flags & NoPeakFile)) {
622                 return initialize_peakfile (file_is_new, _path);
623         } else {
624                 return 0;
625         }
626 }
627
628 bool
629 AudioFileSource::safe_file_extension(ustring file)
630 {
631         return !(file.rfind(".wav") == ustring::npos &&
632                  file.rfind(".aiff")== ustring::npos &&
633                  file.rfind(".aif") == ustring::npos &&
634                  file.rfind(".snd") == ustring::npos &&
635                  file.rfind(".au")  == ustring::npos &&
636                  file.rfind(".raw") == ustring::npos &&
637                  file.rfind(".sf")  == ustring::npos &&
638                  file.rfind(".cdr") == ustring::npos &&
639                  file.rfind(".smp") == ustring::npos &&
640                  file.rfind(".maud")== ustring::npos &&
641                  file.rfind(".vwe") == ustring::npos &&
642                  file.rfind(".paf") == ustring::npos &&
643                  /* protools convention */
644                  file.rfind(".L") == ustring::npos &&
645                  file.rfind(".R") == ustring::npos &&
646 #ifdef HAVE_FLAC
647                  file.rfind(".flac")== ustring::npos &&
648 #endif // HAVE_FLAC
649 #ifdef HAVE_COREAUDIO
650                  file.rfind(".mp3") == ustring::npos &&
651                  file.rfind(".aac") == ustring::npos &&
652                  file.rfind(".mp4") == ustring::npos &&
653 #endif // HAVE_COREAUDIO
654                  file.rfind(".voc") == ustring::npos);
655 }
656
657 void
658 AudioFileSource::mark_immutable ()
659 {
660         /* destructive sources stay writable, and their other flags don't
661            change.
662         */
663
664         if (!(_flags & Destructive)) {
665                 _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
666         }
667 }