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