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