2 Copyright (C) 2000 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.
18 $Id: source.cc 404 2006-03-17 17:39:21Z pauld $
32 #include <pbd/xml++.h>
33 #include <pbd/pthread_utils.h>
35 #include <ardour/audiosource.h>
40 using namespace ARDOUR;
43 pthread_t AudioSource::peak_thread;
44 bool AudioSource::have_peak_thread = false;
45 vector<AudioSource*> AudioSource::pending_peak_sources;
46 Glib::Mutex* AudioSource::pending_peak_sources_lock = 0;
47 int AudioSource::peak_request_pipe[2];
49 bool AudioSource::_build_missing_peakfiles = false;
50 bool AudioSource::_build_peakfiles = false;
52 AudioSource::AudioSource (string name)
53 : Source (name, DataType::AUDIO)
55 if (pending_peak_sources_lock == 0) {
56 pending_peak_sources_lock = new Glib::Mutex;
60 next_peak_clear_should_notify = true;
62 _write_data_count = 0;
65 AudioSource::AudioSource (const XMLNode& node)
68 if (pending_peak_sources_lock == 0) {
69 pending_peak_sources_lock = new Glib::Mutex;
73 next_peak_clear_should_notify = true;
75 _write_data_count = 0;
77 if (set_state (node)) {
78 throw failed_constructor();
82 AudioSource::~AudioSource ()
87 AudioSource::get_state ()
89 XMLNode& node (Source::get_state());
91 if (_captured_for.length()) {
92 node.add_property ("captured-for", _captured_for);
99 AudioSource::set_state (const XMLNode& node)
101 const XMLProperty* prop;
103 Source::set_state (node);
105 if ((prop = node.property ("captured-for")) != 0) {
106 _captured_for = prop->value();
112 /***********************************************************************
114 ***********************************************************************/
117 AudioSource::peak_thread_work (void* arg)
119 PBD::ThreadCreated (pthread_self(), X_("Peak"));
120 struct pollfd pfd[1];
122 if (pending_peak_sources_lock == 0) {
123 pending_peak_sources_lock = new Glib::Mutex;
126 Glib::Mutex::Lock lm (*pending_peak_sources_lock);
130 pfd[0].fd = peak_request_pipe[0];
131 pfd[0].events = POLLIN|POLLERR|POLLHUP;
133 pending_peak_sources_lock->unlock ();
135 if (poll (pfd, 1, -1) < 0) {
137 if (errno == EINTR) {
138 pending_peak_sources_lock->lock ();
142 error << string_compose (_("poll on peak request pipe failed (%1)"),
148 if (pfd[0].revents & ~POLLIN) {
149 error << _("Error on peak thread request pipe") << endmsg;
153 if (pfd[0].revents & POLLIN) {
157 /* empty the pipe of all current requests */
160 size_t nread = ::read (peak_request_pipe[0], &req, sizeof (req));
163 switch ((PeakRequest::Type) req) {
165 case PeakRequest::Build:
168 case PeakRequest::Quit:
169 pthread_exit_pbd (0);
177 } else if (nread == 0) {
179 } else if (errno == EAGAIN) {
182 fatal << _("Error reading from peak request pipe") << endmsg;
188 pending_peak_sources_lock->lock ();
190 while (!pending_peak_sources.empty()) {
192 AudioSource* s = pending_peak_sources.front();
193 pending_peak_sources.erase (pending_peak_sources.begin());
195 pending_peak_sources_lock->unlock ();
197 pending_peak_sources_lock->lock ();
201 pthread_exit_pbd (0);
207 AudioSource::start_peak_thread ()
209 if (!_build_peakfiles) {
213 if (pipe (peak_request_pipe)) {
214 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
218 if (fcntl (peak_request_pipe[0], F_SETFL, O_NONBLOCK)) {
219 error << string_compose(_("UI: cannot set O_NONBLOCK on peak request pipe (%1)"), strerror (errno)) << endmsg;
223 if (fcntl (peak_request_pipe[1], F_SETFL, O_NONBLOCK)) {
224 error << string_compose(_("UI: cannot set O_NONBLOCK on peak request pipe (%1)"), strerror (errno)) << endmsg;
228 if (pthread_create_and_store ("peak file builder", &peak_thread, 0, peak_thread_work, 0)) {
229 error << _("AudioSource: could not create peak thread") << endmsg;
233 have_peak_thread = true;
238 AudioSource::stop_peak_thread ()
240 if (!have_peak_thread) {
246 char c = (char) PeakRequest::Quit;
247 ::write (peak_request_pipe[1], &c, 1);
248 pthread_join (peak_thread, &status);
252 AudioSource::queue_for_peaks (AudioSource& source)
254 if (have_peak_thread) {
256 Glib::Mutex::Lock lm (*pending_peak_sources_lock);
258 source.next_peak_clear_should_notify = true;
260 if (find (pending_peak_sources.begin(),
261 pending_peak_sources.end(),
262 &source) == pending_peak_sources.end()) {
263 pending_peak_sources.push_back (&source);
266 char c = (char) PeakRequest::Build;
267 ::write (peak_request_pipe[1], &c, 1);
271 void AudioSource::clear_queue_for_peaks ()
273 /* this is done to cancel a group of running peak builds */
274 if (have_peak_thread) {
275 Glib::Mutex::Lock lm (*pending_peak_sources_lock);
276 pending_peak_sources.clear ();
282 AudioSource::peaks_ready (sigc::slot<void> the_slot, sigc::connection& conn) const
285 Glib::Mutex::Lock lm (_lock);
287 /* check to see if the peak data is ready. if not
288 connect the slot while still holding the lock.
291 if (!(ret = _peaks_built)) {
292 conn = PeaksReady.connect (the_slot);
299 AudioSource::rename_peakfile (string newpath)
301 /* caller must hold _lock */
303 string oldpath = peakpath;
305 if (access (oldpath.c_str(), F_OK) == 0) {
306 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
307 error << string_compose (_("cannot rename peakfile for %1 from %2 to %3 (%4)"), _name, oldpath, newpath, strerror (errno)) << endmsg;
318 AudioSource::initialize_peakfile (bool newfile, string audio_path)
322 peakpath = peak_path (audio_path);
324 /* Nasty band-aid for older sessions that were created before we
325 used libsndfile for all audio files.
328 if (!newfile && access (peakpath.c_str(), R_OK) != 0) {
329 string str = old_peak_path (audio_path);
330 if (access (str.c_str(), R_OK) == 0) {
337 if (!_build_peakfiles) {
341 _peaks_built = false;
345 if (stat (peakpath.c_str(), &statbuf)) {
346 if (errno != ENOENT) {
347 /* it exists in the peaks dir, but there is some kind of error */
349 error << string_compose(_("AudioSource: cannot stat peakfile \"%1\""), peakpath) << endmsg;
355 /* we found it in the peaks dir */
358 if (statbuf.st_size == 0) {
359 _peaks_built = false;
361 // Check if the audio file has changed since the peakfile was built.
362 struct stat stat_file;
363 int err = stat (audio_path.c_str(), &stat_file);
365 if (!err && stat_file.st_mtime > statbuf.st_mtime){
366 _peaks_built = false;
373 if (!newfile && !_peaks_built && _build_missing_peakfiles && _build_peakfiles) {
374 build_peaks_from_scratch ();
381 AudioSource::read (Sample *dst, jack_nframes_t start, jack_nframes_t cnt) const
383 Glib::Mutex::Lock lm (_lock);
384 return read_unlocked (dst, start, cnt);
388 AudioSource::write (Sample *dst, jack_nframes_t cnt)
390 Glib::Mutex::Lock lm (_lock);
391 return write_unlocked (dst, cnt);
395 AudioSource::read_peaks (PeakData *peaks, jack_nframes_t npeaks, jack_nframes_t start, jack_nframes_t cnt, double samples_per_visual_peak) const
397 Glib::Mutex::Lock lm (_lock);
399 double expected_peaks;
400 PeakData::PeakDatum xmax;
401 PeakData::PeakDatum xmin;
404 jack_nframes_t zero_fill = 0;
406 PeakData* staging = 0;
407 Sample* raw_staging = 0;
410 expected_peaks = (cnt / (double) frames_per_peak);
411 scale = npeaks/expected_peaks;
414 cerr << "======>RP: npeaks = " << npeaks
415 << " start = " << start
417 << " len = " << _length
418 << " samples_per_visual_peak =" << samples_per_visual_peak
419 << " expected was " << expected_peaks << " ... scale = " << scale
420 << " PD ptr = " << peaks
425 /* fix for near-end-of-file conditions */
427 if (cnt > _length - start) {
428 // cerr << "too close to end @ " << _length << " given " << start << " + " << cnt << endl;
429 cnt = _length - start;
430 jack_nframes_t old = npeaks;
431 npeaks = min ((jack_nframes_t) floor (cnt / samples_per_visual_peak), npeaks);
432 zero_fill = old - npeaks;
435 // cerr << "actual npeaks = " << npeaks << " zf = " << zero_fill << endl;
439 // cerr << "RAW DATA\n";
441 /* no scaling at all, just get the sample data and duplicate it for
442 both max and min peak values.
445 Sample* raw_staging = new Sample[cnt];
447 if (read_unlocked (raw_staging, start, cnt) != cnt) {
448 error << _("cannot read sample data for unscaled peak computation") << endmsg;
452 for (jack_nframes_t i = 0; i < npeaks; ++i) {
453 peaks[i].max = raw_staging[i];
454 peaks[i].min = raw_staging[i];
457 delete [] raw_staging;
463 off_t first_peak_byte = (start / frames_per_peak) * sizeof (PeakData);
465 /* open, read, close */
467 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
468 error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
472 // cerr << "DIRECT PEAKS\n";
474 nread = ::pread (peakfile, peaks, sizeof (PeakData)* npeaks, first_peak_byte);
477 if (nread != sizeof (PeakData) * npeaks) {
478 cerr << "AudioSource["
480 << "]: cannot read peaks from peakfile! (read only "
494 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
505 // cerr << "DOWNSAMPLE\n";
509 - more frames-per-peak (lower resolution) than the peakfile, or to put it another way,
510 - less peaks than the peakfile holds for the same range
512 So, read a block into a staging area, and then downsample from there.
514 to avoid confusion, I'll refer to the requested peaks as visual_peaks and the peakfile peaks as stored_peaks
517 const uint32_t chunksize = (uint32_t) min (expected_peaks, 4096.0);
519 staging = new PeakData[chunksize];
521 /* compute the rounded up frame position */
523 jack_nframes_t current_frame = start;
524 jack_nframes_t current_stored_peak = (jack_nframes_t) ceil (current_frame / (double) frames_per_peak);
525 uint32_t next_visual_peak = (uint32_t) ceil (current_frame / samples_per_visual_peak);
526 double next_visual_peak_frame = next_visual_peak * samples_per_visual_peak;
527 uint32_t stored_peak_before_next_visual_peak = (jack_nframes_t) next_visual_peak_frame / frames_per_peak;
528 uint32_t nvisual_peaks = 0;
529 uint32_t stored_peaks_read = 0;
532 /* handle the case where the initial visual peak is on a pixel boundary */
534 current_stored_peak = min (current_stored_peak, stored_peak_before_next_visual_peak);
536 /* open ... close during out: handling */
538 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
539 error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
543 while (nvisual_peaks < npeaks) {
545 if (i == stored_peaks_read) {
547 uint32_t start_byte = current_stored_peak * sizeof(PeakData);
548 tnp = min ((_length/frames_per_peak - current_stored_peak), (jack_nframes_t) expected_peaks);
549 to_read = min (chunksize, tnp);
551 off_t fend = lseek (peakfile, 0, SEEK_END);
553 if ((nread = ::pread (peakfile, staging, sizeof (PeakData) * to_read, start_byte))
554 != sizeof (PeakData) * to_read) {
555 cerr << "AudioSource["
557 << "]: cannot read peak data from peakfile ("
558 << (nread / sizeof(PeakData))
559 << " peaks instead of "
564 << " at start_byte = " << start_byte
565 << " _length = " << _length << " versus len = " << fend
566 << " expected maxpeaks = " << (_length - current_frame)/frames_per_peak
567 << " npeaks was " << npeaks
573 stored_peaks_read = nread / sizeof(PeakData);
579 while ((i < stored_peaks_read) && (current_stored_peak <= stored_peak_before_next_visual_peak)) {
581 xmax = max (xmax, staging[i].max);
582 xmin = min (xmin, staging[i].min);
584 ++current_stored_peak;
588 peaks[nvisual_peaks].max = xmax;
589 peaks[nvisual_peaks].min = xmin;
593 //next_visual_peak_frame = min ((next_visual_peak * samples_per_visual_peak), (next_visual_peak_frame+samples_per_visual_peak) );
594 next_visual_peak_frame = min ((double) start+cnt, (next_visual_peak_frame+samples_per_visual_peak) );
595 stored_peak_before_next_visual_peak = (uint32_t) next_visual_peak_frame / frames_per_peak;
599 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
606 // cerr << "UPSAMPLE\n";
610 - less frames-per-peak (more resolution)
611 - more peaks than stored in the Peakfile
613 So, fetch data from the raw source, and generate peak
617 jack_nframes_t frames_read = 0;
618 jack_nframes_t current_frame = start;
619 jack_nframes_t i = 0;
620 jack_nframes_t nvisual_peaks = 0;
621 jack_nframes_t chunksize = (jack_nframes_t) min (cnt, (jack_nframes_t) 4096);
622 raw_staging = new Sample[chunksize];
624 jack_nframes_t frame_pos = start;
625 double pixel_pos = floor (frame_pos / samples_per_visual_peak);
626 double next_pixel_pos = ceil (frame_pos / samples_per_visual_peak);
627 double pixels_per_frame = 1.0 / samples_per_visual_peak;
632 while (nvisual_peaks < npeaks) {
634 if (i == frames_read) {
636 to_read = min (chunksize, (_length - current_frame));
638 if ((frames_read = read_unlocked (raw_staging, current_frame, to_read)) == 0) {
639 error << string_compose(_("AudioSource[%1]: peak read - cannot read %2 samples at offset %3")
640 , _name, to_read, current_frame)
648 xmax = max (xmax, raw_staging[i]);
649 xmin = min (xmin, raw_staging[i]);
652 pixel_pos += pixels_per_frame;
654 if (pixel_pos >= next_pixel_pos) {
656 peaks[nvisual_peaks].max = xmax;
657 peaks[nvisual_peaks].min = xmin;
662 next_pixel_pos = ceil (pixel_pos + 0.5);
667 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
683 delete [] raw_staging;
689 #undef DEBUG_PEAK_BUILD
692 AudioSource::build_peaks ()
694 vector<PeakBuildRecord*> built;
696 bool pr_signal = false;
697 list<PeakBuildRecord*> copy;
700 Glib::Mutex::Lock lm (_lock);
701 copy = pending_peak_builds;
702 pending_peak_builds.clear ();
705 #ifdef DEBUG_PEAK_BUILD
706 cerr << "build peaks with " << copy.size() << " requests pending\n";
709 for (list<PeakBuildRecord *>::iterator i = copy.begin(); i != copy.end(); ++i) {
711 if ((status = do_build_peak ((*i)->frame, (*i)->cnt)) != 0) {
712 unlink (peakpath.c_str());
715 built.push_back (new PeakBuildRecord (*(*i)));
720 Glib::Mutex::Lock lm (_lock);
725 if (next_peak_clear_should_notify) {
726 next_peak_clear_should_notify = false;
733 for (vector<PeakBuildRecord *>::iterator i = built.begin(); i != built.end(); ++i) {
734 PeakRangeReady ((*i)->frame, (*i)->cnt); /* EMIT SIGNAL */
739 PeaksReady (); /* EMIT SIGNAL */
747 AudioSource::do_build_peak (jack_nframes_t first_frame, jack_nframes_t cnt)
749 jack_nframes_t current_frame;
750 Sample buf[frames_per_peak];
754 jack_nframes_t frames_read;
755 jack_nframes_t frames_to_read;
756 off_t first_peak_byte;
760 #ifdef DEBUG_PEAK_BUILD
761 cerr << pthread_self() << ": " << _name << ": building peaks for " << first_frame << " to " << first_frame + cnt - 1 << endl;
764 first_peak_byte = (first_frame / frames_per_peak) * sizeof (PeakData);
766 #ifdef DEBUG_PEAK_BUILD
767 cerr << "seeking to " << first_peak_byte << " before writing new peak data\n";
770 current_frame = first_frame;
771 peakbuf = new PeakData[(cnt/frames_per_peak)+1];
774 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
775 error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
781 frames_to_read = min (frames_per_peak, cnt);
783 /* lock for every read */
785 if ((frames_read = read (buf, current_frame, frames_to_read)) != frames_to_read) {
786 error << string_compose(_("%1: could not write read raw data for peak computation (%2)"), _name, strerror (errno)) << endmsg;
793 for (jack_nframes_t n = 1; n < frames_read; ++n) {
794 xmax = max (xmax, buf[n]);
795 xmin = min (xmin, buf[n]);
797 // if (current_frame < frames_read) {
798 // cerr << "sample = " << buf[n] << " max = " << xmax << " min = " << xmin << " max of 2 = " << max (xmax, buf[n]) << endl;
802 peakbuf[peaki].max = xmax;
803 peakbuf[peaki].min = xmin;
806 current_frame += frames_read;
810 if (::pwrite (peakfile, peakbuf, sizeof (PeakData) * peaki, first_peak_byte) != (ssize_t) (sizeof (PeakData) * peaki)) {
811 error << string_compose(_("%1: could not write peak file data (%2)"), _name, strerror (errno)) << endmsg;
826 AudioSource::build_peaks_from_scratch ()
828 Glib::Mutex::Lock lp (_lock);
830 next_peak_clear_should_notify = true;
831 pending_peak_builds.push_back (new PeakBuildRecord (0, _length));
832 queue_for_peaks (*this);
836 AudioSource::file_changed (string path)
838 struct stat stat_file;
839 struct stat stat_peak;
841 int e1 = stat (path.c_str(), &stat_file);
842 int e2 = stat (peak_path(path).c_str(), &stat_peak);
844 if (!e1 && !e2 && stat_file.st_mtime > stat_peak.st_mtime){
852 AudioSource::available_peaks (double zoom_factor) const
857 if (zoom_factor < frames_per_peak) {
858 return length(); // peak data will come from the audio file
861 /* peak data comes from peakfile */
863 if ((peakfile = ::open (peakpath.c_str(), O_RDONLY)) < 0) {
864 error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
869 Glib::Mutex::Lock lm (_lock);
870 end = lseek (peakfile, 0, SEEK_END);
875 return (end/sizeof(PeakData)) * frames_per_peak;