Merged with trunk R1705.
[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/shortpath.h>
33 #include <pbd/enumwriter.h>
34
35 #include <sndfile.h>
36
37 #include <glibmm/miscutils.h>
38 #include <glibmm/fileutils.h>
39
40 #include <ardour/audiofilesource.h>
41 #include <ardour/sndfile_helpers.h>
42 #include <ardour/sndfilesource.h>
43 #include <ardour/session.h>
44 #include <ardour/source_factory.h>
45
46 // if these headers come before sigc++ is included
47 // the parser throws ObjC++ errors. (nil is a keyword)
48 #ifdef HAVE_COREAUDIO 
49 #include <ardour/coreaudiosource.h>
50 #include <AudioToolbox/ExtendedAudioFile.h>
51 #include <AudioToolbox/AudioFormat.h>
52 #endif // HAVE_COREAUDIO
53
54 #include "i18n.h"
55
56 using namespace ARDOUR;
57 using namespace PBD;
58 using namespace Glib;
59
60 ustring AudioFileSource::peak_dir = "";
61 ustring AudioFileSource::search_path;
62
63 sigc::signal<void> AudioFileSource::HeaderPositionOffsetChanged;
64 uint64_t           AudioFileSource::header_position_offset = 0;
65
66 /* XXX maybe this too */
67 char   AudioFileSource::bwf_serial_number[13] = "000000000000";
68
69 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags)
70         : AudioSource (s, path), _flags (flags),
71           _channel (0)
72 {
73         /* constructor used for existing external to session files. file must exist already */
74         _is_embedded = AudioFileSource::determine_embeddedness (path);
75
76         if (init (path, true)) {
77                 throw failed_constructor ();
78         }
79
80 }
81
82 AudioFileSource::AudioFileSource (Session& s, ustring path, Flag flags, SampleFormat samp_format, HeaderFormat hdr_format)
83         : AudioSource (s, path), _flags (flags),
84           _channel (0)
85 {
86         /* constructor used for new internal-to-session files. file cannot exist */
87         _is_embedded = false;
88
89         if (init (path, false)) {
90                 throw failed_constructor ();
91         }
92 }
93
94 AudioFileSource::AudioFileSource (Session& s, const XMLNode& node, bool must_exist)
95         : AudioSource (s, node), _flags (Flag (Writable|CanRename))
96           /* _channel is set in set_state() or init() */
97 {
98         /* constructor used for existing internal-to-session files. file must exist */
99
100         if (set_state (node)) {
101                 throw failed_constructor ();
102         }
103
104         string foo = _name;
105         
106         if (init (foo, must_exist)) {
107                 throw failed_constructor ();
108         }
109 }
110
111 AudioFileSource::~AudioFileSource ()
112 {
113         if (removable()) {
114                 unlink (_path.c_str());
115                 unlink (peakpath.c_str());
116         }
117 }
118
119 bool
120 AudioFileSource::determine_embeddedness (ustring path)
121 {
122         return (path.find("/") == 0);
123 }
124
125 bool
126 AudioFileSource::removable () const
127 {
128         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || ((_flags & RemovableIfEmpty) && length() == 0));
129 }
130
131 int
132 AudioFileSource::init (ustring pathstr, bool must_exist)
133 {
134         bool is_new = false;
135
136         _length = 0;
137         timeline_position = 0;
138         _peaks_built = false;
139         file_is_new = false;
140
141         if (!find (pathstr, must_exist, is_new, _channel)) {
142                 throw non_existent_source ();
143         }
144
145         if (is_new && must_exist) {
146                 return -1;
147         }
148
149         return 0;
150 }
151
152
153 ustring
154 AudioFileSource::peak_path (ustring audio_path)
155 {
156         return _session.peak_path_from_audio_path (audio_path);
157 }
158
159 ustring
160 AudioFileSource::old_peak_path (ustring audio_path)
161 {
162         /* XXX hardly bombproof! fix me */
163
164         struct stat stat_file;
165         struct stat stat_mount;
166
167         ustring mp = mountpoint (audio_path);
168
169         stat (audio_path.c_str(), &stat_file);
170         stat (mp.c_str(), &stat_mount);
171
172         char buf[32];
173 #ifdef __APPLE__
174         snprintf (buf, sizeof (buf), "%u-%u-%d.peak", stat_mount.st_ino, stat_file.st_ino, _channel);
175 #else
176         snprintf (buf, sizeof (buf), "%ld-%ld-%d.peak", stat_mount.st_ino, stat_file.st_ino, _channel);
177 #endif
178
179         ustring res = peak_dir;
180         res += buf;
181
182         return res;
183 }
184
185 bool
186 AudioFileSource::get_soundfile_info (ustring path, SoundFileInfo& _info, string& error_msg)
187 {
188 #ifdef HAVE_COREAUDIO
189         if (CoreAudioSource::get_soundfile_info (path, _info, error_msg) == 0) {
190                 return true;
191         }
192 #endif // HAVE_COREAUDIO
193
194         if (SndFileSource::get_soundfile_info (path, _info, error_msg) != 0) {
195                 return true;
196         }
197
198         return false;
199 }
200
201 XMLNode&
202 AudioFileSource::get_state ()
203 {
204         XMLNode& root (AudioSource::get_state());
205         char buf[32];
206         root.add_property (X_("flags"), enum_2_string (_flags));
207         snprintf (buf, sizeof (buf), "%u", _channel);
208         root.add_property (X_("channel"), buf);
209         return root;
210 }
211
212 int
213 AudioFileSource::set_state (const XMLNode& node)
214 {
215         const XMLProperty* prop;
216
217         if (AudioSource::set_state (node)) {
218                 return -1;
219         }
220
221         if ((prop = node.property (X_("flags"))) != 0) {
222                 _flags = Flag (string_2_enum (prop->value(), _flags));
223         } else {
224                 _flags = Flag (0);
225
226         }
227
228         if ((prop = node.property (X_("channel"))) != 0) {
229                 _channel = atoi (prop->value());
230         } else {
231                 _channel = 0;
232         }
233
234         if ((prop = node.property (X_("name"))) != 0) {
235                 _is_embedded = AudioFileSource::determine_embeddedness (prop->value());
236         } else {
237                 _is_embedded = false;
238         }
239
240         if ((prop = node.property (X_("destructive"))) != 0) {
241                 /* old style, from the period when we had DestructiveFileSource */
242                 _flags = Flag (_flags | Destructive);
243         }
244
245         return 0;
246 }
247
248 void
249 AudioFileSource::mark_for_remove ()
250 {
251         // This operation is not allowed for sources for destructive tracks or embedded files.
252         // Fortunately mark_for_remove() is never called for embedded files. This function
253         // must be fixed if that ever happens.
254         if (_flags & Destructive) {
255                 return;
256         }
257
258         _flags = Flag (_flags | Removable | RemoveAtDestroy);
259 }
260
261 void
262 AudioFileSource::mark_streaming_write_completed ()
263 {
264         if (!writable()) {
265                 return;
266         }
267
268         Glib::Mutex::Lock lm (_lock);
269
270         if (_peaks_built) {
271                 PeaksReady (); /* EMIT SIGNAL */
272         }
273 }
274
275 void
276 AudioFileSource::mark_take (ustring id)
277 {
278         if (writable()) {
279                 _take_id = id;
280         }
281 }
282
283 int
284 AudioFileSource::move_to_trash (const ustring& trash_dir_name)
285 {
286         if (is_embedded()) {
287                 cerr << "tried to move an embedded region to trash" << endl;
288                 return -1;
289         }
290
291         ustring newpath;
292
293         if (!writable()) {
294                 return -1;
295         }
296
297         /* don't move the file across filesystems, just
298            stick it in the `trash_dir_name' directory
299            on whichever filesystem it was already on.
300         */
301         
302         newpath = Glib::path_get_dirname (_path);
303         newpath = Glib::path_get_dirname (newpath); 
304
305         cerr << "from " << _path << " dead dir looks like " << newpath << endl;
306
307         newpath += '/';
308         newpath += trash_dir_name;
309         newpath += '/';
310         newpath += Glib::path_get_basename (_path);
311
312         if (access (newpath.c_str(), F_OK) == 0) {
313
314                 /* the new path already exists, try versioning */
315                 
316                 char buf[PATH_MAX+1];
317                 int version = 1;
318                 ustring newpath_v;
319
320                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
321                 newpath_v = buf;
322
323                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
324                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
325                         newpath_v = buf;
326                 }
327                 
328                 if (version == 999) {
329                         error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
330                                           newpath)
331                               << endmsg;
332                 } else {
333                         newpath = newpath_v;
334                 }
335
336         } else {
337
338                 /* it doesn't exist, or we can't read it or something */
339
340         }
341
342         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
343                 error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
344                                   _path, newpath, strerror (errno))
345                       << endmsg;
346                 return -1;
347         }
348
349         if (::unlink (peakpath.c_str()) != 0) {
350                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
351                                   peakpath, _path, strerror (errno))
352                       << endmsg;
353                 /* try to back out */
354                 rename (newpath.c_str(), _path.c_str());
355                 return -1;
356         }
357             
358         _path = newpath;
359         peakpath = "";
360         
361         /* file can not be removed twice, since the operation is not idempotent */
362
363         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
364
365         return 0;
366 }
367
368 bool
369 AudioFileSource::find (ustring& pathstr, bool must_exist, bool& isnew, uint16_t& chan)
370 {
371         ustring::size_type pos;
372         bool ret = false;
373
374         isnew = false;
375
376         if (pathstr[0] != '/') {
377
378                 /* non-absolute pathname: find pathstr in search path */
379
380                 vector<ustring> dirs;
381                 int cnt;
382                 ustring fullpath;
383                 ustring keeppath;
384
385                 if (search_path.length() == 0) {
386                         error << _("FileSource: search path not set") << endmsg;
387                         goto out;
388                 }
389
390                 split (search_path, dirs, ':');
391
392                 cnt = 0;
393                 
394                 for (vector<ustring>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
395
396                         fullpath = *i;
397                         if (fullpath[fullpath.length()-1] != '/') {
398                                 fullpath += '/';
399                         }
400
401                         fullpath += pathstr;
402
403                         /* i (paul) made a nasty design error by using ':' as a special character in
404                            Ardour 0.99 .. this hack tries to make things sort of work.
405                         */
406                         
407                         if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
408                                 
409                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
410
411                                         /* its a real file, no problem */
412                                         
413                                         keeppath = fullpath;
414                                         ++cnt;
415
416                                 } else {
417                                         
418                                         if (must_exist) {
419                                                 
420                                                 /* might be an older session using file:channel syntax. see if the version
421                                                    without the :suffix exists
422                                                  */
423                                                 
424                                                 ustring shorter = pathstr.substr (0, pos);
425                                                 fullpath = *i;
426
427                                                 if (fullpath[fullpath.length()-1] != '/') {
428                                                         fullpath += '/';
429                                                 }
430
431                                                 fullpath += shorter;
432
433                                                 if (Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
434                                                         chan = atoi (pathstr.substr (pos+1));
435                                                         pathstr = shorter;
436                                                         keeppath = fullpath;
437                                                         ++cnt;
438                                                 } 
439                                                 
440                                         } else {
441                                                 
442                                                 /* new derived file (e.g. for timefx) being created in a newer session */
443                                                 
444                                         }
445                                 }
446
447                         } else {
448
449                                 if (Glib::file_test (fullpath, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
450                                         keeppath = fullpath;
451                                         ++cnt;
452                                 } 
453                         }
454                 }
455
456                 if (cnt > 1) {
457
458                         error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, search_path) << endmsg;
459                         goto out;
460
461                 } else if (cnt == 0) {
462
463                         if (must_exist) {
464                                 error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, search_path) << endmsg;
465                                 goto out;
466                         } else {
467                                 isnew = true;
468                         }
469                 }
470
471                 _name = pathstr;
472                 _path = keeppath;
473                 ret = true;
474
475         } else {
476                 
477                 /* external files and/or very very old style sessions include full paths */
478
479                 /* ugh, handle ':' situation */
480
481                 if ((pos = pathstr.find_last_of (':')) != ustring::npos) {
482                         
483                         ustring shorter = pathstr.substr (0, pos);
484
485                         if (Glib::file_test (shorter, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
486                                 chan = atoi (pathstr.substr (pos+1));
487                                 pathstr = shorter;
488                         }
489                 }
490                 
491                 _path = pathstr;
492
493                 if (is_embedded()) {
494                         _name = pathstr;
495                 } else {
496                         _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
497                 }
498
499                 if (!Glib::file_test (pathstr, Glib::FILE_TEST_EXISTS|Glib::FILE_TEST_IS_REGULAR)) {
500
501                         /* file does not exist or we cannot read it */
502                         
503                         if (must_exist) {
504                                 error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
505                                 goto out;
506                         }
507                         
508                         if (errno != ENOENT) {
509                                 error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
510                                 goto out;
511                         }
512                         
513                         /* a new file */
514
515                         isnew = true;
516                         ret = true;
517
518                 } else {
519                         
520                         /* already exists */
521
522                         ret = true;
523
524                 }
525         }
526         
527   out:
528         return ret;
529 }
530
531 void
532 AudioFileSource::set_search_path (ustring p)
533 {
534         search_path = p;
535 }
536
537 void
538 AudioFileSource::set_header_position_offset (nframes_t offset)
539 {
540         header_position_offset = offset;
541         HeaderPositionOffsetChanged ();
542 }
543
544 void 
545 AudioFileSource::handle_header_position_change ()
546 {
547         if (writable()) {
548                 set_header_timeline_position ();
549                 flush_header ();
550         }
551 }
552
553 void
554 AudioFileSource::set_timeline_position (int64_t pos)
555 {
556         timeline_position = pos;
557 }
558
559 void
560 AudioFileSource::set_allow_remove_if_empty (bool yn)
561 {
562         if (!writable()) {
563                 return;
564         }
565
566         if (yn) {
567                 _flags = Flag (_flags | RemovableIfEmpty);
568         } else {
569                 _flags = Flag (_flags & ~RemovableIfEmpty);
570         }
571 }
572
573 int
574 AudioFileSource::set_name (ustring newname, bool destructive)
575 {
576         Glib::Mutex::Lock lm (_lock);
577         ustring oldpath = _path;
578         ustring newpath = Session::change_audio_path_by_name (oldpath, _name, newname, destructive);
579
580         if (newpath.empty()) {
581                 error << string_compose (_("programming error: %1"), "cannot generate a changed audio path") << endmsg;
582                 return -1;
583         }
584
585         // Test whether newpath exists, if yes notify the user but continue. 
586         if (access(newpath.c_str(),F_OK) == 0) {
587                 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;
588                 return -1;
589         }
590
591         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
592                 error << string_compose (_("cannot rename audio file %1 to %2"), _name, newpath) << endmsg;
593                 return -1;
594         }
595
596         _name = Glib::path_get_basename (newpath);
597         _path = newpath;
598
599         return rename_peakfile (peak_path (_path));
600 }
601
602 bool
603 AudioFileSource::is_empty (Session& s, ustring path)
604 {
605         bool ret = false;
606         
607         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable (DataType::AUDIO, s, path, 0, NoPeakFile, false));
608
609         if (afs) {
610                 ret = (afs->length() == 0);
611         }
612
613         return ret;
614 }
615
616 int
617 AudioFileSource::setup_peakfile ()
618 {
619         if (!(_flags & NoPeakFile)) {
620                 return initialize_peakfile (file_is_new, _path);
621         } else {
622                 return 0;
623         }
624 }
625
626 bool
627 AudioFileSource::safe_file_extension(ustring file)
628 {
629         return !(file.rfind(".wav") == ustring::npos &&
630                 file.rfind(".aiff")== ustring::npos &&
631                 file.rfind(".aif") == ustring::npos &&
632                 file.rfind(".snd") == ustring::npos &&
633                 file.rfind(".au")  == ustring::npos &&
634                 file.rfind(".raw") == ustring::npos &&
635                 file.rfind(".sf")  == ustring::npos &&
636                 file.rfind(".cdr") == ustring::npos &&
637                 file.rfind(".smp") == ustring::npos &&
638                 file.rfind(".maud")== ustring::npos &&
639                 file.rfind(".vwe") == ustring::npos &&
640                 file.rfind(".paf") == ustring::npos &&
641 #ifdef HAVE_FLAC
642                 file.rfind(".flac")== ustring::npos &&
643 #endif // HAVE_FLAC
644 #ifdef HAVE_COREAUDIO
645                 file.rfind(".mp3") == ustring::npos &&
646                 file.rfind(".aac") == ustring::npos &&
647                 file.rfind(".mp4") == ustring::npos &&
648 #endif // HAVE_COREAUDIO
649                 file.rfind(".voc") == ustring::npos);
650 }
651
652 void
653 AudioFileSource::mark_immutable ()
654 {
655         /* destructive sources stay writable, and their other flags don't
656            change.
657         */
658
659         if (!(_flags & Destructive)) {
660                 _flags = Flag (_flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy|CanRename));
661         }
662 }