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