2 Copyright (C) 2006 Paul Davis
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.
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.
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.
21 #include "libardour-config.h"
30 #include <sys/utsname.h>
33 #include <glibmm/miscutils.h>
35 #include "ardour/sndfilesource.h"
36 #include "ardour/sndfile_helpers.h"
37 #include "ardour/utils.h"
38 #include "ardour/version.h"
39 #include "ardour/rc_configuration.h"
40 #include "ardour/session.h"
45 using namespace ARDOUR;
49 gain_t* SndFileSource::out_coefficient = 0;
50 gain_t* SndFileSource::in_coefficient = 0;
51 framecnt_t SndFileSource::xfade_frames = 64;
52 const Source::Flag SndFileSource::default_writable_flags = Source::Flag (
55 Source::RemovableIfEmpty |
58 SndFileSource::SndFileSource (Session& s, const XMLNode& node)
60 , AudioFileSource (s, node)
65 throw failed_constructor ();
69 /** Files created this way are never writable or removable */
70 SndFileSource::SndFileSource (Session& s, const string& path, int chn, Flag flags)
71 : Source(s, DataType::AUDIO, path, flags)
72 /* note that the origin of an external file is itself */
73 , AudioFileSource (s, path, Flag (flags & ~(Writable|Removable|RemovableIfEmpty|RemoveAtDestroy)))
80 throw failed_constructor ();
84 /** This constructor is used to construct new files, not open existing ones. */
85 SndFileSource::SndFileSource (Session& s, const string& path, const string& origin,
86 SampleFormat sfmt, HeaderFormat hf, framecnt_t rate, Flag flags)
87 : Source(s, DataType::AUDIO, path, flags)
88 , AudioFileSource (s, path, origin, flags, sfmt, hf)
99 _flags = Flag (_flags & ~Broadcast);
103 fmt = SF_FORMAT_AIFF;
104 _flags = Flag (_flags & ~Broadcast);
109 _flags = Flag (_flags | Broadcast);
114 _flags = Flag (_flags & ~Broadcast);
119 _flags = Flag (_flags & ~Broadcast);
123 fatal << string_compose (_("programming error: %1"), X_("unsupported audio header format requested")) << endmsg;
131 fmt |= SF_FORMAT_FLOAT;
135 fmt |= SF_FORMAT_PCM_24;
139 fmt |= SF_FORMAT_PCM_16;
144 _info.samplerate = rate;
147 if (_flags & Destructive) {
149 throw failed_constructor();
152 /* normal mode: do not open the file here - do that in write_unlocked() as needed
158 SndFileSource::init_sndfile ()
164 // lets try to keep the object initalizations here at the top
168 /* although libsndfile says we don't need to set this,
169 valgrind and source code shows us that we do.
172 memset (&_info, 0, sizeof(_info));
174 _capture_start = false;
175 _capture_end = false;
179 xfade_buf = new Sample[xfade_frames];
180 _timeline_position = header_position_offset;
183 AudioFileSource::HeaderPositionOffsetChanged.connect_same_thread (header_position_connection, boost::bind (&SndFileSource::handle_header_position_change, this));
187 SndFileSource::open ()
189 _descriptor = new SndFileDescriptor (_path, writable(), &_info);
190 _descriptor->Closed.connect_same_thread (file_manager_connection, boost::bind (&SndFileSource::file_closed, this));
191 SNDFILE* sf = _descriptor->allocate ();
195 sf_error_str (0, errbuf, sizeof (errbuf) - 1);
196 #ifndef HAVE_COREAUDIO
197 /* if we have CoreAudio, we will be falling back to that if libsndfile fails,
198 so we don't want to see this message.
201 cerr << "failed to open " << _path << " with name " << _name << endl;
203 error << string_compose(_("SndFileSource: cannot open file \"%1\" for %2 (%3)"),
204 _path, (writable() ? "read+write" : "reading"), errbuf) << endmsg;
209 if (_channel >= _info.channels) {
210 #ifndef HAVE_COREAUDIO
211 error << string_compose(_("SndFileSource: file only contains %1 channels; %2 is invalid as a channel number"), _info.channels, _channel) << endmsg;
218 _length = _info.frames;
220 if (!_broadcast_info) {
221 _broadcast_info = new BroadcastInfo;
224 bool bwf_info_exists = _broadcast_info->load_from_file (sf);
226 /* Set our timeline position to either the time reference from a BWF header or the current
227 start of the session.
229 set_timeline_position (bwf_info_exists ? _broadcast_info->get_time_reference() : header_position_offset);
231 if (_length != 0 && !bwf_info_exists) {
232 delete _broadcast_info;
234 _flags = Flag (_flags & ~Broadcast);
238 sf_command (sf, SFC_SET_UPDATE_HEADER_AUTO, 0, SF_FALSE);
240 if (_flags & Broadcast) {
242 if (!_broadcast_info) {
243 _broadcast_info = new BroadcastInfo;
246 _broadcast_info->set_from_session (_session, header_position_offset);
247 _broadcast_info->set_description (string_compose ("BWF %1", _name));
249 if (!_broadcast_info->write_to_file (sf)) {
250 error << string_compose (_("cannot set broadcast info for audio file %1 (%2); dropping broadcast info for this file"),
251 _path, _broadcast_info->get_error())
253 _flags = Flag (_flags & ~Broadcast);
254 delete _broadcast_info;
260 _descriptor->release ();
265 SndFileSource::~SndFileSource ()
268 delete _broadcast_info;
273 SndFileSource::sample_rate () const
275 return _info.samplerate;
279 SndFileSource::read_unlocked (Sample *dst, framepos_t start, framecnt_t cnt) const
288 if (writable() && !_open) {
289 /* file has not been opened yet - nothing written to it */
290 memset (dst, 0, sizeof (Sample) * cnt);
294 SNDFILE* sf = _descriptor->allocate ();
297 error << string_compose (_("could not allocate file %1 for reading."), _path) << endmsg;
301 if (start > _length) {
303 /* read starts beyond end of data, just memset to zero */
307 } else if (start + cnt > _length) {
309 /* read ends beyond end of data, read some, memset the rest */
311 file_cnt = _length - start;
315 /* read is entirely within data */
320 assert (file_cnt >= 0);
322 if (file_cnt != cnt) {
323 framepos_t delta = cnt - file_cnt;
324 memset (dst+file_cnt, 0, sizeof (Sample) * delta);
329 if (sf_seek (sf, (sf_count_t) start, SEEK_SET|SFM_READ) != (sf_count_t) start) {
331 sf_error_str (0, errbuf, sizeof (errbuf) - 1);
332 error << string_compose(_("SndFileSource: could not seek to frame %1 within %2 (%3)"), start, _name.val().substr (1), errbuf) << endmsg;
333 _descriptor->release ();
337 if (_info.channels == 1) {
338 framecnt_t ret = sf_read_float (sf, dst, file_cnt);
339 if (ret != file_cnt) {
341 sf_error_str (0, errbuf, sizeof (errbuf) - 1);
342 error << string_compose(_("SndFileSource: @ %1 could not read %2 within %3 (%4) (len = %5)"), start, file_cnt, _name.val().substr (1), errbuf, _length) << endl;
344 _descriptor->release ();
349 real_cnt = cnt * _info.channels;
351 Sample* interleave_buf = get_interleave_buffer (real_cnt);
353 nread = sf_read_float (sf, interleave_buf, real_cnt);
354 ptr = interleave_buf + _channel;
355 nread /= _info.channels;
357 /* stride through the interleaved data */
359 for (int32_t n = 0; n < nread; ++n) {
361 ptr += _info.channels;
364 _descriptor->release ();
369 SndFileSource::write_unlocked (Sample *data, framecnt_t cnt)
371 if (!_open && open()) {
376 return destructive_write_unlocked (data, cnt);
378 return nondestructive_write_unlocked (data, cnt);
383 SndFileSource::nondestructive_write_unlocked (Sample *data, framecnt_t cnt)
386 warning << string_compose (_("attempt to write a non-writable audio file source (%1)"), _path) << endmsg;
390 if (_info.channels != 1) {
391 fatal << string_compose (_("programming error: %1 %2"), X_("SndFileSource::write called on non-mono file"), _path) << endmsg;
396 int32_t frame_pos = _length;
398 if (write_float (data, frame_pos, cnt) != cnt) {
402 update_length (_length + cnt);
404 if (_build_peakfiles) {
405 compute_and_write_peaks (data, frame_pos, cnt, false, true);
412 SndFileSource::destructive_write_unlocked (Sample* data, framecnt_t cnt)
415 warning << string_compose (_("attempt to write a non-writable audio file source (%1)"), _path) << endmsg;
419 if (_capture_start && _capture_end) {
421 /* start and end of capture both occur within the data we are writing,
422 so do both crossfades.
425 _capture_start = false;
426 _capture_end = false;
428 /* move to the correct location place */
429 file_pos = capture_start_frame - _timeline_position;
432 framecnt_t subcnt = cnt / 2;
433 framecnt_t ofilepos = file_pos;
436 if (crossfade (data, subcnt, 1) != subcnt) {
441 Sample * tmpdata = data + subcnt;
444 subcnt = cnt - subcnt;
445 if (crossfade (tmpdata, subcnt, 0) != subcnt) {
449 file_pos = ofilepos; // adjusted below
451 } else if (_capture_start) {
453 /* start of capture both occur within the data we are writing,
457 _capture_start = false;
458 _capture_end = false;
460 /* move to the correct location place */
461 file_pos = capture_start_frame - _timeline_position;
463 if (crossfade (data, cnt, 1) != cnt) {
467 } else if (_capture_end) {
469 /* end of capture both occur within the data we are writing,
473 _capture_start = false;
474 _capture_end = false;
476 if (crossfade (data, cnt, 0) != cnt) {
482 /* in the middle of recording */
484 if (write_float (data, file_pos, cnt) != cnt) {
489 update_length (file_pos + cnt);
491 if (_build_peakfiles) {
492 compute_and_write_peaks (data, file_pos, cnt, false, true);
501 SndFileSource::update_header (framepos_t when, struct tm& now, time_t tnow)
503 set_timeline_position (when);
505 if (_flags & Broadcast) {
506 if (setup_broadcast_info (when, now, tnow)) {
511 return flush_header ();
515 SndFileSource::flush_header ()
518 warning << string_compose (_("attempt to flush a non-writable audio file source (%1)"), _path) << endmsg;
523 warning << string_compose (_("attempt to flush an un-opened audio file source (%1)"), _path) << endmsg;
527 SNDFILE* sf = _descriptor->allocate ();
529 error << string_compose (_("could not allocate file %1 to write header"), _path) << endmsg;
533 int const r = sf_command (sf, SFC_UPDATE_HEADER_NOW, 0, 0) != SF_TRUE;
534 _descriptor->release ();
540 SndFileSource::setup_broadcast_info (framepos_t /*when*/, struct tm& now, time_t /*tnow*/)
543 warning << string_compose (_("attempt to store broadcast info in a non-writable audio file source (%1)"), _path) << endmsg;
548 warning << string_compose (_("attempt to set BWF info for an un-opened audio file source (%1)"), _path) << endmsg;
552 if (!(_flags & Broadcast)) {
556 _broadcast_info->set_originator_ref_from_session (_session);
557 _broadcast_info->set_origination_time (&now);
559 /* now update header position taking header offset into account */
561 set_header_timeline_position ();
563 SNDFILE* sf = _descriptor->allocate ();
565 if (sf == 0 || !_broadcast_info->write_to_file (sf)) {
566 error << string_compose (_("cannot set broadcast info for audio file %1 (%2); dropping broadcast info for this file"),
567 _path, _broadcast_info->get_error())
569 _flags = Flag (_flags & ~Broadcast);
570 delete _broadcast_info;
574 _descriptor->release ();
579 SndFileSource::set_header_timeline_position ()
581 if (!(_flags & Broadcast)) {
585 _broadcast_info->set_time_reference (_timeline_position);
587 SNDFILE* sf = _descriptor->allocate ();
589 if (sf == 0 || !_broadcast_info->write_to_file (sf)) {
590 error << string_compose (_("cannot set broadcast info for audio file %1 (%2); dropping broadcast info for this file"),
591 _path, _broadcast_info->get_error())
593 _flags = Flag (_flags & ~Broadcast);
594 delete _broadcast_info;
598 _descriptor->release ();
602 SndFileSource::write_float (Sample* data, framepos_t frame_pos, framecnt_t cnt)
604 SNDFILE* sf = _descriptor->allocate ();
606 if (sf == 0 || sf_seek (sf, frame_pos, SEEK_SET|SFM_WRITE) < 0) {
608 sf_error_str (0, errbuf, sizeof (errbuf) - 1);
609 error << string_compose (_("%1: cannot seek to %2 (libsndfile error: %3"), _path, frame_pos, errbuf) << endmsg;
610 _descriptor->release ();
614 if (sf_writef_float (sf, data, cnt) != (ssize_t) cnt) {
615 _descriptor->release ();
619 _descriptor->release ();
624 SndFileSource::natural_position() const
626 return _timeline_position;
630 SndFileSource::set_destructive (bool yn)
633 _flags = Flag (_flags | Writable | Destructive);
635 xfade_buf = new Sample[xfade_frames];
637 clear_capture_marks ();
638 _timeline_position = header_position_offset;
640 _flags = Flag (_flags & ~Destructive);
641 _timeline_position = 0;
642 /* leave xfade buf alone in case we need it again later */
649 SndFileSource::clear_capture_marks ()
651 _capture_start = false;
652 _capture_end = false;
655 /** @param pos Capture start position in session frames */
657 SndFileSource::mark_capture_start (framepos_t pos)
660 if (pos < _timeline_position) {
661 _capture_start = false;
663 _capture_start = true;
664 capture_start_frame = pos;
670 SndFileSource::mark_capture_end()
678 SndFileSource::crossfade (Sample* data, framecnt_t cnt, int fade_in)
680 framecnt_t xfade = min (xfade_frames, cnt);
681 framecnt_t nofade = cnt - xfade;
682 Sample* fade_data = 0;
683 framepos_t fade_position = 0; // in frames
688 fade_position = file_pos;
691 fade_position = file_pos + nofade;
692 fade_data = data + nofade;
695 if (fade_position > _length) {
697 /* read starts beyond end of data, just memset to zero */
701 } else if (fade_position + xfade > _length) {
703 /* read ends beyond end of data, read some, memset the rest */
705 file_cnt = _length - fade_position;
709 /* read is entirely within data */
716 if ((retval = read_unlocked (xfade_buf, fade_position, file_cnt)) != (ssize_t) file_cnt) {
717 if (retval >= 0 && errno == EAGAIN) {
718 /* XXX - can we really trust that errno is meaningful here? yes POSIX, i'm talking to you.
719 * short or no data there */
720 memset (xfade_buf, 0, xfade * sizeof(Sample));
722 error << string_compose(_("SndFileSource: \"%1\" bad read retval: %2 of %5 (%3: %4)"), _path, retval, errno, strerror (errno), xfade) << endmsg;
728 if (file_cnt != xfade) {
729 framecnt_t delta = xfade - file_cnt;
730 memset (xfade_buf+file_cnt, 0, sizeof (Sample) * delta);
733 if (nofade && !fade_in) {
734 if (write_float (data, file_pos, nofade) != nofade) {
735 error << string_compose(_("SndFileSource: \"%1\" bad write (%2)"), _path, strerror (errno)) << endmsg;
740 if (xfade == xfade_frames) {
744 /* use the standard xfade curve */
748 /* fade new material in */
750 for (n = 0; n < xfade; ++n) {
751 xfade_buf[n] = (xfade_buf[n] * out_coefficient[n]) + (fade_data[n] * in_coefficient[n]);
757 /* fade new material out */
759 for (n = 0; n < xfade; ++n) {
760 xfade_buf[n] = (xfade_buf[n] * in_coefficient[n]) + (fade_data[n] * out_coefficient[n]);
764 } else if (xfade < xfade_frames) {
769 /* short xfade, compute custom curve */
771 compute_equal_power_fades (xfade, in, out);
773 for (framecnt_t n = 0; n < xfade; ++n) {
774 xfade_buf[n] = (xfade_buf[n] * out[n]) + (fade_data[n] * in[n]);
779 /* long xfade length, has to be computed across several calls */
784 if (write_float (xfade_buf, fade_position, xfade) != xfade) {
785 error << string_compose(_("SndFileSource: \"%1\" bad write (%2)"), _path, strerror (errno)) << endmsg;
790 if (fade_in && nofade) {
791 if (write_float (data + xfade, file_pos + xfade, nofade) != nofade) {
792 error << string_compose(_("SndFileSource: \"%1\" bad write (%2)"), _path, strerror (errno)) << endmsg;
801 SndFileSource::last_capture_start_frame () const
804 return capture_start_frame;
811 SndFileSource::handle_header_position_change ()
814 if ( _length != 0 ) {
815 error << string_compose(_("Filesource: start time is already set for existing file (%1): Cannot change start time."), _path ) << endmsg;
816 //in the future, pop up a dialog here that allows user to regenerate file with new start offset
817 } else if (writable()) {
818 _timeline_position = header_position_offset;
819 set_header_timeline_position (); //this will get flushed if/when the file is recorded to
825 SndFileSource::setup_standard_crossfades (Session const & s, framecnt_t rate)
827 /* This static method is assumed to have been called by the Session
828 before any DFS's are created.
831 xfade_frames = (framecnt_t) floor ((s.config.get_destructive_xfade_msecs () / 1000.0) * rate);
833 delete [] out_coefficient;
834 delete [] in_coefficient;
836 out_coefficient = new gain_t[xfade_frames];
837 in_coefficient = new gain_t[xfade_frames];
839 compute_equal_power_fades (xfade_frames, in_coefficient, out_coefficient);
843 SndFileSource::set_timeline_position (framepos_t pos)
845 // destructive track timeline postion does not change
846 // except at instantion or when header_position_offset
847 // (session start) changes
849 if (!destructive()) {
850 AudioFileSource::set_timeline_position (pos);
855 SndFileSource::get_soundfile_info (const string& path, SoundFileInfo& info, string& error_msg)
861 sf_info.format = 0; // libsndfile says to clear this before sf_open().
863 if ((sf = sf_open ((char*) path.c_str(), SFM_READ, &sf_info)) == 0) {
865 error_msg = sf_error_str (0, errbuf, sizeof (errbuf) - 1);
869 info.samplerate = sf_info.samplerate;
870 info.channels = sf_info.channels;
871 info.length = sf_info.frames;
873 string major = sndfile_major_format(sf_info.format);
874 string minor = sndfile_minor_format(sf_info.format);
876 if (major.length() + minor.length() < 16) { /* arbitrary */
877 info.format_name = string_compose("%1/%2", major, minor);
879 info.format_name = string_compose("%1\n%2", major, minor);
882 info.timecode = binfo.load_from_file (sf) ? binfo.get_time_reference() : 0;
890 SndFileSource::one_of_several_channels () const
892 return _info.channels > 1;
896 SndFileSource::clamped_at_unity () const
898 int const type = _info.format & SF_FORMAT_TYPEMASK;
899 int const sub = _info.format & SF_FORMAT_SUBMASK;
900 /* XXX: this may not be the full list of formats that are unclamped */
901 return (sub != SF_FORMAT_FLOAT && sub != SF_FORMAT_DOUBLE && type != SF_FORMAT_OGG);
905 SndFileSource::file_closed ()
907 /* stupid libsndfile updated the headers on close,
908 so touch the peakfile if it exists and has data
909 to make sure its time is as new as the audio
917 SndFileSource::set_path (const string& p)
919 FileSource::set_path (p);
922 _descriptor->set_path (_path);