First pass of sfdb tag searching. Not functional, but very very close.
[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         newpath += '/';
293         newpath += trash_dir_name;
294         newpath += '/';
295         newpath += Glib::path_get_basename (_path);
296
297         if (access (newpath.c_str(), F_OK) == 0) {
298
299                 /* the new path already exists, try versioning */
300                 
301                 char buf[PATH_MAX+1];
302                 int version = 1;
303                 string newpath_v;
304
305                 snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), version);
306                 newpath_v = buf;
307
308                 while (access (newpath_v.c_str(), F_OK) == 0 && version < 999) {
309                         snprintf (buf, sizeof (buf), "%s.%d", newpath.c_str(), ++version);
310                         newpath_v = buf;
311                 }
312                 
313                 if (version == 999) {
314                         error << string_compose (_("there are already 1000 files with names like %1; versioning discontinued"),
315                                           newpath)
316                               << endmsg;
317                 } else {
318                         newpath = newpath_v;
319                 }
320
321         } else {
322
323                 /* it doesn't exist, or we can't read it or something */
324
325         }
326
327         if (::rename (_path.c_str(), newpath.c_str()) != 0) {
328                 error << string_compose (_("cannot rename audio file source from %1 to %2 (%3)"),
329                                   _path, newpath, strerror (errno))
330                       << endmsg;
331                 return -1;
332         }
333
334         if (::unlink (peakpath.c_str()) != 0) {
335                 error << string_compose (_("cannot remove peakfile %1 for %2 (%3)"),
336                                   peakpath, _path, strerror (errno))
337                       << endmsg;
338                 /* try to back out */
339                 rename (newpath.c_str(), _path.c_str());
340                 return -1;
341         }
342             
343         _path = newpath;
344         peakpath = "";
345         
346         /* file can not be removed twice, since the operation is not idempotent */
347
348         _flags = Flag (_flags & ~(RemoveAtDestroy|Removable|RemovableIfEmpty));
349
350         return 0;
351 }
352
353 bool
354 AudioFileSource::find (string pathstr, bool must_exist, bool& isnew)
355 {
356         string::size_type pos;
357         bool ret = false;
358
359         isnew = false;
360
361         /* clean up PATH:CHANNEL notation so that we are looking for the correct path */
362
363         if ((pos = pathstr.find_last_of (':')) == string::npos) {
364                 pathstr = pathstr;
365         } else {
366                 pathstr = pathstr.substr (0, pos);
367         }
368
369         if (pathstr[0] != '/') {
370
371                 /* non-absolute pathname: find pathstr in search path */
372
373                 vector<string> dirs;
374                 int cnt;
375                 string fullpath;
376                 string keeppath;
377
378                 if (search_path.length() == 0) {
379                         error << _("FileSource: search path not set") << endmsg;
380                         goto out;
381                 }
382
383                 split (search_path, dirs, ':');
384
385                 cnt = 0;
386                 
387                 for (vector<string>::iterator i = dirs.begin(); i != dirs.end(); ++i) {
388
389                         fullpath = *i;
390                         if (fullpath[fullpath.length()-1] != '/') {
391                                 fullpath += '/';
392                         }
393                         fullpath += pathstr;
394                         
395                         if (access (fullpath.c_str(), R_OK) == 0) {
396                                 keeppath = fullpath;
397                                 ++cnt;
398                         } 
399                 }
400
401                 if (cnt > 1) {
402
403                         error << string_compose (_("FileSource: \"%1\" is ambigous when searching %2\n\t"), pathstr, search_path) << endmsg;
404                         goto out;
405
406                 } else if (cnt == 0) {
407
408                         if (must_exist) {
409                                 error << string_compose(_("Filesource: cannot find required file (%1): while searching %2"), pathstr, search_path) << endmsg;
410                                 goto out;
411                         } else {
412                                 isnew = true;
413                         }
414                 }
415                 
416                 _name = pathstr;
417                 _path = keeppath;
418                 ret = true;
419
420         } else {
421                 
422                 /* external files and/or very very old style sessions include full paths */
423                 
424                 _path = pathstr;
425                 if (is_embedded()) {
426                         _name = pathstr;
427                 } else {
428                         _name = pathstr.substr (pathstr.find_last_of ('/') + 1);
429                 }
430                 
431                 if (access (_path.c_str(), R_OK) != 0) {
432
433                         /* file does not exist or we cannot read it */
434
435                         if (must_exist) {
436                                 error << string_compose(_("Filesource: cannot find required file (%1): %2"), _path, strerror (errno)) << endmsg;
437                                 goto out;
438                         }
439                         
440                         if (errno != ENOENT) {
441                                 error << string_compose(_("Filesource: cannot check for existing file (%1): %2"), _path, strerror (errno)) << endmsg;
442                                 goto out;
443                         }
444                         
445                         /* a new file */
446
447                         isnew = true;
448                         ret = true;
449
450                 } else {
451                         
452                         /* already exists */
453
454                         ret = true;
455                 }
456         }
457         
458   out:
459         return ret;
460 }
461
462 void
463 AudioFileSource::set_search_path (string p)
464 {
465         search_path = p;
466 }
467
468 void
469 AudioFileSource::set_header_position_offset (nframes_t offset)
470 {
471         header_position_offset = offset;
472         HeaderPositionOffsetChanged ();
473 }
474
475 void
476 AudioFileSource::set_timeline_position (int64_t pos)
477 {
478         timeline_position = pos;
479 }
480
481 void
482 AudioFileSource::set_allow_remove_if_empty (bool yn)
483 {
484         if (!writable()) {
485                 return;
486         }
487
488         if (yn) {
489                 _flags = Flag (_flags | RemovableIfEmpty);
490         } else {
491                 _flags = Flag (_flags & ~RemovableIfEmpty);
492         }
493 }
494
495 int
496 AudioFileSource::set_name (string newname, bool destructive)
497 {
498         Glib::Mutex::Lock lm (_lock);
499         string oldpath = _path;
500         string newpath = Session::change_audio_path_by_name (oldpath, _name, newname, destructive);
501
502         if (newpath.empty()) {
503                 error << string_compose (_("programming error: %1"), "cannot generate a changed audio path") << endmsg;
504                 return -1;
505         }
506
507         // Test whether newpath exists, if yes notify the user but continue. 
508         if (access(newpath.c_str(),F_OK) == 0) {
509                 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;
510                 return -1;
511         }
512
513         if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
514                 error << string_compose (_("cannot rename audio file for %1 to %2"), _name, newpath) << endmsg;
515                 return -1;
516         }
517
518         _name = Glib::path_get_basename (newpath);
519         _path = newpath;
520
521         return rename_peakfile (peak_path (_path));
522 }
523
524 bool
525 AudioFileSource::is_empty (Session& s, string path)
526 {
527         bool ret = false;
528         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable (s, path, NoPeakFile, false));
529
530         if (afs) {
531                 ret = (afs->length() == 0);
532         }
533
534         return ret;
535 }
536
537 int
538 AudioFileSource::setup_peakfile ()
539 {
540         if (!(_flags & NoPeakFile)) {
541                 return initialize_peakfile (file_is_new, _path);
542         } else {
543                 return 0;
544         }
545 }
546
547 bool
548 AudioFileSource::safe_file_extension(string file)
549 {
550         return !(file.rfind(".wav") == string::npos &&
551                 file.rfind(".aiff")== string::npos &&
552                 file.rfind(".aif") == string::npos &&
553                 file.rfind(".snd") == string::npos &&
554                 file.rfind(".au")  == string::npos &&
555                 file.rfind(".raw") == string::npos &&
556                 file.rfind(".sf")  == string::npos &&
557                 file.rfind(".cdr") == string::npos &&
558                 file.rfind(".smp") == string::npos &&
559                 file.rfind(".maud")== string::npos &&
560                 file.rfind(".vwe") == string::npos &&
561                 file.rfind(".paf") == string::npos &&
562 #ifdef HAVE_COREAUDIO
563                 file.rfind(".mp3") == string::npos &&
564                 file.rfind(".aac") == string::npos &&
565                 file.rfind(".mp4") == string::npos &&
566 #endif // HAVE_COREAUDIO
567                 file.rfind(".voc") == string::npos);
568 }