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