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