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>
43 using namespace ARDOUR;
46 sigc::signal<void,Source *> Source::SourceCreated;
47 pthread_t Source::peak_thread;
48 bool Source::have_peak_thread = false;
49 vector<Source*> Source::pending_peak_sources;
50 PBD::Lock Source::pending_peak_sources_lock;
51 int Source::peak_request_pipe[2];
53 bool Source::_build_missing_peakfiles = false;
54 bool Source::_build_peakfiles = false;
56 Source::Source (bool announce)
58 _id = ARDOUR::new_id();
61 next_peak_clear_should_notify = true;
64 _write_data_count = 0;
67 Source::Source (const XMLNode& node)
71 next_peak_clear_should_notify = true;
74 _write_data_count = 0;
76 if (set_state (node)) {
77 throw failed_constructor();
88 XMLNode *node = new XMLNode ("Source");
91 node->add_property ("name", _name);
92 snprintf (buf, sizeof(buf)-1, "%" PRIu64, _id);
93 node->add_property ("id", buf);
95 if (_timestamp != 0) {
96 snprintf (buf, sizeof (buf), "%ld", _timestamp);
97 node->add_property ("timestamp", buf);
100 if (_captured_for.length()) {
101 node->add_property ("captured-for", _captured_for);
108 Source::set_state (const XMLNode& node)
110 const XMLProperty* prop;
112 if ((prop = node.property ("name")) != 0) {
113 _name = prop->value();
118 if ((prop = node.property ("id")) != 0) {
119 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
124 if ((prop = node.property ("timestamp")) != 0) {
125 sscanf (prop->value().c_str(), "%ld", &_timestamp);
128 if ((prop = node.property ("captured-for")) != 0) {
129 _captured_for = prop->value();
135 /***********************************************************************
137 ***********************************************************************/
140 Source::peak_thread_work (void* arg)
142 PBD::ThreadCreated (pthread_self(), X_("Peak"));
143 struct pollfd pfd[1];
145 LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
149 pfd[0].fd = peak_request_pipe[0];
150 pfd[0].events = POLLIN|POLLERR|POLLHUP;
152 pthread_mutex_unlock (pending_peak_sources_lock.mutex());
154 if (poll (pfd, 1, -1) < 0) {
156 if (errno == EINTR) {
157 pthread_mutex_lock (pending_peak_sources_lock.mutex());
161 error << string_compose (_("poll on peak request pipe failed (%1)"),
167 if (pfd[0].revents & ~POLLIN) {
168 error << _("Error on peak thread request pipe") << endmsg;
172 if (pfd[0].revents & POLLIN) {
176 /* empty the pipe of all current requests */
179 size_t nread = ::read (peak_request_pipe[0], &req, sizeof (req));
182 switch ((PeakRequest::Type) req) {
184 case PeakRequest::Build:
187 case PeakRequest::Quit:
188 pthread_exit_pbd (0);
196 } else if (nread == 0) {
198 } else if (errno == EAGAIN) {
201 fatal << _("Error reading from peak request pipe") << endmsg;
207 pthread_mutex_lock (pending_peak_sources_lock.mutex());
209 while (!pending_peak_sources.empty()) {
211 Source* s = pending_peak_sources.front();
212 pending_peak_sources.erase (pending_peak_sources.begin());
214 pthread_mutex_unlock (pending_peak_sources_lock.mutex());
216 pthread_mutex_lock (pending_peak_sources_lock.mutex());
220 pthread_exit_pbd (0);
226 Source::start_peak_thread ()
228 if (!_build_peakfiles) {
232 if (pipe (peak_request_pipe)) {
233 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
237 if (fcntl (peak_request_pipe[0], F_SETFL, O_NONBLOCK)) {
238 error << string_compose(_("UI: cannot set O_NONBLOCK on peak request pipe (%1)"), strerror (errno)) << endmsg;
242 if (fcntl (peak_request_pipe[1], F_SETFL, O_NONBLOCK)) {
243 error << string_compose(_("UI: cannot set O_NONBLOCK on peak request pipe (%1)"), strerror (errno)) << endmsg;
247 if (pthread_create_and_store ("peak file builder", &peak_thread, 0, peak_thread_work, 0)) {
248 error << _("Source: could not create peak thread") << endmsg;
252 have_peak_thread = true;
257 Source::stop_peak_thread ()
259 if (!have_peak_thread) {
265 char c = (char) PeakRequest::Quit;
266 ::write (peak_request_pipe[1], &c, 1);
267 pthread_join (peak_thread, &status);
271 Source::queue_for_peaks (Source& source)
273 if (have_peak_thread) {
275 LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
277 source.next_peak_clear_should_notify = true;
279 if (find (pending_peak_sources.begin(),
280 pending_peak_sources.end(),
281 &source) == pending_peak_sources.end()) {
282 pending_peak_sources.push_back (&source);
285 char c = (char) PeakRequest::Build;
286 ::write (peak_request_pipe[1], &c, 1);
290 void Source::clear_queue_for_peaks ()
292 /* this is done to cancel a group of running peak builds */
293 if (have_peak_thread) {
294 LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
295 pending_peak_sources.clear ();
301 Source::peaks_ready (sigc::slot<void> the_slot, sigc::connection& conn) const
304 LockMonitor lm (_lock, __LINE__, __FILE__);
306 /* check to see if the peak data is ready. if not
307 connect the slot while still holding the lock.
310 if (!(ret = _peaks_built)) {
311 conn = PeaksReady.connect (the_slot);
318 Source::rename_peakfile (string newpath)
320 /* caller must hold _lock */
322 string oldpath = peakpath;
324 if (access (oldpath.c_str(), F_OK) == 0) {
325 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
326 error << string_compose (_("cannot rename peakfile for %1 from %2 to %3 (%4)"), _name, oldpath, newpath, strerror (errno)) << endmsg;
337 Source::initialize_peakfile (bool newfile, string audio_path)
341 peakpath = peak_path (audio_path);
345 if (!_build_peakfiles) {
349 _peaks_built = false;
353 if (stat (peakpath.c_str(), &statbuf)) {
354 if (errno != ENOENT) {
355 /* it exists in the peaks dir, but there is some kind of error */
357 error << string_compose(_("Source: cannot stat peakfile \"%1\""), peakpath) << endmsg;
363 /* we found it in the peaks dir */
366 if (statbuf.st_size == 0) {
367 _peaks_built = false;
369 // Check if the audio file has changed since the peakfile was built.
370 struct stat stat_file;
371 int err = stat (audio_path.c_str(), &stat_file);
373 if (!err && stat_file.st_mtime > statbuf.st_mtime){
374 _peaks_built = false;
381 if (!newfile && !_peaks_built && _build_missing_peakfiles && _build_peakfiles) {
382 build_peaks_from_scratch ();
389 Source::read_peaks (PeakData *peaks, jack_nframes_t npeaks, jack_nframes_t start, jack_nframes_t cnt, double samples_per_visual_peak) const
391 LockMonitor lm (_lock, __LINE__, __FILE__);
393 double expected_peaks;
394 PeakData::PeakDatum xmax;
395 PeakData::PeakDatum xmin;
398 jack_nframes_t zero_fill = 0;
400 PeakData* staging = 0;
401 Sample* raw_staging = 0;
405 expected_peaks = (cnt / (double) frames_per_peak);
406 scale = npeaks/expected_peaks;
409 cerr << "======>RP: npeaks = " << npeaks
410 << " start = " << start
412 << " len = " << _length
413 << " samples_per_visual_peak =" << samples_per_visual_peak
414 << " expected was " << expected_peaks << " ... scale = " << scale
415 << " PD ptr = " << peaks
420 /* fix for near-end-of-file conditions */
422 if (cnt > _length - start) {
423 // cerr << "too close to end @ " << _length << " given " << start << " + " << cnt << endl;
424 cnt = _length - start;
425 jack_nframes_t old = npeaks;
426 npeaks = min ((jack_nframes_t) floor (cnt / samples_per_visual_peak), npeaks);
427 zero_fill = old - npeaks;
430 // cerr << "actual npeaks = " << npeaks << " zf = " << zero_fill << endl;
434 // cerr << "RAW DATA\n";
436 /* no scaling at all, just get the sample data and duplicate it for
437 both max and min peak values.
440 Sample* raw_staging = new Sample[cnt];
441 workbuf = new char[cnt*4];
443 if (read_unlocked (raw_staging, start, cnt, workbuf) != cnt) {
444 error << _("cannot read sample data for unscaled peak computation") << endmsg;
448 for (jack_nframes_t i = 0; i < npeaks; ++i) {
449 peaks[i].max = raw_staging[i];
450 peaks[i].min = raw_staging[i];
453 delete [] raw_staging;
460 off_t first_peak_byte = (start / frames_per_peak) * sizeof (PeakData);
462 /* open, read, close */
464 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
465 error << string_compose(_("Source: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
469 // cerr << "DIRECT PEAKS\n";
471 nread = ::pread (peakfile, peaks, sizeof (PeakData)* npeaks, first_peak_byte);
474 if (nread != sizeof (PeakData) * npeaks) {
477 << "]: cannot read peaks from peakfile! (read only "
491 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
502 // cerr << "DOWNSAMPLE\n";
506 - more frames-per-peak (lower resolution) than the peakfile, or to put it another way,
507 - less peaks than the peakfile holds for the same range
509 So, read a block into a staging area, and then downsample from there.
511 to avoid confusion, I'll refer to the requested peaks as visual_peaks and the peakfile peaks as stored_peaks
514 const uint32_t chunksize = (uint32_t) min (expected_peaks, 4096.0);
516 staging = new PeakData[chunksize];
518 /* compute the rounded up frame position */
520 jack_nframes_t current_frame = start;
521 jack_nframes_t current_stored_peak = (jack_nframes_t) ceil (current_frame / (double) frames_per_peak);
522 uint32_t next_visual_peak = (uint32_t) ceil (current_frame / samples_per_visual_peak);
523 double next_visual_peak_frame = next_visual_peak * samples_per_visual_peak;
524 uint32_t stored_peak_before_next_visual_peak = (jack_nframes_t) next_visual_peak_frame / frames_per_peak;
525 uint32_t nvisual_peaks = 0;
526 uint32_t stored_peaks_read = 0;
529 /* handle the case where the initial visual peak is on a pixel boundary */
531 current_stored_peak = min (current_stored_peak, stored_peak_before_next_visual_peak);
533 /* open ... close during out: handling */
535 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
536 error << string_compose(_("Source: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
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 off_t fend = lseek (peakfile, 0, SEEK_END);
550 if ((nread = ::pread (peakfile, staging, sizeof (PeakData) * to_read, start_byte))
551 != sizeof (PeakData) * to_read) {
554 << "]: cannot read peak data from peakfile ("
555 << (nread / sizeof(PeakData))
556 << " peaks instead of "
561 << " at start_byte = " << start_byte
562 << " _length = " << _length << " versus len = " << fend
563 << " expected maxpeaks = " << (_length - current_frame)/frames_per_peak
564 << " npeaks was " << npeaks
570 stored_peaks_read = nread / sizeof(PeakData);
576 while ((i < stored_peaks_read) && (current_stored_peak <= stored_peak_before_next_visual_peak)) {
578 xmax = max (xmax, staging[i].max);
579 xmin = min (xmin, staging[i].min);
581 ++current_stored_peak;
585 peaks[nvisual_peaks].max = xmax;
586 peaks[nvisual_peaks].min = xmin;
590 //next_visual_peak_frame = min ((next_visual_peak * samples_per_visual_peak), (next_visual_peak_frame+samples_per_visual_peak) );
591 next_visual_peak_frame = min ((double) start+cnt, (next_visual_peak_frame+samples_per_visual_peak) );
592 stored_peak_before_next_visual_peak = (uint32_t) next_visual_peak_frame / frames_per_peak;
596 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
603 // cerr << "UPSAMPLE\n";
607 - less frames-per-peak (more resolution)
608 - more peaks than stored in the Peakfile
610 So, fetch data from the raw source, and generate peak
614 jack_nframes_t frames_read = 0;
615 jack_nframes_t current_frame = start;
616 jack_nframes_t i = 0;
617 jack_nframes_t nvisual_peaks = 0;
618 jack_nframes_t chunksize = (jack_nframes_t) min (cnt, (jack_nframes_t) 4096);
619 raw_staging = new Sample[chunksize];
620 workbuf = new char[chunksize *4];
622 jack_nframes_t frame_pos = start;
623 double pixel_pos = floor (frame_pos / samples_per_visual_peak);
624 double next_pixel_pos = ceil (frame_pos / samples_per_visual_peak);
625 double pixels_per_frame = 1.0 / samples_per_visual_peak;
630 while (nvisual_peaks < npeaks) {
632 if (i == frames_read) {
634 to_read = min (chunksize, (_length - current_frame));
636 if ((frames_read = read_unlocked (raw_staging, current_frame, to_read, workbuf)) < 0) {
637 error << string_compose(_("Source[%1]: peak read - cannot read %2 samples at offset %3")
638 , _name, to_read, current_frame)
646 xmax = max (xmax, raw_staging[i]);
647 xmin = min (xmin, raw_staging[i]);
650 pixel_pos += pixels_per_frame;
652 if (pixel_pos >= next_pixel_pos) {
654 peaks[nvisual_peaks].max = xmax;
655 peaks[nvisual_peaks].min = xmin;
660 next_pixel_pos = ceil (pixel_pos + 0.5);
665 memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
681 delete [] raw_staging;
691 #undef DEBUG_PEAK_BUILD
694 Source::build_peaks ()
696 vector<PeakBuildRecord*> built;
698 bool pr_signal = false;
699 list<PeakBuildRecord*> copy;
702 LockMonitor lm (_lock, __LINE__, __FILE__);
703 copy = pending_peak_builds;
704 pending_peak_builds.clear ();
707 #ifdef DEBUG_PEAK_BUILD
708 cerr << "build peaks with " << copy.size() << " requests pending\n";
711 for (list<PeakBuildRecord *>::iterator i = copy.begin(); i != copy.end(); ++i) {
713 if ((status = do_build_peak ((*i)->frame, (*i)->cnt)) != 0) {
714 unlink (peakpath.c_str());
717 built.push_back (new PeakBuildRecord (*(*i)));
722 LockMonitor lm (_lock, __LINE__, __FILE__);
727 if (next_peak_clear_should_notify) {
728 next_peak_clear_should_notify = false;
735 for (vector<PeakBuildRecord *>::iterator i = built.begin(); i != built.end(); ++i) {
736 PeakRangeReady ((*i)->frame, (*i)->cnt); /* EMIT SIGNAL */
741 PeaksReady (); /* EMIT SIGNAL */
749 Source::do_build_peak (jack_nframes_t first_frame, jack_nframes_t cnt)
751 jack_nframes_t current_frame;
752 Sample buf[frames_per_peak];
757 jack_nframes_t frames_read;
758 jack_nframes_t frames_to_read;
759 off_t first_peak_byte;
763 #ifdef DEBUG_PEAK_BUILD
764 cerr << pthread_self() << ": " << _name << ": building peaks for " << first_frame << " to " << first_frame + cnt - 1 << endl;
767 first_peak_byte = (first_frame / frames_per_peak) * sizeof (PeakData);
769 #ifdef DEBUG_PEAK_BUILD
770 cerr << "seeking to " << first_peak_byte << " before writing new peak data\n";
773 current_frame = first_frame;
774 peakbuf = new PeakData[(cnt/frames_per_peak)+1];
777 workbuf = new char[max(frames_per_peak, cnt) * 4];
779 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
780 error << string_compose(_("Source: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
786 frames_to_read = min (frames_per_peak, cnt);
788 if ((frames_read = read_unlocked (buf, current_frame, frames_to_read, workbuf)) != frames_to_read) {
789 error << string_compose(_("%1: could not write read raw data for peak computation (%2)"), _name, strerror (errno)) << endmsg;
796 for (jack_nframes_t n = 1; n < frames_read; ++n) {
797 xmax = max (xmax, buf[n]);
798 xmin = min (xmin, buf[n]);
800 // if (current_frame < frames_read) {
801 // cerr << "sample = " << buf[n] << " max = " << xmax << " min = " << xmin << " max of 2 = " << max (xmax, buf[n]) << endl;
805 peakbuf[peaki].max = xmax;
806 peakbuf[peaki].min = xmin;
809 current_frame += frames_read;
813 if (::pwrite (peakfile, peakbuf, sizeof (PeakData) * peaki, first_peak_byte) != (ssize_t) (sizeof (PeakData) * peaki)) {
814 error << string_compose(_("%1: could not write peak file data (%2)"), _name, strerror (errno)) << endmsg;
831 Source::build_peaks_from_scratch ()
833 LockMonitor lp (_lock, __LINE__, __FILE__);
835 next_peak_clear_should_notify = true;
836 pending_peak_builds.push_back (new PeakBuildRecord (0, _length));
837 queue_for_peaks (*this);
841 Source::file_changed (string path)
843 struct stat stat_file;
844 struct stat stat_peak;
846 int e1 = stat (path.c_str(), &stat_file);
847 int e2 = stat (peak_path(path).c_str(), &stat_peak);
849 if (!e1 && !e2 && stat_file.st_mtime > stat_peak.st_mtime){
865 if (_use_cnt) --_use_cnt;
869 Source::available_peaks (double zoom_factor) const
874 if (zoom_factor < frames_per_peak) {
875 return length(); // peak data will come from the audio file
878 /* peak data comes from peakfile */
880 if ((peakfile = ::open (peakpath.c_str(), O_RDONLY)) < 0) {
881 error << string_compose(_("Source: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
886 LockMonitor lm (_lock, __LINE__, __FILE__);
887 end = lseek (peakfile, 0, SEEK_END);
892 return (end/sizeof(PeakData)) * frames_per_peak;