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