Enabled conditional FLAC importing.
[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/enumwriter.h>
33
34 #include <sndfile.h>
35
36 #include <glibmm/miscutils.h>
37
38 #include <ardour/audiofilesource.h>
39 #include <ardour/sndfile_helpers.h>
40 #include <ardour/sndfilesource.h>
41 #include <ardour/session.h>
42 #include <ardour/source_factory.h>
43
44 // if these headers come before sigc++ is included
45 // the parser throws ObjC++ errors. (nil is a keyword)
46 #ifdef HAVE_COREAUDIO 
47 #include <ardour/coreaudiosource.h>
48 #include <AudioToolbox/ExtendedAudioFile.h>
49 #include <AudioToolbox/AudioFormat.h>
50 #endif // HAVE_COREAUDIO
51
52 #include "i18n.h"
53
54 using namespace ARDOUR;
55 using namespace PBD;
56 using namespace Glib;
57
58 ustring AudioFileSource::peak_dir = "";
59 ustring AudioFileSource::search_path;
60
61 sigc::signal<void> AudioFileSource::HeaderPositionOffsetChanged;
62 uint64_t           AudioFileSource::header_position_offset = 0;
63
64 /* XXX maybe this too */
65 char   AudioFileSource::bwf_serial_number[13] = "000000000000";
66
67 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags)
68         : AudioSource (s, path), _flags (flags),
69           _channel (0)
70 {
71         /* constructor used for existing external to session files. file must exist already */
72         _is_embedded = AudioFileSource::determine_embeddedness (path);
73
74         if (init (path, true)) {
75                 throw failed_constructor ();
76         }
77
78 }
79
80 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags, SampleFormat samp_format, HeaderFormat hdr_format)
81         : AudioSource (s, path), _flags (flags),
82           _channel (0)
83 {
84         /* constructor used for new internal-to-session files. file cannot exist */
85         _is_embedded = false;
86
87         if (init (path, false)) {
88                 throw failed_constructor ();
89         }
90 }
91
92 AudioFileSource::AudioFileSource (Session& s, const XMLNode& node, bool must_exist)
93         : AudioSource (s, node), _flags (Flag (Writable|CanRename))
94           /* _channel is set in set_state() */
95 {
96         /* constructor used for existing internal-to-session files. file must exist */
97
98         if (set_state (node)) {
99                 throw failed_constructor ();
100         }
101         
102         if (init (_name, must_exist)) {
103                 throw failed_constructor ();
104         }
105 }
106
107 AudioFileSource::~AudioFileSource ()
108 {
109         if (removable()) {
110                 unlink (_path.c_str());
111                 unlink (peakpath.c_str());
112         }
113 }
114
115 bool
116 AudioFileSource::determine_embeddedness (ustring path)
117 {
118         return (path.find("/") == 0);
119 }
120
121 bool
122 AudioFileSource::removable () const
123 {
124         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || ((_flags & RemovableIfEmpty) && length() == 0));
125 }
126
127 int
128 AudioFileSource::init (ustring pathstr, bool must_exist)
129 {
130         bool is_new = false;
131
132         _length = 0;
133         timeline_position = 0;
134         _peaks_built = false;
135         file_is_new = false;
136
137         if (!find (pathstr, must_exist, is_new)) {
138                 throw non_existent_source ();
139         }
140
141         if (is_new && must_exist) {
142                 return -1;
143         }
144
145         return 0;
146 }
147
148
149 ustring
150 AudioFileSource::peak_path (ustring audio_path)
151 {
152         return _session.peak_path_from_audio_path (audio_path);
153 }
154
155 ustring
156 AudioFileSource::old_peak_path (ustring audio_path)
157 {
158         /* XXX hardly bombproof! fix me */
159
160         struct stat stat_file;
161         struct stat stat_mount;
162
163         ustring mp = mountpoint (audio_path);
164
165         stat (audio_path.c_str(), &stat_file);
166         stat (mp.c_str(), &stat_mount);
167
168         char buf[32];
169 #ifdef __APPLE__
170         snprintf (buf, sizeof (buf), "%u-%u-%d.peak", stat_mount.st_ino, stat_file.st_ino, _channel);
171 #else
172         snprintf (buf, sizeof (buf), "%ld-%ld-%d.peak", stat_mount.st_ino, stat_file.st_ino, _channel);
173 #endif
174
175         ustring res = peak_dir;
176         res += buf;
177
178         return res;
179 }
180
181 bool
182 AudioFileSource::get_soundfile_info (ustring path, SoundFileInfo& _info, string& error_msg)
183 {
184 #ifdef HAVE_COREAUDIO
185         if (CoreAudioSource::get_soundfile_info (path, _info, error_msg) == 0) {
186                 return true;
187         }
188 #endif // HAVE_COREAUDIO
189
190         if (SndFileSource::get_soundfile_info (path, _info, error_msg) != 0) {
191                 return true;
192         }
193
194         return false;
195 }
196
197 XMLNode&
198 AudioFileSource::get_state ()
199 {
200         XMLNode& root (AudioSource::get_state());
201         char buf[32];
202         root.add_property (X_("flags"), enum_2_string (_flags));
203         snprintf (buf, sizeof (buf), "%u", _channel);
204         root.add_property (X_("channel"), buf);
205         return root;
206 }
207
208 int
209 AudioFileSource::set_state (const XMLNode& node)
210 {
211         const XMLProperty* prop;
212
213         if (AudioSource::set_state (node)) {
214                 return -1;
215         }
216
217         if ((prop = node.property (X_("flags"))) != 0) {
218                 _flags = Flag (string_2_enum (prop->value(), _flags));
219         } else {
220                 _flags = Flag (0);
221
222         }
223
224         if ((prop = node.property (X_("channel"))) != 0) {
225                 _channel = atoi (prop->value());
226         } else {
227                 _channel = 0;
228         }
229
230         if ((prop = node.property (X_("name"))) != 0) {
231                 _is_embedded = AudioFileSource::determine_embeddedness (prop->value());
232         } else {
233                 _is_embedded = false;
234         }
235
236         if ((prop = node.property (X_("destructive"))) != 0) {
237                 /* old style, from the period when we had DestructiveFileSource */
238                 _flags = Flag (_flags | Destructive);
239         }
240
241         return 0;
242 }
243
244 void
245 AudioFileSource::mark_for_remove ()
246 {
247         if (!writable()) {
248                 return;
249         }
250
251         _flags = Flag (_flags | Removable | RemoveAtDestroy);
252 }
253
254 void
255 AudioFileSource::mark_streaming_write_completed ()
256 {
257         if (!writable()) {
258                 return;
259         }
260
261         Glib::Mutex::Lock lm (_lock);
262
263         if (_peaks_built) {
264                 PeaksReady (); /* EMIT SIGNAL */
265         }
266 }
267
268 void
269 AudioFileSource::mark_take (ustring id)
270 {
271         if (writable()) {
272                 _take_id = id;
273         }
274 }
275
276 int
277 AudioFileSource::move_to_trash (const ustring& trash_dir_name)
278 {
279         if (is_embedded()) {
280                 cerr << "tried to move an embedded region to trash" << endl;
281                 return -1;
282         }
283
284         ustring newpath;
285
286         if (!writable()) {
287                 return -1;
288         }
289
290         /* don't move the file across filesystems, just
291            stick it in the `trash_dir_name' directory
292            on whichever filesystem it was already on.
293         */
294         
295         newpath = Glib::path_get_dirname (_path);
296         newpath = Glib::path_get_dirname (newpath); 
297
298         cerr << "from " << _path << " dead dir looks like " << newpath << endl;
299
300         newpath += '/';
301         newpath += trash_dir_name;
302         newpath += '/';
303         newpath += Glib::path_get_basename (_path);
304
305         if (access (newpath.c_str(), F_OK) == 0) {
306
307                 /* the new path already exists, try versioning */
308                 
309                 char buf[PATH_MAX+1];
310                 int version = 1;
311                 ustring newpath_v;
312
313                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
314                 newpath_v = buf;
315
316                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
317                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
318                         newpath_v = buf;
319                 }
320                 
321                 if (version == 999) {
322                         error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
323                                           newpath)
324                               << endmsg;
325                 } else {
326                         newpath = newpath_v;
327                 }
328
329         } else {
330
331                 /* it doesn't exist, or we can't read it or something */
332
333         }
334
335         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
336                 error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
337                                   _path, newpath, strerror (errno))
338                       << endmsg;
339                 return -1;
340         }
341
342         if (::unlink (peakpath.c_str()) != 0) {
343                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
344                                   peakpath, _path, strerror (errno))
345                       << endmsg;
346                 /* try to back out */
347                 rename (newpath.c_str(), _path.c_str());
348                 return -1;
349         }
350             
351         _path = newpath;
352         peakpath = "";
353         
354         /* file can not be removed twice, since the operation is not idempotent */
355
356         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
357
358         return 0;
359 }
360
361 bool
362 AudioFileSource::find (ustring& pathstr, bool must_exist, bool& isnew)
363 {
364         ustring::size_type pos;
365         bool ret = false;
366
367         isnew = false;
368
369         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
370
371         if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
372                 pathstr = pathstr.substr (0, pos);
373         }
374
375         if (pathstr[0] != '/') {
376
377                 /* non-absolute pathname: find pathstr in search path */
378
379                 vector<ustring> dirs;
380                 int cnt;
381                 ustring fullpath;
382                 ustring keeppath;
383
384                 if (search_path.length() == 0) {
385                         error << _("FileSource: search path not set") << endmsg;
386                         goto out;
387                 }
388
389                 split (search_path, dirs, ':');
390
391                 cnt = 0;
392                 
393                 for (vector<ustring>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
394
395                         fullpath = *i;
396                         if (fullpath[fullpath.length()-1] != '/') {
397                                 fullpath += '/';
398                         }
399                         fullpath += pathstr;
400                         
401                         if (access (fullpath.c_str(), R_OK) == 0) {
402                                 keeppath = fullpath;
403                                 ++cnt;
404                         } 
405                 }
406
407                 if (cnt > 1) {
408
409                         error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, search_path) << endmsg;
410                         goto out;
411
412                 } else if (cnt == 0) {
413
414                         if (must_exist) {
415                                 error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, search_path) << endmsg;
416                                 goto out;
417                         } else {
418                                 isnew = true;
419                         }
420                 }
421                 
422                 _name = pathstr;
423                 _path = keeppath;
424                 ret = true;
425
426         } else {
427                 
428                 /* external files and/or very very old style sessions include full paths */
429                 
430                 _path = pathstr;
431                 if (is_embedded()) {
432                         _name = pathstr;
433                 } else {
434                         _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
435                 }
436                 
437                 if (access (_path.c_str(), R_OK) != 0) {
438
439                         /* file does not exist or we cannot read it */
440
441                         if (must_exist) {
442                                 error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
443                                 goto out;
444                         }
445                         
446                         if (errno != ENOENT) {
447                                 error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
448                                 goto out;
449                         }
450                         
451                         /* a new file */
452
453                         isnew = true;
454                         ret = true;
455
456                 } else {
457                         
458                         /* already exists */
459
460                         ret = true;
461                 }
462         }
463         
464   out:
465         return ret;
466 }
467
468 void
469 AudioFileSource::set_search_path (ustring p)
470 {
471         search_path = p;
472 }
473
474 void
475 AudioFileSource::set_header_position_offset (nframes_t offset)
476 {
477         header_position_offset = offset;
478         HeaderPositionOffsetChanged ();
479 }
480
481 void
482 AudioFileSource::set_timeline_position (int64_t pos)
483 {
484         timeline_position = pos;
485 }
486
487 void
488 AudioFileSource::set_allow_remove_if_empty (bool yn)
489 {
490         if (!writable()) {
491                 return;
492         }
493
494         if (yn) {
495                 _flags = Flag (_flags | RemovableIfEmpty);
496         } else {
497                 _flags = Flag (_flags & ~RemovableIfEmpty);
498         }
499 }
500
501 int
502 AudioFileSource::set_name (ustring newname, bool destructive)
503 {
504         Glib::Mutex::Lock lm (_lock);
505         ustring oldpath = _path;
506         ustring newpath = Session::change_audio_path_by_name (oldpath, _name, newname, destructive);
507
508         if (newpath.empty()) {
509                 error << string_compose (_("programming error: %1"), "cannot generate a changed audio path") << endmsg;
510                 return -1;
511         }
512
513         // Test whether newpath exists, if yes notify the user but continue. 
514         if (access(newpath.c_str(),F_OK) == 0) {
515                 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;
516                 return -1;
517         }
518
519         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
520                 error << string_compose (_("cannot rename audio file %1 to %2"), _name, newpath) << endmsg;
521                 return -1;
522         }
523
524         _name = Glib::path_get_basename (newpath);
525         _path = newpath;
526
527         return rename_peakfile (peak_path (_path));
528 }
529
530 bool
531 AudioFileSource::is_empty (Session& s, ustring path)
532 {
533         bool ret = false;
534         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable (s, path, 0, NoPeakFile, false));
535
536         if (afs) {
537                 ret = (afs->length() == 0);
538         }
539
540         return ret;
541 }
542
543 int
544 AudioFileSource::setup_peakfile ()
545 {
546         if (!(_flags & NoPeakFile)) {
547                 return initialize_peakfile (file_is_new, _path);
548         } else {
549                 return 0;
550         }
551 }
552
553 bool
554 AudioFileSource::safe_file_extension(ustring file)
555 {
556         return !(file.rfind(".wav") == ustring::npos &&
557                 file.rfind(".aiff")== ustring::npos &&
558                 file.rfind(".aif") == ustring::npos &&
559                 file.rfind(".snd") == ustring::npos &&
560                 file.rfind(".au")  == ustring::npos &&
561                 file.rfind(".raw") == ustring::npos &&
562                 file.rfind(".sf")  == ustring::npos &&
563                 file.rfind(".cdr") == ustring::npos &&
564                 file.rfind(".smp") == ustring::npos &&
565                 file.rfind(".maud")== ustring::npos &&
566                 file.rfind(".vwe") == ustring::npos &&
567                 file.rfind(".paf") == ustring::npos &&
568 #ifdef HAVE_FLAC
569                 file.rfind(".flac")== ustring::npos &&
570 #endif // HAVE_FLAC
571 #ifdef HAVE_COREAUDIO
572                 file.rfind(".mp3") == ustring::npos &&
573                 file.rfind(".aac") == ustring::npos &&
574                 file.rfind(".mp4") == ustring::npos &&
575 #endif // HAVE_COREAUDIO
576                 file.rfind(".voc") == ustring::npos);
577 }
578
579 void
580 AudioFileSource::mark_immutable ()
581 {
582         /* destructive sources stay writable, and their other flags don't
583            change.
584         */
585
586         if (!(_flags & Destructive)) {
587                 _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
588         }
589 }