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