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