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.
32 #include <pbd/lockmonitor.h>
33 #include <pbd/xml++.h>
34 #include <pbd/pthread_utils.h>
36 #include <ardour/source.h>
37 #include <ardour/filesource.h>
38 #include <ardour/sndfilesource.h>
45 using namespace ARDOUR;
48 sigc::signal<void,Source *> Source::SourceCreated;
49 pthread_t Source::peak_thread;
50 bool Source::have_peak_thread = false;
51 vector<Source*> Source::pending_peak_sources;
52 PBD::Lock Source::pending_peak_sources_lock;
53 int Source::peak_request_pipe[2];
55 bool Source::_build_missing_peakfiles = false;
56 bool Source::_build_peakfiles = false;
58 Source::Source (bool announce)
60 _id = ARDOUR::new_id();
63 next_peak_clear_should_notify = true;
67 _write_data_count = 0;
70 Source::Source (const XMLNode& node)
74 next_peak_clear_should_notify = true;
78 _write_data_count = 0;
80 if (set_state (node)) {
81 throw failed_constructor();
95 XMLNode *node = new XMLNode ("Source");
98 node->add_property ("name", _name);
99 snprintf (buf, sizeof(buf)-1, "%" PRIu64, _id);
100 node->add_property ("id", buf);
102 if (_timestamp != 0) {
103 snprintf (buf, sizeof (buf), "%ld", _timestamp);
104 node->add_property ("timestamp", buf);
107 if (_captured_for.length()) {
108 node->add_property ("captured-for", _captured_for);
115 Source::set_state (const XMLNode& node)
117 const XMLProperty* prop;
119 if ((prop = node.property ("name")) != 0) {
120 _name = prop->value();
125 if ((prop = node.property ("id")) != 0) {
126 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
131 if ((prop = node.property ("timestamp")) != 0) {
132 sscanf (prop->value().c_str(), "%ld", &_timestamp);
135 if ((prop = node.property ("captured-for")) != 0) {
136 _captured_for = prop->value();
142 /***********************************************************************
144 ***********************************************************************/
147 Source::peak_thread_work (void* arg)
149 PBD::ThreadCreated (pthread_self(), X_("Peak"));
150 struct pollfd pfd[1];
152 LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
156 pfd[0].fd = peak_request_pipe[0];
157 pfd[0].events = POLLIN|POLLERR|POLLHUP;
159 pthread_mutex_unlock (pending_peak_sources_lock.mutex());
161 if (poll (pfd, 1, -1) < 0) {
163 if (errno == EINTR) {
164 pthread_mutex_lock (pending_peak_sources_lock.mutex());
168 error << string_compose (_("poll on peak request pipe failed (%1)"),
174 if (pfd[0].revents & ~POLLIN) {
175 error << _("Error on peak thread request pipe") << endmsg;
179 if (pfd[0].revents & POLLIN) {
183 /* empty the pipe of all current requests */
186 size_t nread = ::read (peak_request_pipe[0], &req, sizeof (req));
189 switch ((PeakRequest::Type) req) {
191 case PeakRequest::Build:
194 case PeakRequest::Quit:
195 pthread_exit_pbd (0);
203 } else if (nread == 0) {
205 } else if (errno == EAGAIN) {
208 fatal << _("Error reading from peak request pipe") << endmsg;
214 pthread_mutex_lock (pending_peak_sources_lock.mutex());
216 while (!pending_peak_sources.empty()) {
218 Source* s = pending_peak_sources.front();
219 pending_peak_sources.erase (pending_peak_sources.begin());
221 pthread_mutex_unlock (pending_peak_sources_lock.mutex());
223 pthread_mutex_lock (pending_peak_sources_lock.mutex());
227 pthread_exit_pbd (0);
233 Source::start_peak_thread ()
235 if (!_build_peakfiles) {
239 if (pipe (peak_request_pipe)) {
240 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
244 if (fcntl (peak_request_pipe[0], F_SETFL, O_NONBLOCK)) {
245 error << string_compose(_("UI: cannot set O_NONBLOCK on peak request pipe (%1)"), strerror (errno)) << endmsg;
249 if (fcntl (peak_request_pipe[1], F_SETFL, O_NONBLOCK)) {
250 error << string_compose(_("UI: cannot set O_NONBLOCK on peak request pipe (%1)"), strerror (errno)) << endmsg;
254 if (pthread_create_and_store ("peak file builder", &peak_thread, 0, peak_thread_work, 0)) {
255 error << _("Source: could not create peak thread") << endmsg;
259 have_peak_thread = true;
264 Source::stop_peak_thread ()
266 if (!have_peak_thread) {
272 char c = (char) PeakRequest::Quit;
273 ::write (peak_request_pipe[1], &c, 1);
274 pthread_join (peak_thread, &status);
278 Source::queue_for_peaks (Source& source)
280 if (have_peak_thread) {
282 LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
284 source.next_peak_clear_should_notify = true;
286 if (find (pending_peak_sources.begin(),
287 pending_peak_sources.end(),
288 &source) == pending_peak_sources.end()) {
289 pending_peak_sources.push_back (&source);
292 char c = (char) PeakRequest::Build;
293 ::write (peak_request_pipe[1], &c, 1);
297 void Source::clear_queue_for_peaks ()
299 /* this is done to cancel a group of running peak builds */
300 if (have_peak_thread) {
301 LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
302 pending_peak_sources.clear ();
308 Source::peaks_ready (sigc::slot<void> the_slot) const
311 LockMonitor lm (_lock, __LINE__, __FILE__);
313 /* check to see if the peak data is ready. if not
314 connect the slot while still holding the lock.
317 if (!(ret = _peaks_built)) {
318 PeaksReady.connect (the_slot);
325 Source::initialize_peakfile (bool newfile, string audio_path)
329 peakpath = peak_path (audio_path);
333 if (!_build_peakfiles) {
337 _peaks_built = false;
341 if (stat (peakpath.c_str(), &statbuf)) {
342 if (errno != ENOENT) {
343 /* it exists in the peaks dir, but there is some kind of error */
345 error << string_compose(_("Source: cannot stat peakfile \"%1\""), peakpath) << endmsg;
349 /* older sessions stored peaks in the same directory
350 as the audio. so check there as well.
353 string oldpeakpath = old_peak_path (audio_path);
355 if (stat (oldpeakpath.c_str(), &statbuf)) {
357 if (errno == ENOENT) {
363 /* it exists in the audio dir , but there is some kind of error */
365 error << string_compose(_("Source: cannot stat peakfile \"%1\" or \"%2\""), peakpath, oldpeakpath) << endmsg;
371 /* we found it in the sound dir, where they lived once upon a time, in a land ... etc. */
373 peakpath = oldpeakpath;
378 /* we found it in the peaks dir */
381 if (statbuf.st_size == 0) {
382 _peaks_built = false;
384 // Check if the audio file has changed since the peakfile was built.
385 struct stat stat_file;
386 int err = stat (audio_path.c_str(), &stat_file);
388 if (!err && stat_file.st_mtime > statbuf.st_mtime){
389 _peaks_built = false;
396 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
397 error << string_compose(_("Source: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
401 if (!newfile && !_peaks_built && _build_missing_peakfiles && _build_peakfiles) {
402 build_peaks_from_scratch ();
409 Source::read_peaks (PeakData *peaks, jack_nframes_t npeaks, jack_nframes_t start, jack_nframes_t cnt, double samples_per_visual_peak) const
411 LockMonitor lm (_lock, __LINE__, __FILE__);
413 double expected_peaks;
414 PeakData::PeakDatum xmax;
415 PeakData::PeakDatum xmin;
418 jack_nframes_t zero_fill = 0;
420 PeakData* staging = 0;
421 Sample* raw_staging = 0;
423 expected_peaks = (cnt / (double) frames_per_peak);
424 scale = npeaks/expected_peaks;
427 cerr << "======>RP: npeaks = " << npeaks
428 << " start = " << start
430 << " len = " << _length
431 << " samples_per_visual_peak =" << samples_per_visual_peak
432 << " expected was " << expected_peaks << " ... scale = " << scale
433 << " PD ptr = " << peaks
438 /* fix for near-end-of-file conditions */
440 if (cnt > _length - start) {
441 // cerr << "too close to end @ " << _length << " given " << start << " + " << cnt << endl;
442 cnt = _length - start;
443 jack_nframes_t old = npeaks;
444 npeaks = min ((jack_nframes_t) floor (cnt / samples_per_visual_peak), npeaks);
445 zero_fill = old - npeaks;
448 // cerr << "actual npeaks = " << npeaks << " zf = " << zero_fill << endl;
452 // cerr << "RAW DATA\n";
454 /* no scaling at all, just get the sample data and duplicate it for
455 both max and min peak values.
458 Sample* raw_staging = new Sample[cnt];
460 if (read_unlocked (raw_staging, start, cnt) != cnt) {
461 error << _("cannot read sample data for unscaled peak computation") << endmsg;
465 for (jack_nframes_t i = 0; i < npeaks; ++i) {
466 peaks[i].max = raw_staging[i];
467 peaks[i].min = raw_staging[i];
470 delete [] raw_staging;
477 // cerr << "DIRECT PEAKS\n";
479 off_t first_peak_byte = (start / frames_per_peak) * sizeof (PeakData);
481 if ((nread = ::pread (peakfile, peaks, sizeof (PeakData)* npeaks, first_peak_byte)) != sizeof (PeakData) * npeaks) {
484 << "]: cannot read peaks from peakfile! (read only "
498 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
509 // cerr << "DOWNSAMPLE\n";
513 - more frames-per-peak (lower resolution) than the peakfile, or to put it another way,
514 - less peaks than the peakfile holds for the same range
516 So, read a block into a staging area, and then downsample from there.
518 to avoid confusion, I'll refer to the requested peaks as visual_peaks and the peakfile peaks as stored_peaks
521 const uint32_t chunksize = (uint32_t) min (expected_peaks, 4096.0);
523 staging = new PeakData[chunksize];
525 /* compute the rounded up frame position */
527 jack_nframes_t current_frame = start;
528 jack_nframes_t current_stored_peak = (jack_nframes_t) ceil (current_frame / (double) frames_per_peak);
529 uint32_t next_visual_peak = (uint32_t) ceil (current_frame / samples_per_visual_peak);
530 double next_visual_peak_frame = next_visual_peak * samples_per_visual_peak;
531 uint32_t stored_peak_before_next_visual_peak = (jack_nframes_t) next_visual_peak_frame / frames_per_peak;
532 uint32_t nvisual_peaks = 0;
533 uint32_t stored_peaks_read = 0;
536 /* handle the case where the initial visual peak is on a pixel boundary */
538 current_stored_peak = min (current_stored_peak, stored_peak_before_next_visual_peak);
540 while (nvisual_peaks < npeaks) {
542 if (i == stored_peaks_read) {
544 uint32_t start_byte = current_stored_peak * sizeof(PeakData);
545 tnp = min ((_length/frames_per_peak - current_stored_peak), (jack_nframes_t) expected_peaks);
546 to_read = min (chunksize, tnp);
548 if ((nread = ::pread (peakfile, staging, sizeof (PeakData) * to_read, start_byte))
549 != sizeof (PeakData) * to_read) {
552 << "]: cannot read peak data from peakfile ("
554 << " peaks instead of "
559 << " at start_byte = " << start_byte
560 << " _length = " << _length
561 << " expected maxpeaks = " << (_length - current_frame)/frames_per_peak
562 << " npeaks was " << npeaks
568 stored_peaks_read = nread / sizeof(PeakData);
574 while ((i < stored_peaks_read) && (current_stored_peak <= stored_peak_before_next_visual_peak)) {
576 xmax = max (xmax, staging[i].max);
577 xmin = min (xmin, staging[i].min);
579 ++current_stored_peak;
583 peaks[nvisual_peaks].max = xmax;
584 peaks[nvisual_peaks].min = xmin;
588 //next_visual_peak_frame = min ((next_visual_peak * samples_per_visual_peak), (next_visual_peak_frame+samples_per_visual_peak) );
589 next_visual_peak_frame = min ((double) start+cnt, (next_visual_peak_frame+samples_per_visual_peak) );
590 stored_peak_before_next_visual_peak = (uint32_t) next_visual_peak_frame / frames_per_peak;
594 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
601 // cerr << "UPSAMPLE\n";
605 - less frames-per-peak (more resolution)
606 - more peaks than stored in the Peakfile
608 So, fetch data from the raw source, and generate peak
612 jack_nframes_t frames_read = 0;
613 jack_nframes_t current_frame = start;
614 jack_nframes_t i = 0;
615 jack_nframes_t nvisual_peaks = 0;
616 jack_nframes_t chunksize = (jack_nframes_t) min (cnt, (jack_nframes_t) 4096);
617 raw_staging = new Sample[chunksize];
619 jack_nframes_t frame_pos = start;
620 double pixel_pos = floor (frame_pos / samples_per_visual_peak);
621 double next_pixel_pos = ceil (frame_pos / samples_per_visual_peak);
622 double pixels_per_frame = 1.0 / samples_per_visual_peak;
627 while (nvisual_peaks < npeaks) {
629 if (i == frames_read) {
631 to_read = min (chunksize, (_length - current_frame));
633 if ((frames_read = read_unlocked (raw_staging, current_frame, to_read)) < 0) {
634 error << string_compose(_("Source[%1]: peak read - cannot read %2 samples at offset %3")
635 , _name, to_read, current_frame)
643 xmax = max (xmax, raw_staging[i]);
644 xmin = min (xmin, raw_staging[i]);
647 pixel_pos += pixels_per_frame;
649 if (pixel_pos >= next_pixel_pos) {
651 peaks[nvisual_peaks].max = xmax;
652 peaks[nvisual_peaks].min = xmin;
657 next_pixel_pos = ceil (pixel_pos + 0.5);
662 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
674 delete [] raw_staging;
680 #undef DEBUG_PEAK_BUILD
683 Source::build_peaks ()
685 vector<PeakBuildRecord*> built;
687 bool pr_signal = false;
688 list<PeakBuildRecord*> copy;
691 LockMonitor lm (_lock, __LINE__, __FILE__);
692 copy = pending_peak_builds;
693 pending_peak_builds.clear ();
697 #ifdef DEBUG_PEAK_BUILD
698 cerr << "build peaks with " << pending_peak_builds.size() << " requests pending\n";
701 for (list<PeakBuildRecord *>::iterator i = copy.begin(); i != copy.end(); ++i) {
703 if ((status = do_build_peak ((*i)->frame, (*i)->cnt)) != 0) {
704 unlink (peakpath.c_str());
707 built.push_back (new PeakBuildRecord (*(*i)));
712 LockMonitor lm (_lock, __LINE__, __FILE__);
717 if (next_peak_clear_should_notify) {
718 next_peak_clear_should_notify = false;
725 for (vector<PeakBuildRecord *>::iterator i = built.begin(); i != built.end(); ++i) {
726 PeakRangeReady ((*i)->frame, (*i)->cnt); /* EMIT SIGNAL */
731 PeaksReady (); /* EMIT SIGNAL */
739 Source::do_build_peak (jack_nframes_t first_frame, jack_nframes_t cnt)
741 jack_nframes_t current_frame;
742 Sample buf[frames_per_peak];
746 jack_nframes_t frames_read;
747 jack_nframes_t frames_to_read;
748 off_t first_peak_byte;
751 #ifdef DEBUG_PEAK_BUILD
752 cerr << pthread_self() << ": " << _name << ": building peaks for " << first_frame << " to " << first_frame + cnt - 1 << endl;
755 first_peak_byte = (first_frame / frames_per_peak) * sizeof (PeakData);
757 #ifdef DEBUG_PEAK_BUILD
758 cerr << "seeking to " << first_peak_byte << " before writing new peak data\n";
761 current_frame = first_frame;
762 peakbuf = new PeakData[(cnt/frames_per_peak)+1];
767 frames_to_read = min (frames_per_peak, cnt);
769 if ((frames_read = read_unlocked (buf, current_frame, frames_to_read)) != frames_to_read) {
770 error << string_compose(_("%1: could not write read raw data for peak computation (%2)"), _name, strerror (errno)) << endmsg;
777 for (jack_nframes_t n = 1; n < frames_read; ++n) {
778 xmax = max (xmax, buf[n]);
779 xmin = min (xmin, buf[n]);
781 // if (current_frame < frames_read) {
782 // cerr << "sample = " << buf[n] << " max = " << xmax << " min = " << xmin << " max of 2 = " << max (xmax, buf[n]) << endl;
786 peakbuf[peaki].max = xmax;
787 peakbuf[peaki].min = xmin;
790 current_frame += frames_read;
794 if (::pwrite (peakfile, peakbuf, sizeof (PeakData) * peaki, first_peak_byte) != (ssize_t) (sizeof (PeakData) * peaki)) {
795 error << string_compose(_("%1: could not write peak file data (%2)"), _name, strerror (errno)) << endmsg;
807 Source::build_peaks_from_scratch ()
809 LockMonitor lp (_lock, __LINE__, __FILE__);
811 next_peak_clear_should_notify = true;
812 pending_peak_builds.push_back (new PeakBuildRecord (0, _length));
813 queue_for_peaks (*this);
817 Source::file_changed (string path)
819 struct stat stat_file;
820 struct stat stat_peak;
822 int e1 = stat (path.c_str(), &stat_file);
823 int e2 = stat (peak_path(path).c_str(), &stat_peak);
825 if (!e1 && !e2 && stat_file.st_mtime > stat_peak.st_mtime){
841 if (_use_cnt) --_use_cnt;