committed INCOMPLETE 24bit filesource support
[ardour.git] / libs / ardour / source.cc
1 /*
2     Copyright (C) 2000 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     $Id$
19 */
20
21 #include <sys/stat.h>
22 #include <unistd.h>
23 #include <fcntl.h>
24 #include <poll.h>
25 #include <float.h>
26 #include <cerrno>
27 #include <ctime>
28 #include <cmath>
29 #include <iomanip>
30 #include <algorithm>
31
32 #include <pbd/lockmonitor.h>
33 #include <pbd/xml++.h>
34 #include <pbd/pthread_utils.h>
35
36 #include <ardour/source.h>
37 #include <ardour/filesource.h>
38 #include <ardour/sndfilesource.h>
39
40 #include "i18n.h"
41
42 using std::min;
43 using std::max;
44
45 using namespace ARDOUR;
46 using namespace PBD;
47
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];
54
55 bool Source::_build_missing_peakfiles = false;
56 bool Source::_build_peakfiles = false;
57
58 Source::Source (bool announce)
59 {
60         _id = ARDOUR::new_id();
61         _use_cnt = 0;
62         _peaks_built = false;
63         next_peak_clear_should_notify = true;
64         peakfile = -1;
65         _timestamp = 0;
66         _read_data_count = 0;
67         _write_data_count = 0;
68 }
69
70 Source::Source (const XMLNode& node) 
71 {
72         _use_cnt = 0;
73         _peaks_built = false;
74         next_peak_clear_should_notify = true;
75         peakfile = -1;
76         _timestamp = 0;
77         _read_data_count = 0;
78         _write_data_count = 0;
79
80         if (set_state (node)) {
81                 throw failed_constructor();
82         }
83 }
84
85 Source::~Source ()
86 {
87         if (peakfile >= 0) {
88                 close (peakfile);
89         }
90 }
91
92 XMLNode&
93 Source::get_state ()
94 {
95         XMLNode *node = new XMLNode ("Source");
96         char buf[64];
97
98         node->add_property ("name", _name);
99         snprintf (buf, sizeof(buf)-1, "%" PRIu64, _id);
100         node->add_property ("id", buf);
101
102         if (_timestamp != 0) {
103                 snprintf (buf, sizeof (buf), "%ld", _timestamp);
104                 node->add_property ("timestamp", buf);
105         }
106
107         if (_captured_for.length()) {
108                 node->add_property ("captured-for", _captured_for);
109         }
110
111         return *node;
112 }
113
114 int
115 Source::set_state (const XMLNode& node)
116 {
117         const XMLProperty* prop;
118
119         if ((prop = node.property ("name")) != 0) {
120                 _name = prop->value();
121         } else {
122                 return -1;
123         }
124         
125         if ((prop = node.property ("id")) != 0) {
126                 sscanf (prop->value().c_str(), "%" PRIu64, &_id);
127         } else {
128                 return -1;
129         }
130
131         if ((prop = node.property ("timestamp")) != 0) {
132                 sscanf (prop->value().c_str(), "%ld", &_timestamp);
133         }
134
135         if ((prop = node.property ("captured-for")) != 0) {
136                 _captured_for = prop->value();
137         }
138
139         return 0;
140 }
141
142 /***********************************************************************
143   PEAK FILE STUFF
144  ***********************************************************************/
145
146 void*
147 Source::peak_thread_work (void* arg)
148 {
149         PBD::ThreadCreated (pthread_self(), X_("Peak"));
150         struct pollfd pfd[1];
151
152         LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
153
154         while (true) {
155
156                 pfd[0].fd = peak_request_pipe[0];
157                 pfd[0].events = POLLIN|POLLERR|POLLHUP;
158
159                 pthread_mutex_unlock (pending_peak_sources_lock.mutex());
160
161                 if (poll (pfd, 1, -1) < 0) {
162
163                         if (errno == EINTR) {
164                                 pthread_mutex_lock (pending_peak_sources_lock.mutex());
165                                 continue;
166                         }
167                         
168                         error << string_compose (_("poll on peak request pipe failed (%1)"),
169                                           strerror (errno))
170                               << endmsg;
171                         break;
172                 }
173
174                 if (pfd[0].revents & ~POLLIN) {
175                         error << _("Error on peak thread request pipe") << endmsg;
176                         break;
177                 }
178
179                 if (pfd[0].revents & POLLIN) {
180
181                         char req;
182                         
183                         /* empty the pipe of all current requests */
184
185                         while (1) {
186                                 size_t nread = ::read (peak_request_pipe[0], &req, sizeof (req));
187
188                                 if (nread == 1) {
189                                         switch ((PeakRequest::Type) req) {
190                                         
191                                         case PeakRequest::Build:
192                                                 break;
193                                                 
194                                         case PeakRequest::Quit:
195                                                 pthread_exit_pbd (0);
196                                                 /*NOTREACHED*/
197                                                 break;
198                                                 
199                                         default:
200                                                 break;
201                                         }
202
203                                 } else if (nread == 0) {
204                                         break;
205                                 } else if (errno == EAGAIN) {
206                                         break;
207                                 } else {
208                                         fatal << _("Error reading from peak request pipe") << endmsg;
209                                         /*NOTREACHED*/
210                                 }
211                         }
212                 }
213
214                 pthread_mutex_lock (pending_peak_sources_lock.mutex());
215
216                 while (!pending_peak_sources.empty()) {
217
218                         Source* s = pending_peak_sources.front();
219                         pending_peak_sources.erase (pending_peak_sources.begin());
220
221                         pthread_mutex_unlock (pending_peak_sources_lock.mutex());
222                         s->build_peaks();
223                         pthread_mutex_lock (pending_peak_sources_lock.mutex());
224                 }
225         }
226
227         pthread_exit_pbd (0);
228         /*NOTREACHED*/
229         return 0;
230 }
231
232 int
233 Source::start_peak_thread ()
234 {
235         if (!_build_peakfiles) {
236                 return 0;
237         }
238
239         if (pipe (peak_request_pipe)) {
240                 error << string_compose(_("Cannot create transport request signal pipe (%1)"), strerror (errno)) << endmsg;
241                 return -1;
242         }
243
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;
246                 return -1;
247         }
248
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;
251                 return -1;
252         }
253
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;
256                 return -1;
257         }
258
259         have_peak_thread = true;
260         return 0;
261 }
262
263 void
264 Source::stop_peak_thread ()
265 {
266         if (!have_peak_thread) {
267                 return;
268         }
269
270         void* status;
271
272         char c = (char) PeakRequest::Quit;
273         ::write (peak_request_pipe[1], &c, 1);
274         pthread_join (peak_thread, &status);
275 }
276
277 void 
278 Source::queue_for_peaks (Source& source)
279 {
280         if (have_peak_thread) {
281
282                 LockMonitor lm (pending_peak_sources_lock, __LINE__, __FILE__);
283
284                 source.next_peak_clear_should_notify = true;
285
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);
290                 }
291
292                 char c = (char) PeakRequest::Build;
293                 ::write (peak_request_pipe[1], &c, 1);
294         }
295 }
296
297 void Source::clear_queue_for_peaks ()
298 {
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 ();
303         }
304 }
305
306
307 bool
308 Source::peaks_ready (sigc::slot<void> the_slot) const
309 {
310         bool ret;
311         LockMonitor lm (_lock, __LINE__, __FILE__);
312
313         /* check to see if the peak data is ready. if not
314            connect the slot while still holding the lock.
315         */
316
317         if (!(ret = _peaks_built)) {
318                 PeaksReady.connect (the_slot);
319         }
320
321         return ret;
322 }
323
324 int
325 Source::initialize_peakfile (bool newfile, string audio_path)
326 {
327         struct stat statbuf;
328
329         peakpath = peak_path (audio_path);
330
331         if (newfile) {
332
333                 if (!_build_peakfiles) {
334                         return 0;
335                 }
336
337                 _peaks_built = false;
338
339         } else {
340
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 */
344                                 
345                                 error << string_compose(_("Source: cannot stat peakfile \"%1\""), peakpath) << endmsg;
346                                 return -1;
347                         }
348
349                         /* older sessions stored peaks in the same directory
350                            as the audio. so check there as well.
351                         */
352                         
353                         string oldpeakpath = old_peak_path (audio_path);
354                         
355                         if (stat (oldpeakpath.c_str(), &statbuf)) {
356                                 
357                                 if (errno == ENOENT) {
358
359                                         statbuf.st_size = 0;
360
361                                 } else {
362                                         
363                                         /* it exists in the audio dir , but there is some kind of error */
364                                         
365                                         error << string_compose(_("Source: cannot stat peakfile \"%1\" or \"%2\""), peakpath, oldpeakpath) << endmsg;
366                                         return -1;
367                                 }
368                                 
369                         } else {
370
371                                 /* we found it in the sound dir, where they lived once upon a time, in a land ... etc. */
372
373                                 peakpath = oldpeakpath;
374                         }
375
376                 } else {
377                         
378                         /* we found it in the peaks dir */
379                 }
380                 
381                 if (statbuf.st_size == 0) {
382                         _peaks_built = false;
383                 } else {
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);
387                         
388                         if (!err && stat_file.st_mtime > statbuf.st_mtime){
389                                 _peaks_built = false;
390                         } else {
391                                 _peaks_built = true;
392                         }
393                 }
394         }
395
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;
398                 return -1;
399         }
400
401         if (!newfile && !_peaks_built && _build_missing_peakfiles && _build_peakfiles) {
402                 build_peaks_from_scratch ();
403         } 
404
405         return 0;
406 }
407
408 int 
409 Source::read_peaks (PeakData *peaks, jack_nframes_t npeaks, jack_nframes_t start, jack_nframes_t cnt, double samples_per_visual_peak) const
410 {
411         LockMonitor lm (_lock, __LINE__, __FILE__);
412         double scale;
413         double expected_peaks;
414         PeakData::PeakDatum xmax;
415         PeakData::PeakDatum xmin;
416         int32_t to_read;
417         uint32_t nread;
418         jack_nframes_t zero_fill = 0;
419         int ret = -1;
420         PeakData* staging = 0;
421         Sample* raw_staging = 0;
422         char * workbuf = 0;
423         
424         expected_peaks = (cnt / (double) frames_per_peak);
425         scale = npeaks/expected_peaks;
426
427 #if 0
428         cerr << "======>RP: npeaks = " << npeaks 
429              << " start = " << start 
430              << " cnt = " << cnt 
431              << " len = " << _length 
432              << "   samples_per_visual_peak =" << samples_per_visual_peak 
433              << " expected was " << expected_peaks << " ... scale = " << scale
434              << " PD ptr = " << peaks
435              <<endl;
436         
437 #endif
438
439         /* fix for near-end-of-file conditions */
440
441         if (cnt > _length - start) {
442                 // cerr << "too close to end @ " << _length << " given " << start << " + " << cnt << endl;
443                 cnt = _length - start;
444                 jack_nframes_t old = npeaks;
445                 npeaks = min ((jack_nframes_t) floor (cnt / samples_per_visual_peak), npeaks);
446                 zero_fill = old - npeaks;
447         }
448
449         // cerr << "actual npeaks = " << npeaks << " zf = " << zero_fill << endl;
450         
451         if (npeaks == cnt) {
452
453                 // cerr << "RAW DATA\n";
454                 
455                 /* no scaling at all, just get the sample data and duplicate it for
456                    both max and min peak values.
457                 */
458
459                 Sample* raw_staging = new Sample[cnt];
460                 workbuf = new char[cnt*4];
461                 
462                 if (read_unlocked (raw_staging, start, cnt, workbuf) != cnt) {
463                         error << _("cannot read sample data for unscaled peak computation") << endmsg;
464                         return -1;
465                 }
466
467                 for (jack_nframes_t i = 0; i < npeaks; ++i) {
468                         peaks[i].max = raw_staging[i];
469                         peaks[i].min = raw_staging[i];
470                 }
471
472                 delete [] raw_staging;
473                 delete [] workbuf;
474                 return 0;
475         }
476
477         if (scale == 1.0) {
478
479                 // cerr << "DIRECT PEAKS\n";
480                 
481                 off_t first_peak_byte = (start / frames_per_peak) * sizeof (PeakData);
482
483                 if ((nread = ::pread (peakfile, peaks, sizeof (PeakData)* npeaks, first_peak_byte)) != sizeof (PeakData) * npeaks) {
484                         cerr << "Source["
485                              << _name
486                              << "]: cannot read peaks from peakfile! (read only " 
487                              << nread
488                              << " not " 
489                              << npeaks
490                               << "at sample " 
491                              << start
492                              << " = byte "
493                              << first_peak_byte
494                              << ')'
495                              << endl;
496                         return -1;
497                 }
498
499                 if (zero_fill) {
500                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
501                 }
502
503                 return 0;
504         }
505
506
507         jack_nframes_t tnp;
508
509         if (scale < 1.0) {
510
511                 // cerr << "DOWNSAMPLE\n";
512
513                 /* the caller wants:
514
515                     - more frames-per-peak (lower resolution) than the peakfile, or to put it another way,
516                     - less peaks than the peakfile holds for the same range
517
518                     So, read a block into a staging area, and then downsample from there.
519
520                     to avoid confusion, I'll refer to the requested peaks as visual_peaks and the peakfile peaks as stored_peaks  
521                 */
522
523                 const uint32_t chunksize = (uint32_t) min (expected_peaks, 4096.0);
524                 
525                 staging = new PeakData[chunksize];
526                 
527                 /* compute the rounded up frame position  */
528         
529                 jack_nframes_t current_frame = start;
530                 jack_nframes_t current_stored_peak = (jack_nframes_t) ceil (current_frame / (double) frames_per_peak);
531                 uint32_t       next_visual_peak  = (uint32_t) ceil (current_frame / samples_per_visual_peak);
532                 double         next_visual_peak_frame = next_visual_peak * samples_per_visual_peak;
533                 uint32_t       stored_peak_before_next_visual_peak = (jack_nframes_t) next_visual_peak_frame / frames_per_peak;
534                 uint32_t       nvisual_peaks = 0;
535                 uint32_t       stored_peaks_read = 0;
536                 uint32_t       i = 0;
537
538                 /* handle the case where the initial visual peak is on a pixel boundary */
539
540                 current_stored_peak = min (current_stored_peak, stored_peak_before_next_visual_peak);
541
542                 while (nvisual_peaks < npeaks) {
543
544                         if (i == stored_peaks_read) {
545
546                                 uint32_t       start_byte = current_stored_peak * sizeof(PeakData);
547                                 tnp = min ((_length/frames_per_peak - current_stored_peak), (jack_nframes_t) expected_peaks);
548                                 to_read = min (chunksize, tnp);
549                                 
550                                 if ((nread = ::pread (peakfile, staging, sizeof (PeakData) * to_read, start_byte))
551                                     != sizeof (PeakData) * to_read) {
552                                         cerr << "Source["
553                                              << _name
554                                              << "]: cannot read peak data from peakfile ("
555                                              << nread 
556                                              << " peaks instead of "
557                                              << to_read
558                                              << ") ("
559                                              << strerror (errno)
560                                              << ')'
561                                              << " at start_byte = " << start_byte 
562                                              << " _length = " << _length
563                                              << " expected maxpeaks = " << (_length - current_frame)/frames_per_peak
564                                              << " npeaks was " << npeaks
565                                              << endl;
566                                         goto out;
567                                 }
568
569                                 i = 0;
570                                 stored_peaks_read = nread / sizeof(PeakData);
571                         }
572
573                         xmax = -1.0;
574                         xmin = 1.0;
575
576                         while ((i < stored_peaks_read) && (current_stored_peak <= stored_peak_before_next_visual_peak)) {
577
578                                 xmax = max (xmax, staging[i].max);
579                                 xmin = min (xmin, staging[i].min);
580                                 ++i;
581                                 ++current_stored_peak;
582                                 --expected_peaks;
583                         }
584
585                         peaks[nvisual_peaks].max = xmax;
586                         peaks[nvisual_peaks].min = xmin;
587                         ++nvisual_peaks;
588                         ++next_visual_peak;
589
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; 
593                 }
594
595                 if (zero_fill) {
596                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
597                 }
598                 
599                 ret = 0;
600
601         } else {
602                 
603                 // cerr << "UPSAMPLE\n";
604
605                 /* the caller wants 
606
607                      - less frames-per-peak (more resolution)
608                      - more peaks than stored in the Peakfile
609
610                    So, fetch data from the raw source, and generate peak
611                    data on the fly.
612                 */
613
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];
621                 
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;
626
627                 xmin = 1.0;
628                 xmax = -1.0;
629
630                 while (nvisual_peaks < npeaks) {
631
632                         if (i == frames_read) {
633                                 
634                                 to_read = min (chunksize, (_length - current_frame));
635                                 
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) 
639                                               << endmsg;
640                                         goto out;
641                                 }
642
643                                 i = 0;
644                         }
645                         
646                         xmax = max (xmax, raw_staging[i]);
647                         xmin = min (xmin, raw_staging[i]);
648                         ++i;
649                         ++current_frame;
650                         pixel_pos += pixels_per_frame;
651
652                         if (pixel_pos >= next_pixel_pos) {
653
654                                 peaks[nvisual_peaks].max = xmax;
655                                 peaks[nvisual_peaks].min = xmin;
656                                 ++nvisual_peaks;
657                                 xmin = 1.0;
658                                 xmax = -1.0;
659
660                                 next_pixel_pos = ceil (pixel_pos + 0.5);
661                         }
662                 }
663                 
664                 if (zero_fill) {
665                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
666                 }
667
668                 ret = 0;
669         }
670
671   out:
672         if (staging) {
673                 delete [] staging;
674         } 
675
676         if (raw_staging) {
677                 delete [] raw_staging;
678         }
679
680         if (workbuf) {
681                 delete [] workbuf;
682         }
683         
684         return ret;
685 }
686
687 #undef DEBUG_PEAK_BUILD
688
689 int
690 Source::build_peaks ()
691 {
692         vector<PeakBuildRecord*> built;
693         int status = -1;
694         bool pr_signal = false;
695         list<PeakBuildRecord*> copy;
696
697         {
698                 LockMonitor lm (_lock, __LINE__, __FILE__);
699                 copy = pending_peak_builds;
700                 pending_peak_builds.clear ();
701         }
702                 
703
704 #ifdef DEBUG_PEAK_BUILD
705         cerr << "build peaks with " << pending_peak_builds.size() << " requests pending\n";
706 #endif          
707
708         for (list<PeakBuildRecord *>::iterator i = copy.begin(); i != copy.end(); ++i) {
709                 
710                 if ((status = do_build_peak ((*i)->frame, (*i)->cnt)) != 0) { 
711                         unlink (peakpath.c_str());
712                         break;
713                 }
714                 built.push_back (new PeakBuildRecord (*(*i)));
715                 delete *i;
716         }
717
718         { 
719                 LockMonitor lm (_lock, __LINE__, __FILE__);
720
721                 if (status == 0) {
722                         _peaks_built = true;
723                         
724                         if (next_peak_clear_should_notify) {
725                                 next_peak_clear_should_notify = false;
726                                 pr_signal = true;
727                         }
728                 }
729         }
730
731         if (status == 0) {
732                 for (vector<PeakBuildRecord *>::iterator i = built.begin(); i != built.end(); ++i) {
733                         PeakRangeReady ((*i)->frame, (*i)->cnt); /* EMIT SIGNAL */
734                         delete *i;
735                 }
736
737                 if (pr_signal) {
738                         PeaksReady (); /* EMIT SIGNAL */
739                 }
740         }
741
742         return status;
743 }
744
745 int
746 Source::do_build_peak (jack_nframes_t first_frame, jack_nframes_t cnt)
747 {
748         jack_nframes_t current_frame;
749         Sample buf[frames_per_peak];
750         Sample xmin, xmax;
751         uint32_t  peaki;
752         PeakData* peakbuf;
753         char * workbuf = 0;
754         jack_nframes_t frames_read;
755         jack_nframes_t frames_to_read;
756         off_t first_peak_byte;
757         int ret = -1;
758
759 #ifdef DEBUG_PEAK_BUILD
760         cerr << pthread_self() << ": " << _name << ": building peaks for " << first_frame << " to " << first_frame + cnt - 1 << endl;
761 #endif
762
763         first_peak_byte = (first_frame / frames_per_peak) * sizeof (PeakData);
764
765 #ifdef DEBUG_PEAK_BUILD
766         cerr << "seeking to " << first_peak_byte << " before writing new peak data\n";
767 #endif
768
769         current_frame = first_frame;
770         peakbuf = new PeakData[(cnt/frames_per_peak)+1];
771         peaki = 0;
772
773         workbuf = new char[max(frames_per_peak, cnt) * 4];
774         
775         while (cnt) {
776
777                 frames_to_read = min (frames_per_peak, cnt);
778
779                 if ((frames_read = read_unlocked (buf, current_frame, frames_to_read, workbuf)) != frames_to_read) {
780                         error << string_compose(_("%1: could not write read raw data for peak computation (%2)"), _name, strerror (errno)) << endmsg;
781                         goto out;
782                 }
783
784                 xmin = buf[0];
785                 xmax = buf[0];
786
787                 for (jack_nframes_t n = 1; n < frames_read; ++n) {
788                         xmax = max (xmax, buf[n]);
789                         xmin = min (xmin, buf[n]);
790
791 //                      if (current_frame < frames_read) {
792 //                              cerr << "sample = " << buf[n] << " max = " << xmax << " min = " << xmin << " max of 2 = " << max (xmax, buf[n]) << endl;
793 //                      }
794                 }
795
796                 peakbuf[peaki].max = xmax;
797                 peakbuf[peaki].min = xmin;
798                 peaki++;
799
800                 current_frame += frames_read;
801                 cnt -= frames_read;
802         }
803
804         if (::pwrite (peakfile, peakbuf, sizeof (PeakData) * peaki, first_peak_byte) != (ssize_t) (sizeof (PeakData) * peaki)) {
805                 error << string_compose(_("%1: could not write peak file data (%2)"), _name, strerror (errno)) << endmsg;
806                 goto out;
807         }
808
809         ret = 0;
810
811   out:
812         delete [] peakbuf;
813         if (workbuf)
814                 delete [] workbuf;
815         return ret;
816 }
817
818 void
819 Source::build_peaks_from_scratch ()
820 {
821         LockMonitor lp (_lock, __LINE__, __FILE__); 
822
823         next_peak_clear_should_notify = true;
824         pending_peak_builds.push_back (new PeakBuildRecord (0, _length));
825         queue_for_peaks (*this);
826 }
827
828 bool
829 Source::file_changed (string path)
830 {
831         struct stat stat_file;
832         struct stat stat_peak;
833
834         int e1 = stat (path.c_str(), &stat_file);
835         int e2 = stat (peak_path(path).c_str(), &stat_peak);
836         
837         if (!e1 && !e2 && stat_file.st_mtime > stat_peak.st_mtime){
838                 return true;
839         } else {
840                 return false;
841         }
842 }
843
844 void
845 Source::use ()
846 {
847         _use_cnt++;
848 }
849
850 void
851 Source::release ()
852 {
853         if (_use_cnt) --_use_cnt;
854 }