Merged with trunk R708
[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 sigc::signal<void,AudioSource *> AudioSource::AudioSourceCreated;
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 (string name)
54         : Source (name)
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 (const XMLNode& node) 
67         : Source (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, char * workbuf) const
383 {
384         Glib::Mutex::Lock lm (_lock);
385         return read_unlocked (dst, start, cnt, workbuf);
386 }
387
388 jack_nframes_t
389 AudioSource::write (Sample *dst, jack_nframes_t cnt, char * workbuf)
390 {
391         Glib::Mutex::Lock lm (_lock);
392         return write_unlocked (dst, cnt, workbuf);
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         char * workbuf = 0;
410         int peakfile = -1;
411
412         expected_peaks = (cnt / (double) frames_per_peak);
413         scale = npeaks/expected_peaks;
414
415 #if 0
416         cerr << "======>RP: npeaks = " << npeaks 
417              << " start = " << start 
418              << " cnt = " << cnt 
419              << " len = " << _length 
420              << "   samples_per_visual_peak =" << samples_per_visual_peak 
421              << " expected was " << expected_peaks << " ... scale = " << scale
422              << " PD ptr = " << peaks
423              <<endl;
424         
425 #endif
426
427         /* fix for near-end-of-file conditions */
428
429         if (cnt > _length - start) {
430                 // cerr << "too close to end @ " << _length << " given " << start << " + " << cnt << endl;
431                 cnt = _length - start;
432                 jack_nframes_t old = npeaks;
433                 npeaks = min ((jack_nframes_t) floor (cnt / samples_per_visual_peak), npeaks);
434                 zero_fill = old - npeaks;
435         }
436
437         // cerr << "actual npeaks = " << npeaks << " zf = " << zero_fill << endl;
438         
439         if (npeaks == cnt) {
440
441                 // cerr << "RAW DATA\n";
442                 
443                 /* no scaling at all, just get the sample data and duplicate it for
444                    both max and min peak values.
445                 */
446
447                 Sample* raw_staging = new Sample[cnt];
448                 workbuf = new char[cnt*4];
449                 
450                 if (read_unlocked (raw_staging, start, cnt, workbuf) != cnt) {
451                         error << _("cannot read sample data for unscaled peak computation") << endmsg;
452                         return -1;
453                 }
454
455                 for (jack_nframes_t i = 0; i < npeaks; ++i) {
456                         peaks[i].max = raw_staging[i];
457                         peaks[i].min = raw_staging[i];
458                 }
459
460                 delete [] raw_staging;
461                 delete [] workbuf;
462                 return 0;
463         }
464
465         if (scale == 1.0) {
466
467                 off_t first_peak_byte = (start / frames_per_peak) * sizeof (PeakData);
468
469                 /* open, read, close */
470
471                 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
472                         error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
473                         return -1;
474                 }
475
476                 // cerr << "DIRECT PEAKS\n";
477                 
478                 nread = ::pread (peakfile, peaks, sizeof (PeakData)* npeaks, first_peak_byte);
479                 close (peakfile);
480
481                 if (nread != sizeof (PeakData) * npeaks) {
482                         cerr << "AudioSource["
483                              << _name
484                              << "]: cannot read peaks from peakfile! (read only " 
485                              << nread
486                              << " not " 
487                              << npeaks
488                               << "at sample " 
489                              << start
490                              << " = byte "
491                              << first_peak_byte
492                              << ')'
493                              << endl;
494                         return -1;
495                 }
496
497                 if (zero_fill) {
498                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
499                 }
500
501                 return 0;
502         }
503
504
505         jack_nframes_t tnp;
506
507         if (scale < 1.0) {
508
509                 // cerr << "DOWNSAMPLE\n";
510
511                 /* the caller wants:
512
513                     - more frames-per-peak (lower resolution) than the peakfile, or to put it another way,
514                     - less peaks than the peakfile holds for the same range
515
516                     So, read a block into a staging area, and then downsample from there.
517
518                     to avoid confusion, I'll refer to the requested peaks as visual_peaks and the peakfile peaks as stored_peaks  
519                 */
520
521                 const uint32_t chunksize = (uint32_t) min (expected_peaks, 4096.0);
522                 
523                 staging = new PeakData[chunksize];
524                 
525                 /* compute the rounded up frame position  */
526         
527                 jack_nframes_t current_frame = start;
528                 jack_nframes_t current_stored_peak = (jack_nframes_t) ceil (current_frame / (double) frames_per_peak);
529                 uint32_t       next_visual_peak  = (uint32_t) ceil (current_frame / samples_per_visual_peak);
530                 double         next_visual_peak_frame = next_visual_peak * samples_per_visual_peak;
531                 uint32_t       stored_peak_before_next_visual_peak = (jack_nframes_t) next_visual_peak_frame / frames_per_peak;
532                 uint32_t       nvisual_peaks = 0;
533                 uint32_t       stored_peaks_read = 0;
534                 uint32_t       i = 0;
535
536                 /* handle the case where the initial visual peak is on a pixel boundary */
537
538                 current_stored_peak = min (current_stored_peak, stored_peak_before_next_visual_peak);
539
540                 /* open ... close during out: handling */
541
542                 if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
543                         error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
544                         return 0;
545                 }
546
547                 while (nvisual_peaks < npeaks) {
548
549                         if (i == stored_peaks_read) {
550
551                                 uint32_t       start_byte = current_stored_peak * sizeof(PeakData);
552                                 tnp = min ((_length/frames_per_peak - current_stored_peak), (jack_nframes_t) expected_peaks);
553                                 to_read = min (chunksize, tnp);
554                                 
555                                 off_t fend = lseek (peakfile, 0, SEEK_END);
556                                 
557                                 if ((nread = ::pread (peakfile, staging, sizeof (PeakData) * to_read, start_byte))
558                                     != sizeof (PeakData) * to_read) {
559                                         cerr << "AudioSource["
560                                              << _name
561                                              << "]: cannot read peak data from peakfile ("
562                                              << (nread / sizeof(PeakData))
563                                              << " peaks instead of "
564                                              << to_read
565                                              << ") ("
566                                              << strerror (errno)
567                                              << ')'
568                                              << " at start_byte = " << start_byte 
569                                              << " _length = " << _length << " versus len = " << fend
570                                              << " expected maxpeaks = " << (_length - current_frame)/frames_per_peak
571                                              << " npeaks was " << npeaks
572                                              << endl;
573                                         goto out;
574                                 }
575
576                                 i = 0;
577                                 stored_peaks_read = nread / sizeof(PeakData);
578                         }
579
580                         xmax = -1.0;
581                         xmin = 1.0;
582
583                         while ((i < stored_peaks_read) && (current_stored_peak <= stored_peak_before_next_visual_peak)) {
584
585                                 xmax = max (xmax, staging[i].max);
586                                 xmin = min (xmin, staging[i].min);
587                                 ++i;
588                                 ++current_stored_peak;
589                                 --expected_peaks;
590                         }
591
592                         peaks[nvisual_peaks].max = xmax;
593                         peaks[nvisual_peaks].min = xmin;
594                         ++nvisual_peaks;
595                         ++next_visual_peak;
596
597                         //next_visual_peak_frame = min ((next_visual_peak * samples_per_visual_peak), (next_visual_peak_frame+samples_per_visual_peak) );
598                         next_visual_peak_frame =  min ((double) start+cnt, (next_visual_peak_frame+samples_per_visual_peak) );
599                         stored_peak_before_next_visual_peak = (uint32_t) next_visual_peak_frame / frames_per_peak; 
600                 }
601
602                 if (zero_fill) {
603                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
604                 }
605                 
606                 ret = 0;
607
608         } else {
609                 
610                 // cerr << "UPSAMPLE\n";
611
612                 /* the caller wants 
613
614                      - less frames-per-peak (more resolution)
615                      - more peaks than stored in the Peakfile
616
617                    So, fetch data from the raw source, and generate peak
618                    data on the fly.
619                 */
620
621                 jack_nframes_t frames_read = 0;
622                 jack_nframes_t current_frame = start;
623                 jack_nframes_t i = 0;
624                 jack_nframes_t nvisual_peaks = 0;
625                 jack_nframes_t chunksize = (jack_nframes_t) min (cnt, (jack_nframes_t) 4096);
626                 raw_staging = new Sample[chunksize];
627                 workbuf = new char[chunksize *4];
628                 
629                 jack_nframes_t frame_pos = start;
630                 double pixel_pos = floor (frame_pos / samples_per_visual_peak);
631                 double next_pixel_pos = ceil (frame_pos / samples_per_visual_peak);
632                 double pixels_per_frame = 1.0 / samples_per_visual_peak;
633
634                 xmin = 1.0;
635                 xmax = -1.0;
636
637                 while (nvisual_peaks < npeaks) {
638
639                         if (i == frames_read) {
640                                 
641                                 to_read = min (chunksize, (_length - current_frame));
642                                 
643                                 if ((frames_read = read_unlocked (raw_staging, current_frame, to_read, workbuf)) == 0) {
644                                         error << string_compose(_("AudioSource[%1]: peak read - cannot read %2 samples at offset %3")
645                                                          , _name, to_read, current_frame) 
646                                               << endmsg;
647                                         goto out;
648                                 }
649
650                                 i = 0;
651                         }
652                         
653                         xmax = max (xmax, raw_staging[i]);
654                         xmin = min (xmin, raw_staging[i]);
655                         ++i;
656                         ++current_frame;
657                         pixel_pos += pixels_per_frame;
658
659                         if (pixel_pos >= next_pixel_pos) {
660
661                                 peaks[nvisual_peaks].max = xmax;
662                                 peaks[nvisual_peaks].min = xmin;
663                                 ++nvisual_peaks;
664                                 xmin = 1.0;
665                                 xmax = -1.0;
666
667                                 next_pixel_pos = ceil (pixel_pos + 0.5);
668                         }
669                 }
670                 
671                 if (zero_fill) {
672                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
673                 }
674
675                 ret = 0;
676         }
677
678   out:
679         if (peakfile >= 0) {
680                 close (peakfile);
681         }
682
683         if (staging) {
684                 delete [] staging;
685         } 
686
687         if (raw_staging) {
688                 delete [] raw_staging;
689         }
690
691         if (workbuf) {
692                 delete [] workbuf;
693         }
694         
695         return ret;
696 }
697
698 #undef DEBUG_PEAK_BUILD
699
700 int
701 AudioSource::build_peaks ()
702 {
703         vector<PeakBuildRecord*> built;
704         int status = -1;
705         bool pr_signal = false;
706         list<PeakBuildRecord*> copy;
707
708         {
709                 Glib::Mutex::Lock lm (_lock);
710                 copy = pending_peak_builds;
711                 pending_peak_builds.clear ();
712         }
713                 
714 #ifdef DEBUG_PEAK_BUILD
715         cerr << "build peaks with " << copy.size() << " requests pending\n";
716 #endif          
717
718         for (list<PeakBuildRecord *>::iterator i = copy.begin(); i != copy.end(); ++i) {
719                 
720                 if ((status = do_build_peak ((*i)->frame, (*i)->cnt)) != 0) { 
721                         unlink (peakpath.c_str());
722                         break;
723                 }
724                 built.push_back (new PeakBuildRecord (*(*i)));
725                 delete *i;
726         }
727
728         { 
729                 Glib::Mutex::Lock lm (_lock);
730
731                 if (status == 0) {
732                         _peaks_built = true;
733                         
734                         if (next_peak_clear_should_notify) {
735                                 next_peak_clear_should_notify = false;
736                                 pr_signal = true;
737                         }
738                 }
739         }
740
741         if (status == 0) {
742                 for (vector<PeakBuildRecord *>::iterator i = built.begin(); i != built.end(); ++i) {
743                         PeakRangeReady ((*i)->frame, (*i)->cnt); /* EMIT SIGNAL */
744                         delete *i;
745                 }
746
747                 if (pr_signal) {
748                         PeaksReady (); /* EMIT SIGNAL */
749                 }
750         }
751
752         return status;
753 }
754
755 int
756 AudioSource::do_build_peak (jack_nframes_t first_frame, jack_nframes_t cnt)
757 {
758         jack_nframes_t current_frame;
759         Sample buf[frames_per_peak];
760         Sample xmin, xmax;
761         uint32_t  peaki;
762         PeakData* peakbuf;
763         char * workbuf = 0;
764         jack_nframes_t frames_read;
765         jack_nframes_t frames_to_read;
766         off_t first_peak_byte;
767         int peakfile = -1;
768         int ret = -1;
769
770 #ifdef DEBUG_PEAK_BUILD
771         cerr << pthread_self() << ": " << _name << ": building peaks for " << first_frame << " to " << first_frame + cnt - 1 << endl;
772 #endif
773
774         first_peak_byte = (first_frame / frames_per_peak) * sizeof (PeakData);
775
776 #ifdef DEBUG_PEAK_BUILD
777         cerr << "seeking to " << first_peak_byte << " before writing new peak data\n";
778 #endif
779
780         current_frame = first_frame;
781         peakbuf = new PeakData[(cnt/frames_per_peak)+1];
782         peaki = 0;
783
784         workbuf = new char[max(frames_per_peak, cnt) * 4];
785         
786         if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
787                 error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
788                 return -1;
789         }
790         
791         while (cnt) {
792
793                 frames_to_read = min (frames_per_peak, cnt);
794
795                 /* lock for every read */
796
797                 if ((frames_read = read (buf, current_frame, frames_to_read, workbuf)) != frames_to_read) {
798                         error << string_compose(_("%1: could not write read raw data for peak computation (%2)"), _name, strerror (errno)) << endmsg;
799                         goto out;
800                 }
801
802                 xmin = buf[0];
803                 xmax = buf[0];
804
805                 for (jack_nframes_t n = 1; n < frames_read; ++n) {
806                         xmax = max (xmax, buf[n]);
807                         xmin = min (xmin, buf[n]);
808
809 //                      if (current_frame < frames_read) {
810 //                              cerr << "sample = " << buf[n] << " max = " << xmax << " min = " << xmin << " max of 2 = " << max (xmax, buf[n]) << endl;
811 //                      }
812                 }
813
814                 peakbuf[peaki].max = xmax;
815                 peakbuf[peaki].min = xmin;
816                 peaki++;
817
818                 current_frame += frames_read;
819                 cnt -= frames_read;
820         }
821
822         if (::pwrite (peakfile, peakbuf, sizeof (PeakData) * peaki, first_peak_byte) != (ssize_t) (sizeof (PeakData) * peaki)) {
823                 error << string_compose(_("%1: could not write peak file data (%2)"), _name, strerror (errno)) << endmsg;
824                 goto out;
825         }
826
827         ret = 0;
828
829   out:
830         delete [] peakbuf;
831         if (peakfile >= 0) {
832                 close (peakfile);
833         }
834         if (workbuf)
835                 delete [] workbuf;
836         return ret;
837 }
838
839 void
840 AudioSource::build_peaks_from_scratch ()
841 {
842         Glib::Mutex::Lock lp (_lock);
843
844         next_peak_clear_should_notify = true;
845         pending_peak_builds.push_back (new PeakBuildRecord (0, _length));
846         queue_for_peaks (*this);
847 }
848
849 bool
850 AudioSource::file_changed (string path)
851 {
852         struct stat stat_file;
853         struct stat stat_peak;
854
855         int e1 = stat (path.c_str(), &stat_file);
856         int e2 = stat (peak_path(path).c_str(), &stat_peak);
857         
858         if (!e1 && !e2 && stat_file.st_mtime > stat_peak.st_mtime){
859                 return true;
860         } else {
861                 return false;
862         }
863 }
864
865 jack_nframes_t
866 AudioSource::available_peaks (double zoom_factor) const
867 {
868         int peakfile;
869         off_t end;
870
871         if (zoom_factor < frames_per_peak) {
872                 return length(); // peak data will come from the audio file
873         } 
874         
875         /* peak data comes from peakfile */
876
877         if ((peakfile = ::open (peakpath.c_str(), O_RDONLY)) < 0) {
878                 error << string_compose(_("AudioSource: cannot open peakpath \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
879                 return 0;
880         }
881
882         { 
883                 Glib::Mutex::Lock lm (_lock);
884                 end = lseek (peakfile, 0, SEEK_END);
885         }
886
887         close (peakfile);
888
889         return (end/sizeof(PeakData)) * frames_per_peak;
890 }
891
892 void
893 AudioSource::update_length (jack_nframes_t pos, jack_nframes_t cnt)
894 {
895         if (pos + cnt > _length) {
896                 _length = pos+cnt;
897         }
898 }
899