fix compose mess, and a number of 64 bit printf specs
[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
423         expected_peaks = (cnt / (double) frames_per_peak);
424         scale = npeaks/expected_peaks;
425
426 #if 0
427         cerr << "======>RP: npeaks = " << npeaks 
428              << " start = " << start 
429              << " cnt = " << cnt 
430              << " len = " << _length 
431              << "   samples_per_visual_peak =" << samples_per_visual_peak 
432              << " expected was " << expected_peaks << " ... scale = " << scale
433              << " PD ptr = " << peaks
434              <<endl;
435         
436 #endif
437
438         /* fix for near-end-of-file conditions */
439
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;
446         }
447
448         // cerr << "actual npeaks = " << npeaks << " zf = " << zero_fill << endl;
449         
450         if (npeaks == cnt) {
451
452                 // cerr << "RAW DATA\n";
453                 
454                 /* no scaling at all, just get the sample data and duplicate it for
455                    both max and min peak values.
456                 */
457
458                 Sample* raw_staging = new Sample[cnt];
459                 
460                 if (read_unlocked (raw_staging, start, cnt) != cnt) {
461                         error << _("cannot read sample data for unscaled peak computation") << endmsg;
462                         return -1;
463                 }
464
465                 for (jack_nframes_t i = 0; i < npeaks; ++i) {
466                         peaks[i].max = raw_staging[i];
467                         peaks[i].min = raw_staging[i];
468                 }
469
470                 delete [] raw_staging;
471                 
472                 return 0;
473         }
474
475         if (scale == 1.0) {
476
477                 // cerr << "DIRECT PEAKS\n";
478                 
479                 off_t first_peak_byte = (start / frames_per_peak) * sizeof (PeakData);
480
481                 if ((nread = ::pread (peakfile, peaks, sizeof (PeakData)* npeaks, first_peak_byte)) != sizeof (PeakData) * npeaks) {
482                         cerr << "Source["
483                              << _name
484                              << "]: cannot read peaks from peakfile! (read only " 
485                              << nread
486                              << " not " 
487                              << npeaks
488                               << "at sample " 
489                              << start
490                              << " = byte "
491                              << first_peak_byte
492                              << ')'
493                              << endl;
494                         return -1;
495                 }
496
497                 if (zero_fill) {
498                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
499                 }
500
501                 return 0;
502         }
503
504
505         jack_nframes_t tnp;
506
507         if (scale < 1.0) {
508
509                 // cerr << "DOWNSAMPLE\n";
510
511                 /* the caller wants:
512
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
515
516                     So, read a block into a staging area, and then downsample from there.
517
518                     to avoid confusion, I'll refer to the requested peaks as visual_peaks and the peakfile peaks as stored_peaks  
519                 */
520
521                 const uint32_t chunksize = (uint32_t) min (expected_peaks, 4096.0);
522                 
523                 staging = new PeakData[chunksize];
524                 
525                 /* compute the rounded up frame position  */
526         
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;
534                 uint32_t       i = 0;
535
536                 /* handle the case where the initial visual peak is on a pixel boundary */
537
538                 current_stored_peak = min (current_stored_peak, stored_peak_before_next_visual_peak);
539
540                 while (nvisual_peaks < npeaks) {
541
542                         if (i == stored_peaks_read) {
543
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);
547                                 
548                                 if ((nread = ::pread (peakfile, staging, sizeof (PeakData) * to_read, start_byte))
549                                     != sizeof (PeakData) * to_read) {
550                                         cerr << "Source["
551                                              << _name
552                                              << "]: cannot read peak data from peakfile ("
553                                              << nread 
554                                              << " peaks instead of "
555                                              << to_read
556                                              << ") ("
557                                              << strerror (errno)
558                                              << ')'
559                                              << " at start_byte = " << start_byte 
560                                              << " _length = " << _length
561                                              << " expected maxpeaks = " << (_length - current_frame)/frames_per_peak
562                                              << " npeaks was " << npeaks
563                                              << endl;
564                                         goto out;
565                                 }
566
567                                 i = 0;
568                                 stored_peaks_read = nread / sizeof(PeakData);
569                         }
570
571                         xmax = -1.0;
572                         xmin = 1.0;
573
574                         while ((i < stored_peaks_read) && (current_stored_peak <= stored_peak_before_next_visual_peak)) {
575
576                                 xmax = max (xmax, staging[i].max);
577                                 xmin = min (xmin, staging[i].min);
578                                 ++i;
579                                 ++current_stored_peak;
580                                 --expected_peaks;
581                         }
582
583                         peaks[nvisual_peaks].max = xmax;
584                         peaks[nvisual_peaks].min = xmin;
585                         ++nvisual_peaks;
586                         ++next_visual_peak;
587
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; 
591                 }
592
593                 if (zero_fill) {
594                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
595                 }
596                 
597                 ret = 0;
598
599         } else {
600                 
601                 // cerr << "UPSAMPLE\n";
602
603                 /* the caller wants 
604
605                      - less frames-per-peak (more resolution)
606                      - more peaks than stored in the Peakfile
607
608                    So, fetch data from the raw source, and generate peak
609                    data on the fly.
610                 */
611
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];
618
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;
623
624                 xmin = 1.0;
625                 xmax = -1.0;
626
627                 while (nvisual_peaks < npeaks) {
628
629                         if (i == frames_read) {
630                                 
631                                 to_read = min (chunksize, (_length - current_frame));
632                                 
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) 
636                                               << endmsg;
637                                         goto out;
638                                 }
639
640                                 i = 0;
641                         }
642                         
643                         xmax = max (xmax, raw_staging[i]);
644                         xmin = min (xmin, raw_staging[i]);
645                         ++i;
646                         ++current_frame;
647                         pixel_pos += pixels_per_frame;
648
649                         if (pixel_pos >= next_pixel_pos) {
650
651                                 peaks[nvisual_peaks].max = xmax;
652                                 peaks[nvisual_peaks].min = xmin;
653                                 ++nvisual_peaks;
654                                 xmin = 1.0;
655                                 xmax = -1.0;
656
657                                 next_pixel_pos = ceil (pixel_pos + 0.5);
658                         }
659                 }
660                 
661                 if (zero_fill) {
662                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
663                 }
664
665                 ret = 0;
666         }
667
668   out:
669         if (staging) {
670                 delete [] staging;
671         } 
672
673         if (raw_staging) {
674                 delete [] raw_staging;
675         }
676
677         return ret;
678 }
679
680 #undef DEBUG_PEAK_BUILD
681
682 int
683 Source::build_peaks ()
684 {
685         vector<PeakBuildRecord*> built;
686         int status = -1;
687         bool pr_signal = false;
688         list<PeakBuildRecord*> copy;
689
690         {
691                 LockMonitor lm (_lock, __LINE__, __FILE__);
692                 copy = pending_peak_builds;
693                 pending_peak_builds.clear ();
694         }
695                 
696
697 #ifdef DEBUG_PEAK_BUILD
698         cerr << "build peaks with " << pending_peak_builds.size() << " requests pending\n";
699 #endif          
700
701         for (list<PeakBuildRecord *>::iterator i = copy.begin(); i != copy.end(); ++i) {
702                 
703                 if ((status = do_build_peak ((*i)->frame, (*i)->cnt)) != 0) { 
704                         unlink (peakpath.c_str());
705                         break;
706                 }
707                 built.push_back (new PeakBuildRecord (*(*i)));
708                 delete *i;
709         }
710
711         { 
712                 LockMonitor lm (_lock, __LINE__, __FILE__);
713
714                 if (status == 0) {
715                         _peaks_built = true;
716                         
717                         if (next_peak_clear_should_notify) {
718                                 next_peak_clear_should_notify = false;
719                                 pr_signal = true;
720                         }
721                 }
722         }
723
724         if (status == 0) {
725                 for (vector<PeakBuildRecord *>::iterator i = built.begin(); i != built.end(); ++i) {
726                         PeakRangeReady ((*i)->frame, (*i)->cnt); /* EMIT SIGNAL */
727                         delete *i;
728                 }
729
730                 if (pr_signal) {
731                         PeaksReady (); /* EMIT SIGNAL */
732                 }
733         }
734
735         return status;
736 }
737
738 int
739 Source::do_build_peak (jack_nframes_t first_frame, jack_nframes_t cnt)
740 {
741         jack_nframes_t current_frame;
742         Sample buf[frames_per_peak];
743         Sample xmin, xmax;
744         uint32_t  peaki;
745         PeakData* peakbuf;
746         jack_nframes_t frames_read;
747         jack_nframes_t frames_to_read;
748         off_t first_peak_byte;
749         int ret = -1;
750
751 #ifdef DEBUG_PEAK_BUILD
752         cerr << pthread_self() << ": " << _name << ": building peaks for " << first_frame << " to " << first_frame + cnt - 1 << endl;
753 #endif
754
755         first_peak_byte = (first_frame / frames_per_peak) * sizeof (PeakData);
756
757 #ifdef DEBUG_PEAK_BUILD
758         cerr << "seeking to " << first_peak_byte << " before writing new peak data\n";
759 #endif
760
761         current_frame = first_frame;
762         peakbuf = new PeakData[(cnt/frames_per_peak)+1];
763         peaki = 0;
764
765         while (cnt) {
766
767                 frames_to_read = min (frames_per_peak, cnt);
768
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;
771                         goto out;
772                 }
773
774                 xmin = buf[0];
775                 xmax = buf[0];
776
777                 for (jack_nframes_t n = 1; n < frames_read; ++n) {
778                         xmax = max (xmax, buf[n]);
779                         xmin = min (xmin, buf[n]);
780
781 //                      if (current_frame < frames_read) {
782 //                              cerr << "sample = " << buf[n] << " max = " << xmax << " min = " << xmin << " max of 2 = " << max (xmax, buf[n]) << endl;
783 //                      }
784                 }
785
786                 peakbuf[peaki].max = xmax;
787                 peakbuf[peaki].min = xmin;
788                 peaki++;
789
790                 current_frame += frames_read;
791                 cnt -= frames_read;
792         }
793
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;
796                 goto out;
797         }
798
799         ret = 0;
800
801   out:
802         delete [] peakbuf;
803         return ret;
804 }
805
806 void
807 Source::build_peaks_from_scratch ()
808 {
809         LockMonitor lp (_lock, __LINE__, __FILE__); 
810
811         next_peak_clear_should_notify = true;
812         pending_peak_builds.push_back (new PeakBuildRecord (0, _length));
813         queue_for_peaks (*this);
814 }
815
816 bool
817 Source::file_changed (string path)
818 {
819         struct stat stat_file;
820         struct stat stat_peak;
821
822         int e1 = stat (path.c_str(), &stat_file);
823         int e2 = stat (peak_path(path).c_str(), &stat_peak);
824         
825         if (!e1 && !e2 && stat_file.st_mtime > stat_peak.st_mtime){
826                 return true;
827         } else {
828                 return false;
829         }
830 }
831
832 void
833 Source::use ()
834 {
835         _use_cnt++;
836 }
837
838 void
839 Source::release ()
840 {
841         if (_use_cnt) --_use_cnt;
842 }