display timecode from BWF etc in SF browser; accels for windows now work (misspelling...
[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 <errno.h>
26
27 #include <pbd/mountpoint.h>
28 #include <pbd/pathscanner.h>
29 #include <pbd/stl_delete.h>
30 #include <pbd/strsplit.h>
31
32 #include <sndfile.h>
33
34 #include <glibmm/miscutils.h>
35
36 #include <ardour/audiofilesource.h>
37 #include <ardour/sndfile_helpers.h>
38 #include <ardour/sndfilesource.h>
39 #include <ardour/session.h>
40 #include <ardour/source_factory.h>
41
42 // if these headers come before sigc++ is included
43 // the parser throws ObjC++ errors. (nil is a keyword)
44 #ifdef HAVE_COREAUDIO 
45 #include <ardour/coreaudiosource.h>
46 #include <AudioToolbox/ExtendedAudioFile.h>
47 #include <AudioToolbox/AudioFormat.h>
48 #endif // HAVE_COREAUDIO
49
50 #include "i18n.h"
51
52 using namespace ARDOUR;
53 using namespace PBD;
54
55 string AudioFileSource::peak_dir = "";
56 string AudioFileSource::search_path;
57
58 sigc::signal<void> AudioFileSource::HeaderPositionOffsetChanged;
59 uint64_t           AudioFileSource::header_position_offset = 0;
60
61 /* XXX maybe this too */
62 char   AudioFileSource::bwf_serial_number[13] = "000000000000";
63
64 AudioFileSource::AudioFileSource (Session& s, string idstr, Flag flags)
65         : AudioSource (s, idstr), _flags (flags)
66 {
67         /* constructor used for existing external to session files. file must exist already */
68         _is_embedded = AudioFileSource::determine_embeddedness (idstr);
69
70         if (init (idstr, true)) {
71                 throw failed_constructor ();
72         }
73
74 }
75
76 AudioFileSource::AudioFileSource (Session& s, std::string path, Flag flags, SampleFormat samp_format, HeaderFormat hdr_format)
77         : AudioSource (s, path), _flags (flags)
78 {
79         /* constructor used for new internal-to-session files. file cannot exist */
80         _is_embedded = false;
81
82         if (init (path, false)) {
83                 throw failed_constructor ();
84         }
85 }
86
87 AudioFileSource::AudioFileSource (Session& s, const XMLNode& node)
88         : AudioSource (s, node), _flags (Flag (Writable|CanRename))
89 {
90         /* constructor used for existing internal-to-session files. file must exist */
91
92         if (set_state (node)) {
93                 throw failed_constructor ();
94         }
95         
96         if (init (_name, true)) {
97                 throw failed_constructor ();
98         }
99 }
100
101 AudioFileSource::~AudioFileSource ()
102 {
103         if (removable()) {
104                 unlink (_path.c_str());
105                 unlink (peakpath.c_str());
106         }
107 }
108
109 bool
110 AudioFileSource::determine_embeddedness (std::string path)
111 {
112         return (path.find("/") == 0);
113 }
114
115 bool
116 AudioFileSource::removable () const
117 {
118         return (_flags & Removable) && ((_flags & RemoveAtDestroy) || ((_flags & RemovableIfEmpty) && length() == 0));
119 }
120
121 int
122 AudioFileSource::init (string pathstr, bool must_exist)
123 {
124         bool is_new = false;
125
126         _length = 0;
127         timeline_position = 0;
128         next_peak_clear_should_notify = false;
129         _peaks_built = false;
130         file_is_new = false;
131
132         if (!find (pathstr, must_exist, is_new)) {
133                 return -1;
134         }
135
136         if (is_new && must_exist) {
137                 return -1;
138         }
139
140         return 0;
141 }
142
143
144 string
145 AudioFileSource::peak_path (string audio_path)
146 {
147         return _session.peak_path_from_audio_path (audio_path);
148 }
149
150 string
151 AudioFileSource::old_peak_path (string audio_path)
152 {
153         /* XXX hardly bombproof! fix me */
154
155         struct stat stat_file;
156         struct stat stat_mount;
157
158         string mp = mountpoint (audio_path);
159
160         stat (audio_path.c_str(), &stat_file);
161         stat (mp.c_str(), &stat_mount);
162
163         char buf[32];
164 #ifdef __APPLE__
165         snprintf (buf, sizeof (buf), "%u-%u-%d.peak", stat_mount.st_ino, stat_file.st_ino, channel);
166 #else
167         snprintf (buf, sizeof (buf), "%ld-%ld-%d.peak", stat_mount.st_ino, stat_file.st_ino, channel);
168 #endif
169
170         string res = peak_dir;
171         res += buf;
172
173         return res;
174 }
175
176 bool
177 AudioFileSource::get_soundfile_info (string path, SoundFileInfo& _info, string& error_msg)
178 {
179 #ifdef HAVE_COREAUDIO
180         if (CoreAudioSource::get_soundfile_info (path, _info, error_msg) == 0) {
181                 return true;
182         }
183 #endif // HAVE_COREAUDIO
184
185         if (SndFileSource::get_soundfile_info (path, _info, error_msg) != 0) {
186                 return true;
187         }
188
189         return false;
190 }
191
192 XMLNode&
193 AudioFileSource::get_state ()
194 {
195         XMLNode& root (AudioSource::get_state());
196         char buf[16];
197         snprintf (buf, sizeof (buf), "0x%x", (int)_flags);
198         root.add_property ("flags", buf);
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                 int ival;
214                 sscanf (prop->value().c_str(), "0x%x", &ival);
215                 _flags = Flag (ival);
216
217         } else {
218
219                 _flags = Flag (0);
220
221         }
222
223         if ((prop = node.property (X_("name"))) != 0) {
224                 _is_embedded = AudioFileSource::determine_embeddedness (prop->value());
225         } else {
226                 _is_embedded = false;
227         }
228
229         if ((prop = node.property (X_("destructive"))) != 0) {
230                 /* old style, from the period when we had DestructiveFileSource */
231                 _flags = Flag (_flags | Destructive);
232         }
233
234         return 0;
235 }
236
237 void
238 AudioFileSource::mark_for_remove ()
239 {
240         if (!writable()) {
241                 return;
242         }
243
244         _flags = Flag (_flags | Removable | RemoveAtDestroy);
245 }
246
247 void
248 AudioFileSource::mark_streaming_write_completed ()
249 {
250         if (!writable()) {
251                 return;
252         }
253
254         Glib::Mutex::Lock lm (_lock);
255
256         next_peak_clear_should_notify = true;
257
258         if (_peaks_built || pending_peak_builds.empty()) {
259                 _peaks_built = true;
260                  PeaksReady (); /* EMIT SIGNAL */
261         }
262 }
263
264 void
265 AudioFileSource::mark_take (string id)
266 {
267         if (writable()) {
268                 _take_id = id;
269         }
270 }
271
272 int
273 AudioFileSource::move_to_trash (const string trash_dir_name)
274 {
275         if (is_embedded()) {
276                 cerr << "tried to move an embedded region to trash" << endl;
277                 return -1;
278         }
279
280         string newpath;
281
282         if (!writable()) {
283                 return -1;
284         }
285
286         /* don't move the file across filesystems, just
287            stick it in the `trash_dir_name' directory
288            on whichever filesystem it was already on.
289         */
290
291         newpath = Glib::path_get_dirname (_path);
292         newpath = Glib::path_get_dirname (newpath);
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 for %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 }