b74f6b370f396a12e3fa85a2404a8b1a04b65893
[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
57 string AudioFileSource::peak_dir = "";
58 string AudioFileSource::search_path;
59
60 sigc::signal<void> AudioFileSource::HeaderPositionOffsetChanged;
61 uint64_t           AudioFileSource::header_position_offset = 0;
62
63 /* XXX maybe this too */
64 char   AudioFileSource::bwf_serial_number[13] = "000000000000";
65
66 AudioFileSource::AudioFileSource (Session& s, string path, Flag flags)
67         : AudioSource (s, path), _flags (flags),
68           channel (0)
69 {
70         /* constructor used for existing external to session files. file must exist already */
71         _is_embedded = AudioFileSource::determine_embeddedness (path);
72
73         if (init (path, true)) {
74                 throw failed_constructor ();
75         }
76
77 }
78
79 AudioFileSource::AudioFileSource (Session& s, std::string path, Flag flags, SampleFormat samp_format, HeaderFormat hdr_format)
80         : AudioSource (s, path), _flags (flags),
81           channel (0)
82 {
83         /* constructor used for new internal-to-session files. file cannot exist */
84         _is_embedded = false;
85
86         if (init (path, false)) {
87                 throw failed_constructor ();
88         }
89 }
90
91 AudioFileSource::AudioFileSource (Session& s, const XMLNode& node)
92         : AudioSource (s, node), _flags (Flag (Writable|CanRename))
93           /* channel is set in set_state() */
94 {
95         /* constructor used for existing internal-to-session files. file must exist */
96
97         if (set_state (node)) {
98                 throw failed_constructor ();
99         }
100         
101         if (init (_name, true)) {
102                 throw failed_constructor ();
103         }
104 }
105
106 AudioFileSource::~AudioFileSource ()
107 {
108         if (removable()) {
109                 unlink (_path.c_str());
110                 unlink (peakpath.c_str());
111         }
112 }
113
114 bool
115 AudioFileSource::determine_embeddedness (std::string path)
116 {
117         return (path.find("/") == 0);
118 }
119
120 bool
121 AudioFileSource::removable () const
122 {
123         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || ((_flags & RemovableIfEmpty) && length() == 0));
124 }
125
126 int
127 AudioFileSource::init (string pathstr, bool must_exist)
128 {
129         bool is_new = false;
130
131         _length = 0;
132         timeline_position = 0;
133         next_peak_clear_should_notify = false;
134         _peaks_built = false;
135         file_is_new = false;
136
137         if (!find (pathstr, must_exist, is_new)) {
138                 return -1;
139         }
140
141         if (is_new && must_exist) {
142                 return -1;
143         }
144
145         return 0;
146 }
147
148
149 string
150 AudioFileSource::peak_path (string audio_path)
151 {
152         return _session.peak_path_from_audio_path (audio_path);
153 }
154
155 string
156 AudioFileSource::old_peak_path (string audio_path)
157 {
158         /* XXX hardly bombproof! fix me */
159
160         struct stat stat_file;
161         struct stat stat_mount;
162
163         string 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         string res = peak_dir;
176         res += buf;
177
178         return res;
179 }
180
181 bool
182 AudioFileSource::get_soundfile_info (string 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), "%d", 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         next_peak_clear_should_notify = true;
264
265         if (_peaks_built || pending_peak_builds.empty()) {
266                 _peaks_built = true;
267                 PeaksReady (); /* EMIT SIGNAL */
268         }
269 }
270
271 void
272 AudioFileSource::mark_take (string id)
273 {
274         if (writable()) {
275                 _take_id = id;
276         }
277 }
278
279 int
280 AudioFileSource::move_to_trash (const string trash_dir_name)
281 {
282         if (is_embedded()) {
283                 cerr << "tried to move an embedded region to trash" << endl;
284                 return -1;
285         }
286
287         string newpath;
288
289         if (!writable()) {
290                 return -1;
291         }
292
293         /* don't move the file across filesystems, just
294            stick it in the `trash_dir_name' directory
295            on whichever filesystem it was already on.
296         */
297         
298         newpath = Glib::path_get_dirname (_path);
299         newpath = Glib::path_get_dirname (newpath); 
300
301         cerr << "from " << _path << " dead dir looks like " << newpath << endl;
302
303         newpath += '/';
304         newpath += trash_dir_name;
305         newpath += '/';
306         newpath += Glib::path_get_basename (_path);
307
308         if (access (newpath.c_str(), F_OK) == 0) {
309
310                 /* the new path already exists, try versioning */
311                 
312                 char buf[PATH_MAX+1];
313                 int version = 1;
314                 string newpath_v;
315
316                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
317                 newpath_v = buf;
318
319                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
320                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
321                         newpath_v = buf;
322                 }
323                 
324                 if (version == 999) {
325                         error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
326                                           newpath)
327                               << endmsg;
328                 } else {
329                         newpath = newpath_v;
330                 }
331
332         } else {
333
334                 /* it doesn't exist, or we can't read it or something */
335
336         }
337
338         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
339                 error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
340                                   _path, newpath, strerror (errno))
341                       << endmsg;
342                 return -1;
343         }
344
345         if (::unlink (peakpath.c_str()) != 0) {
346                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
347                                   peakpath, _path, strerror (errno))
348                       << endmsg;
349                 /* try to back out */
350                 rename (newpath.c_str(), _path.c_str());
351                 return -1;
352         }
353             
354         _path = newpath;
355         peakpath = "";
356         
357         /* file can not be removed twice, since the operation is not idempotent */
358
359         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
360
361         return 0;
362 }
363
364 bool
365 AudioFileSource::find (string pathstr, bool must_exist, bool& isnew)
366 {
367         string::size_type pos;
368         bool ret = false;
369
370         isnew = false;
371
372         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
373
374         if ((pos = pathstr.find_last_of (':')) == string::npos) {
375                 pathstr = pathstr;
376         } else {
377                 pathstr = pathstr.substr (0, pos);
378         }
379
380         if (pathstr[0] != '/') {
381
382                 /* non-absolute pathname: find pathstr in search path */
383
384                 vector<string> dirs;
385                 int cnt;
386                 string fullpath;
387                 string keeppath;
388
389                 if (search_path.length() == 0) {
390                         error << _("FileSource: search path not set") << endmsg;
391                         goto out;
392                 }
393
394                 split (search_path, dirs, ':');
395
396                 cnt = 0;
397                 
398                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
399
400                         fullpath = *i;
401                         if (fullpath[fullpath.length()-1] != '/') {
402                                 fullpath += '/';
403                         }
404                         fullpath += pathstr;
405                         
406                         if (access (fullpath.c_str(), R_OK) == 0) {
407                                 keeppath = fullpath;
408                                 ++cnt;
409                         } 
410                 }
411
412                 if (cnt > 1) {
413
414                         error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, search_path) << endmsg;
415                         goto out;
416
417                 } else if (cnt == 0) {
418
419                         if (must_exist) {
420                                 error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, search_path) << endmsg;
421                                 goto out;
422                         } else {
423                                 isnew = true;
424                         }
425                 }
426                 
427                 _name = pathstr;
428                 _path = keeppath;
429                 ret = true;
430
431         } else {
432                 
433                 /* external files and/or very very old style sessions include full paths */
434                 
435                 _path = pathstr;
436                 if (is_embedded()) {
437                         _name = pathstr;
438                 } else {
439                         _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
440                 }
441                 
442                 if (access (_path.c_str(), R_OK) != 0) {
443
444                         /* file does not exist or we cannot read it */
445
446                         if (must_exist) {
447                                 error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
448                                 goto out;
449                         }
450                         
451                         if (errno != ENOENT) {
452                                 error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
453                                 goto out;
454                         }
455                         
456                         /* a new file */
457
458                         isnew = true;
459                         ret = true;
460
461                 } else {
462                         
463                         /* already exists */
464
465                         ret = true;
466                 }
467         }
468         
469   out:
470         return ret;
471 }
472
473 void
474 AudioFileSource::set_search_path (string p)
475 {
476         search_path = p;
477 }
478
479 void
480 AudioFileSource::set_header_position_offset (nframes_t offset)
481 {
482         header_position_offset = offset;
483         HeaderPositionOffsetChanged ();
484 }
485
486 void
487 AudioFileSource::set_timeline_position (int64_t pos)
488 {
489         timeline_position = pos;
490 }
491
492 void
493 AudioFileSource::set_allow_remove_if_empty (bool yn)
494 {
495         if (!writable()) {
496                 return;
497         }
498
499         if (yn) {
500                 _flags = Flag (_flags | RemovableIfEmpty);
501         } else {
502                 _flags = Flag (_flags & ~RemovableIfEmpty);
503         }
504 }
505
506 int
507 AudioFileSource::set_name (string newname, bool destructive)
508 {
509         Glib::Mutex::Lock lm (_lock);
510         string oldpath = _path;
511         string newpath = Session::change_audio_path_by_name (oldpath, _name, newname, destructive);
512
513         if (newpath.empty()) {
514                 error << string_compose (_("programming error: %1"), "cannot generate a changed audio path") << endmsg;
515                 return -1;
516         }
517
518         // Test whether newpath exists, if yes notify the user but continue. 
519         if (access(newpath.c_str(),F_OK) == 0) {
520                 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;
521                 return -1;
522         }
523
524         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
525                 error << string_compose (_("cannot rename audio file %1 to %2"), _name, newpath) << endmsg;
526                 return -1;
527         }
528
529         _name = Glib::path_get_basename (newpath);
530         _path = newpath;
531
532         return rename_peakfile (peak_path (_path));
533 }
534
535 bool
536 AudioFileSource::is_empty (Session& s, string path)
537 {
538         bool ret = false;
539         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable (s, path, 0, NoPeakFile, false));
540
541         if (afs) {
542                 ret = (afs->length() == 0);
543         }
544
545         return ret;
546 }
547
548 int
549 AudioFileSource::setup_peakfile ()
550 {
551         if (!(_flags & NoPeakFile)) {
552                 return initialize_peakfile (file_is_new, _path);
553         } else {
554                 return 0;
555         }
556 }
557
558 bool
559 AudioFileSource::safe_file_extension(string file)
560 {
561         return !(file.rfind(".wav") == string::npos &&
562                 file.rfind(".aiff")== string::npos &&
563                 file.rfind(".aif") == string::npos &&
564                 file.rfind(".snd") == string::npos &&
565                 file.rfind(".au")  == string::npos &&
566                 file.rfind(".raw") == string::npos &&
567                 file.rfind(".sf")  == string::npos &&
568                 file.rfind(".cdr") == string::npos &&
569                 file.rfind(".smp") == string::npos &&
570                 file.rfind(".maud")== string::npos &&
571                 file.rfind(".vwe") == string::npos &&
572                 file.rfind(".paf") == string::npos &&
573 #ifdef HAVE_COREAUDIO
574                 file.rfind(".mp3") == string::npos &&
575                 file.rfind(".aac") == string::npos &&
576                 file.rfind(".mp4") == string::npos &&
577 #endif // HAVE_COREAUDIO
578                 file.rfind(".voc") == string::npos);
579 }
580
581 void
582 AudioFileSource::mark_immutable ()
583 {
584         _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
585 }