1e13a29acc063ab2d6339c80247ba07cfabc2a04
[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
42 // if these headers come before sigc++ is included
43 // the parser throws ObjC++ errors. (nil is a keyword)
44 #ifdef HAVE_COREAUDIO 
45 #include <ardour/coreaudio_source.h>
46 #include <AudioToolbox/ExtendedAudioFile.h>
47 #include <AudioToolbox/AudioFormat.h>
48 #endif // HAVE_COREAUDIO
49
50 #include "i18n.h"
51
52 using namespace ARDOUR;
53 using namespace PBD;
54
55 string AudioFileSource::peak_dir = "";
56 string AudioFileSource::search_path;
57
58 sigc::signal<void,struct tm*, time_t> AudioFileSource::HeaderPositionOffsetChanged;
59 bool                                  AudioFileSource::header_position_negative;
60 uint64_t                              AudioFileSource::header_position_offset;
61
62 char   AudioFileSource::bwf_country_code[3] = "US";
63 char   AudioFileSource::bwf_organization_code[4] = "LAS";
64 char   AudioFileSource::bwf_serial_number[13] = "000000000000";
65
66 AudioFileSource::AudioFileSource (string idstr, Flag flags)
67         : AudioSource (idstr), _flags (flags)
68 {
69         /* constructor used for existing external to session files. file must exist already */
70
71         if (init (idstr, true)) {
72                 throw failed_constructor ();
73         }
74
75 }
76
77 AudioFileSource::AudioFileSource (std::string path, Flag flags, SampleFormat samp_format, HeaderFormat hdr_format)
78         : AudioSource (path), _flags (flags)
79 {
80         /* constructor used for new internal-to-session files. file cannot exist */
81
82         if (init (path, false)) {
83                 throw failed_constructor ();
84         }
85 }
86
87 AudioFileSource::AudioFileSource (const XMLNode& node)
88         : AudioSource (node), _flags (Flag (Writable|CanRename))
89 {
90         /* constructor used for existing internal-to-session files. file must exist */
91
92         if (set_state (node)) {
93                 throw failed_constructor ();
94         }
95         
96         if (init (_name, true)) {
97                 throw failed_constructor ();
98         }
99 }
100
101 AudioFileSource::~AudioFileSource ()
102 {
103         if (removable()) {
104                 unlink (_path.c_str());
105                 unlink (peakpath.c_str());
106         }
107 }
108
109 bool
110 AudioFileSource::removable () const
111 {
112         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || 
113                                       ((_flags & RemovableIfEmpty) && is_empty (_path)));
114 }
115
116 int
117 AudioFileSource::init (string pathstr, bool must_exist)
118 {
119         bool is_new = false;
120
121         _length = 0;
122         next_peak_clear_should_notify = false;
123         
124         if (!find (pathstr, must_exist, is_new)) {
125                 cerr << "cannot find " << pathstr << " with me = " << must_exist << endl;
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 #ifdef HAVE_COREAUDIO
170
171 AudioFileSource*
172 AudioFileSource::create (const XMLNode& node)
173 {
174         AudioFileSource* es = 0;
175
176         if (node.property (X_("destructive")) != 0) {
177                 
178                 es = new DestructiveFileSource (node);
179         
180         } else {
181                 
182                 try {
183                         es = new CoreAudioSource (node);
184                 } 
185                 
186                 
187                 catch (failed_constructor& err) {
188                         es = new SndFileSource (node);
189                 }
190         }
191         
192         return es;
193 }
194
195 #else
196
197 AudioFileSource*
198 AudioFileSource::create (const XMLNode& node)
199 {
200         if (node.property (X_("destructive")) != 0) {
201                 
202                 return new DestructiveFileSource (node);
203                 
204         } else {
205                 
206                 return new SndFileSource (node);
207         }
208 }
209
210 #endif // HAVE_COREAUDIO
211
212 #ifdef HAVE_COREAUDIO
213 AudioFileSource*
214 AudioFileSource::create (const string& idstr)
215 {
216         AudioFileSource* es = 0;
217
218         try {
219                 es = new CoreAudioSource (idstr);
220         }
221
222         catch (failed_constructor& err) {
223                 es = new SndFileSource (idstr);
224         }
225
226         return es;
227 }
228
229 #else
230
231 AudioFileSource*
232 AudioFileSource::create (string idstr)
233 {
234         return new SndFileSource (idstr);
235 }
236
237 #endif // HAVE_COREAUDIO
238
239 #ifdef HAVE_COREAUDIO
240 std::string 
241 CFStringRefToStdString(CFStringRef stringRef)
242 {
243         CFIndex size = 
244                 CFStringGetMaximumSizeForEncoding(CFStringGetLength(stringRef) , 
245                 kCFStringEncodingASCII);
246             char *buf = new char[size];
247         
248         std::string result;
249
250         if(CFStringGetCString(stringRef, buf, size, kCFStringEncodingASCII)) {
251             result = buf;
252         }
253         delete [] buf;
254         return result;
255 }
256 #endif // HAVE_COREAUDIO
257
258 bool
259 AudioFileSource::get_soundfile_info (string path, SoundFileInfo& _info, string& error_msg)
260 {
261 #ifdef HAVE_COREAUDIO
262         OSStatus err = noErr;
263     FSRef ref; 
264         ExtAudioFileRef af = 0;
265         size_t size;
266     CFStringRef name;
267
268     err = FSPathMakeRef ((UInt8*)path.c_str(), &ref, 0);
269         if (err != noErr) {
270         ExtAudioFileDispose (af);
271                 goto libsndfile;
272         }
273
274         err = ExtAudioFileOpen(&ref, &af);
275         if (err != noErr) {
276         ExtAudioFileDispose (af);
277                 goto libsndfile;
278         }
279
280         AudioStreamBasicDescription absd;
281         memset(&absd, 0, sizeof(absd));
282         size = sizeof(AudioStreamBasicDescription);
283         err = ExtAudioFileGetProperty(af,
284                         kExtAudioFileProperty_FileDataFormat, &size, &absd);
285         if (err != noErr) {
286         ExtAudioFileDispose (af);
287                 goto libsndfile;
288         }
289
290         _info.samplerate = absd.mSampleRate;
291         _info.channels   = absd.mChannelsPerFrame;
292
293     size = sizeof(_info.length);
294     err = ExtAudioFileGetProperty(af, kExtAudioFileProperty_FileLengthFrames, &size, &_info.length);
295     if (err != noErr) {
296         ExtAudioFileDispose (af);
297                 goto libsndfile;
298     }
299
300         size = sizeof(CFStringRef);
301         err = AudioFormatGetProperty(
302                         kAudioFormatProperty_FormatName, sizeof(absd), &absd, &size, &name);
303         if (err != noErr) {
304         ExtAudioFileDispose (af);
305                 goto libsndfile;
306         }
307
308         _info.format_name = CFStringRefToStdString(name);
309
310     ExtAudioFileDispose (af);
311         return true;
312         
313 libsndfile:
314 #endif // HAVE_COREAUDIO
315
316         SNDFILE *sf;
317         SF_INFO sf_info;
318
319         sf_info.format = 0; // libsndfile says to clear this before sf_open().
320
321         if ((sf = sf_open ((char*) path.c_str(), SFM_READ, &sf_info)) == 0) { 
322                 char errbuf[256];
323                 error_msg = sf_error_str (0, errbuf, sizeof (errbuf) - 1);
324                 return false;
325         }
326
327         sf_close (sf);
328
329         _info.samplerate  = sf_info.samplerate;
330         _info.channels    = sf_info.channels;
331         _info.length      = sf_info.frames;
332         _info.format_name = string_compose("Format: %1, %2",
333                                            sndfile_major_format(sf_info.format),
334                                            sndfile_minor_format(sf_info.format));
335         return true;
336 }
337
338 XMLNode&
339 AudioFileSource::get_state ()
340 {
341         XMLNode& root (AudioSource::get_state());
342         char buf[16];
343         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
344         root.add_property ("flags", buf);
345         return root;
346 }
347
348 int
349 AudioFileSource::set_state (const XMLNode& node)
350 {
351         const XMLProperty* prop;
352
353         if (AudioSource::set_state (node)) {
354                 return -1;
355         }
356
357         if ((prop = node.property (X_("flags"))) != 0) {
358
359                 int ival;
360                 sscanf (prop->value().c_str(), "0x%x", &ival);
361                 _flags = Flag (ival);
362
363         } else {
364
365                 _flags = Flag (0);
366
367         }
368
369         return 0;
370 }
371
372 void
373 AudioFileSource::mark_for_remove ()
374 {
375         if (!writable()) {
376                 return;
377         }
378         _flags = Flag (_flags | RemoveAtDestroy);
379 }
380
381 void
382 AudioFileSource::mark_streaming_write_completed ()
383 {
384         if (!writable()) {
385                 return;
386         }
387
388         Glib::Mutex::Lock lm (_lock);
389
390         next_peak_clear_should_notify = true;
391
392         if (_peaks_built || pending_peak_builds.empty()) {
393                 _peaks_built = true;
394                  PeaksReady (); /* EMIT SIGNAL */
395         }
396 }
397
398 void
399 AudioFileSource::mark_take (string id)
400 {
401         if (writable()) {
402                 _take_id = id;
403         }
404 }
405
406 int
407 AudioFileSource::move_to_trash (const string trash_dir_name)
408 {
409         string newpath;
410
411         if (!writable()) {
412                 return -1;
413         }
414
415         /* don't move the file across filesystems, just
416            stick it in the `trash_dir_name' directory
417            on whichever filesystem it was already on.
418         */
419
420         newpath = Glib::path_get_dirname (_path);
421         newpath = Glib::path_get_dirname (newpath);
422
423         newpath += '/';
424         newpath += trash_dir_name;
425         newpath += '/';
426         newpath += Glib::path_get_basename (_path);
427
428         if (access (newpath.c_str(), F_OK) == 0) {
429
430                 /* the new path already exists, try versioning */
431                 
432                 char buf[PATH_MAX+1];
433                 int version = 1;
434                 string newpath_v;
435
436                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
437                 newpath_v = buf;
438
439                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
440                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
441                         newpath_v = buf;
442                 }
443                 
444                 if (version == 999) {
445                         error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
446                                           newpath)
447                               << endmsg;
448                 } else {
449                         newpath = newpath_v;
450                 }
451
452         } else {
453
454                 /* it doesn't exist, or we can't read it or something */
455
456         }
457
458         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
459                 error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
460                                   _path, newpath, strerror (errno))
461                       << endmsg;
462                 return -1;
463         }
464
465         if (::unlink (peakpath.c_str()) != 0) {
466                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
467                                   peakpath, _path, strerror (errno))
468                       << endmsg;
469                 /* try to back out */
470                 rename (newpath.c_str(), _path.c_str());
471                 return -1;
472         }
473             
474         _path = newpath;
475         peakpath = "";
476         
477         /* file can not be removed twice, since the operation is not idempotent */
478
479         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
480
481         return 0;
482 }
483
484 bool
485 AudioFileSource::find (string pathstr, bool must_exist, bool& isnew)
486 {
487         string::size_type pos;
488         bool ret = false;
489
490         isnew = false;
491
492         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
493
494         if ((pos = pathstr.find_last_of (':')) == string::npos) {
495                 pathstr = pathstr;
496         } else {
497                 pathstr = pathstr.substr (0, pos);
498         }
499
500         if (pathstr[0] != '/') {
501
502                 /* non-absolute pathname: find pathstr in search path */
503
504                 vector<string> dirs;
505                 int cnt;
506                 string fullpath;
507                 string keeppath;
508
509                 if (search_path.length() == 0) {
510                         error << _("FileSource: search path not set") << endmsg;
511                         goto out;
512                 }
513
514                 split (search_path, dirs, ':');
515
516                 cnt = 0;
517                 
518                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
519
520                         fullpath = *i;
521                         if (fullpath[fullpath.length()-1] != '/') {
522                                 fullpath += '/';
523                         }
524                         fullpath += pathstr;
525                         
526                         if (access (fullpath.c_str(), R_OK) == 0) {
527                                 keeppath = fullpath;
528                                 ++cnt;
529                         } 
530                 }
531
532                 if (cnt > 1) {
533
534                         error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, search_path) << endmsg;
535                         goto out;
536
537                 } else if (cnt == 0) {
538
539                         if (must_exist) {
540                                 error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, search_path) << endmsg;
541                                 goto out;
542                         } else {
543                                 isnew = true;
544                         }
545                 }
546                 
547                 _name = pathstr;
548                 _path = keeppath;
549                 ret = true;
550
551         } else {
552                 
553                 /* external files and/or very very old style sessions include full paths */
554                 
555                 _path = pathstr;
556                 _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
557                 
558                 if (access (_path.c_str(), R_OK) != 0) {
559
560                         /* file does not exist or we cannot read it */
561
562                         if (must_exist) {
563                                 error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
564                                 goto out;
565                         }
566                         
567                         if (errno != ENOENT) {
568                                 error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
569                                 goto out;
570                         }
571                         
572                         /* a new file */
573
574                         isnew = true;
575                         ret = true;
576
577                 } else {
578                         
579                         /* already exists */
580
581                         ret = true;
582                 }
583         }
584         
585   out:
586         return ret;
587 }
588
589 void
590 AudioFileSource::set_search_path (string p)
591 {
592         search_path = p;
593 }
594
595 void
596 AudioFileSource::set_header_position_offset (jack_nframes_t offset, bool negative)
597 {
598         time_t tnow;
599
600         time (&tnow);
601
602         header_position_offset = offset;
603         header_position_negative = negative;
604         HeaderPositionOffsetChanged (localtime (&tnow), tnow); /* EMIT SIGNAL */
605 }
606
607 void
608 AudioFileSource::set_timeline_position (jack_nframes_t pos)
609 {
610         timeline_position = pos;
611 }
612
613 void
614 AudioFileSource::handle_header_position_change (struct tm* now, time_t tnow)
615 {
616         /* don't do this if the file has never had its header flushed to disk yet */
617
618         if (writable() && _timestamp) {
619                 set_header_timeline_position ();
620                 flush_header ();
621         }
622 }
623
624 void
625 AudioFileSource::set_allow_remove_if_empty (bool yn)
626 {
627         if (writable()) {
628                 allow_remove_if_empty = yn;
629         }
630 }
631
632 int
633 AudioFileSource::set_name (string newname, bool destructive)
634 {
635         Glib::Mutex::Lock lm (_lock);
636         string oldpath = _path;
637         string newpath = Session::change_audio_path_by_name (oldpath, _name, newname, destructive);
638
639         if (newpath.empty()) {
640                 error << string_compose (_("programming error: %1"), "cannot generate a changed audio path") << endmsg;
641                 return -1;
642         }
643
644         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
645                 error << string_compose (_("cannot rename audio file for %1 to %2"), _name, newpath) << endmsg;
646                 return -1;
647         }
648
649         _name = Glib::path_get_basename (newpath);
650         _path = newpath;
651
652         return rename_peakfile (peak_path (_path));
653 }
654
655 bool
656 AudioFileSource::is_empty (string path)
657 {
658         /* XXX fix me */
659
660         return false;
661 }
662