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