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