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