more solo model work, including a GUI fix for mute button state when the route is...
[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 */
19
20 #include <sys/stat.h>
21 #include <unistd.h>
22 #include <fcntl.h>
23 #include <poll.h>
24 #include <float.h>
25 #include <utime.h>
26 #include <cerrno>
27 #include <ctime>
28 #include <cmath>
29 #include <iomanip>
30 #include <fstream>
31 #include <algorithm>
32 #include <vector>
33
34 #include <glibmm/fileutils.h>
35 #include <glibmm/miscutils.h>
36
37 #include "pbd/xml++.h"
38 #include "pbd/pthread_utils.h"
39
40 #include "ardour/audiosource.h"
41 #include "ardour/cycle_timer.h"
42 #include "ardour/session.h"
43 #include "ardour/transient_detector.h"
44 #include "ardour/runtime_functions.h"
45
46 #include "i18n.h"
47
48 using namespace std;
49 using namespace ARDOUR;
50 using namespace PBD;
51 using Glib::ustring;
52
53 bool AudioSource::_build_missing_peakfiles = false;
54
55 /** true if we want peakfiles (e.g. if we are displaying a GUI) */
56 bool AudioSource::_build_peakfiles = false;
57
58 #define _FPP 256
59
60 AudioSource::AudioSource (Session& s, ustring name)
61         : Source (s, DataType::AUDIO, name)
62         , _length (0)
63 {
64         _peaks_built = false;
65         _peak_byte_max = 0;
66         peakfile = -1;
67         _read_data_count = 0;
68         _write_data_count = 0;
69         peak_leftover_cnt = 0;
70         peak_leftover_size = 0;
71         peak_leftovers = 0;
72 }
73
74 AudioSource::AudioSource (Session& s, const XMLNode& node)
75         : Source (s, node)
76         , _length (0)
77 {
78
79         _peaks_built = false;
80         _peak_byte_max = 0;
81         peakfile = -1;
82         _read_data_count = 0;
83         _write_data_count = 0;
84         peak_leftover_cnt = 0;
85         peak_leftover_size = 0;
86         peak_leftovers = 0;
87
88         if (set_state (node, Stateful::loading_state_version)) {
89                 throw failed_constructor();
90         }
91 }
92
93 AudioSource::~AudioSource ()
94 {
95         /* shouldn't happen but make sure we don't leak file descriptors anyway */
96
97         if (peak_leftover_cnt) {
98                 cerr << "AudioSource destroyed with leftover peak data pending" << endl;
99         }
100
101         if (peakfile >= 0) {
102                 ::close (peakfile);
103         }
104
105         delete [] peak_leftovers;
106 }
107
108 XMLNode&
109 AudioSource::get_state ()
110 {
111         XMLNode& node (Source::get_state());
112
113         if (_captured_for.length()) {
114                 node.add_property ("captured-for", _captured_for);
115         }
116
117         return node;
118 }
119
120 int
121 AudioSource::set_state (const XMLNode& node, int /*version*/)
122 {
123         const XMLProperty* prop;
124
125         if ((prop = node.property ("captured-for")) != 0) {
126                 _captured_for = prop->value();
127         }
128
129         return 0;
130 }
131
132 sframes_t
133 AudioSource::length (sframes_t /*pos*/) const
134 {
135         return _length;
136 }
137
138 void
139 AudioSource::update_length (sframes_t pos, sframes_t cnt)
140 {
141         if (pos + cnt > _length) {
142                 _length = pos + cnt;
143         }
144 }
145
146
147 /***********************************************************************
148   PEAK FILE STUFF
149  ***********************************************************************/
150
151 /** Checks to see if peaks are ready.  If so, we return true.  If not, we return false, and
152  *  things are set up so that doThisWhenReady is called when the peaks are ready.
153  *  A new PBD::ScopedConnection is created for the associated connection and written to
154  *  *connect_here_if_not.
155  *
156  *  @param doThisWhenReady Function to call when peaks are ready (if they are not already).
157  *  @param connect_here_if_not Address to write new ScopedConnection to.
158  *  @param event_loop Event loop for doThisWhenReady to be called in.
159  */
160 bool
161 AudioSource::peaks_ready (boost::function<void()> doThisWhenReady, ScopedConnection** connect_here_if_not, EventLoop* event_loop) const
162 {
163         bool ret;
164         Glib::Mutex::Lock lm (_peaks_ready_lock);
165
166         /* check to see if the peak data is ready. if not
167            connect the slot while still holding the lock.
168         */
169
170         if (!(ret = _peaks_built)) {
171                 *connect_here_if_not = new ScopedConnection;
172                 PeaksReady.connect (**connect_here_if_not, MISSING_INVALIDATOR, doThisWhenReady, event_loop);
173         }
174
175         return ret;
176 }
177
178 void
179 AudioSource::touch_peakfile ()
180 {
181         struct stat statbuf;
182
183         if (stat (peakpath.c_str(), &statbuf) != 0 || statbuf.st_size == 0) {
184                 return;
185         }
186
187         struct utimbuf tbuf;
188
189         tbuf.actime = statbuf.st_atime;
190         tbuf.modtime = time ((time_t) 0);
191
192         utime (peakpath.c_str(), &tbuf);
193 }
194
195 int
196 AudioSource::rename_peakfile (ustring newpath)
197 {
198         /* caller must hold _lock */
199
200         ustring oldpath = peakpath;
201
202         if (access (oldpath.c_str(), F_OK) == 0) {
203                 if (rename (oldpath.c_str(), newpath.c_str()) != 0) {
204                         error << string_compose (_("cannot rename peakfile for %1 from %2 to %3 (%4)"), _name, oldpath, newpath, strerror (errno)) << endmsg;
205                         return -1;
206                 }
207         }
208
209         peakpath = newpath;
210
211         return 0;
212 }
213
214 int
215 AudioSource::initialize_peakfile (bool newfile, ustring audio_path)
216 {
217         struct stat statbuf;
218
219         peakpath = peak_path (audio_path);
220
221         /* if the peak file should be there, but isn't .... */
222
223         if (!newfile && !Glib::file_test (peakpath.c_str(), Glib::FILE_TEST_EXISTS)) {
224                 peakpath = find_broken_peakfile (peakpath, audio_path);
225         }
226
227         if (stat (peakpath.c_str(), &statbuf)) {
228                 if (errno != ENOENT) {
229                         /* it exists in the peaks dir, but there is some kind of error */
230
231                         error << string_compose(_("AudioSource: cannot stat peakfile \"%1\""), peakpath) << endmsg;
232                         return -1;
233                 }
234
235                 /* peakfile does not exist */
236
237                 _peaks_built = false;
238
239         } else {
240
241                 /* we found it in the peaks dir, so check it out */
242
243                 if (statbuf.st_size == 0 || ((nframes_t) statbuf.st_size < ((length(_timeline_position) / _FPP) * sizeof (PeakData)))) {
244                         // empty
245                         _peaks_built = false;
246                 } else {
247                         // Check if the audio file has changed since the peakfile was built.
248                         struct stat stat_file;
249                         int err = stat (audio_path.c_str(), &stat_file);
250
251                         if (err) {
252                                 _peaks_built = false;
253                                 _peak_byte_max = 0;
254                         } else {
255
256                                 /* allow 6 seconds slop on checking peak vs. file times because of various
257                                    disk action "races"
258                                 */
259
260                                 if (stat_file.st_mtime > statbuf.st_mtime && (stat_file.st_mtime - statbuf.st_mtime > 6)) {
261                                         _peaks_built = false;
262                                         _peak_byte_max = 0;
263                                 } else {
264                                         _peaks_built = true;
265                                         _peak_byte_max = statbuf.st_size;
266                                 }
267                         }
268                 }
269         }
270
271         if (!newfile && !_peaks_built && _build_missing_peakfiles && _build_peakfiles) {
272                 build_peaks_from_scratch ();
273         }
274
275         return 0;
276 }
277
278 framecnt_t
279 AudioSource::read (Sample *dst, framepos_t start, framecnt_t cnt, int /*channel*/) const
280 {
281         Glib::Mutex::Lock lm (_lock);
282         return read_unlocked (dst, start, cnt);
283 }
284
285 framecnt_t
286 AudioSource::write (Sample *dst, framecnt_t cnt)
287 {
288         Glib::Mutex::Lock lm (_lock);
289         /* any write makes the fill not removable */
290         _flags = Flag (_flags & ~Removable);
291         return write_unlocked (dst, cnt);
292 }
293
294 int
295 AudioSource::read_peaks (PeakData *peaks, framecnt_t npeaks, framepos_t start, framecnt_t cnt, double samples_per_visual_peak) const
296 {
297         return read_peaks_with_fpp (peaks, npeaks, start, cnt, samples_per_visual_peak, _FPP);
298 }
299
300 /** @param peaks Buffer to write peak data.
301  *  @param npeaks Number of peaks to write.
302  */
303
304 int
305 AudioSource::read_peaks_with_fpp (PeakData *peaks, framecnt_t npeaks, framepos_t start, framecnt_t cnt,
306                                   double samples_per_visual_peak, framecnt_t samples_per_file_peak) const
307 {
308         Glib::Mutex::Lock lm (_lock);
309         double scale;
310         double expected_peaks;
311         PeakData::PeakDatum xmax;
312         PeakData::PeakDatum xmin;
313         int32_t to_read;
314         uint32_t nread;
315         framecnt_t zero_fill = 0;
316         int ret = -1;
317         PeakData* staging = 0;
318         Sample* raw_staging = 0;
319         int _peakfile = -1;
320
321         expected_peaks = (cnt / (double) samples_per_file_peak);
322         scale = npeaks/expected_peaks;
323
324 #undef DEBUG_READ_PEAKS
325 #ifdef DEBUG_READ_PEAKS
326         cerr << "======>RP: npeaks = " << npeaks
327              << " start = " << start
328              << " cnt = " << cnt
329              << " len = " << _length
330              << "   samples_per_visual_peak =" << samples_per_visual_peak
331              << " expected was " << expected_peaks << " ... scale = " << scale
332              << " PD ptr = " << peaks
333              <<endl;
334
335 #endif
336
337         /* fix for near-end-of-file conditions */
338
339         if (cnt > _length - start) {
340                 // cerr << "too close to end @ " << _length << " given " << start << " + " << cnt << endl;
341                 cnt = _length - start;
342                 framecnt_t old = npeaks;
343                 npeaks = min ((framecnt_t) floor (cnt / samples_per_visual_peak), npeaks);
344                 zero_fill = old - npeaks;
345         }
346
347         // cerr << "actual npeaks = " << npeaks << " zf = " << zero_fill << endl;
348
349         if (npeaks == cnt) {
350
351 #ifdef DEBUG_READ_PEAKS
352                 cerr << "RAW DATA\n";
353 #endif
354                 /* no scaling at all, just get the sample data and duplicate it for
355                    both max and min peak values.
356                 */
357
358                 Sample* raw_staging = new Sample[cnt];
359
360                 if (read_unlocked (raw_staging, start, cnt) != cnt) {
361                         error << _("cannot read sample data for unscaled peak computation") << endmsg;
362                         return -1;
363                 }
364
365                 for (framecnt_t i = 0; i < npeaks; ++i) {
366                         peaks[i].max = raw_staging[i];
367                         peaks[i].min = raw_staging[i];
368                 }
369
370                 delete [] raw_staging;
371                 return 0;
372         }
373
374         if (scale == 1.0) {
375
376                 off_t first_peak_byte = (start / samples_per_file_peak) * sizeof (PeakData);
377
378                 /* open, read, close */
379
380                 if ((_peakfile = ::open (peakpath.c_str(), O_RDONLY, 0664)) < 0) {
381                         error << string_compose(_("AudioSource: cannot open peakpath (a) \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
382                         return -1;
383                 }
384
385 #ifdef DEBUG_READ_PEAKS
386                 cerr << "DIRECT PEAKS\n";
387 #endif
388
389                 nread = ::pread (_peakfile, peaks, sizeof (PeakData)* npeaks, first_peak_byte);
390                 close (_peakfile);
391
392                 if (nread != sizeof (PeakData) * npeaks) {
393                         cerr << "AudioSource["
394                              << _name
395                              << "]: cannot read peaks from peakfile! (read only "
396                              << nread
397                              << " not "
398                              << npeaks
399                               << "at sample "
400                              << start
401                              << " = byte "
402                              << first_peak_byte
403                              << ')'
404                              << endl;
405                         return -1;
406                 }
407
408                 if (zero_fill) {
409                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
410                 }
411
412                 return 0;
413         }
414
415
416         framecnt_t tnp;
417
418         if (scale < 1.0) {
419
420 #ifdef DEBUG_READ_PEAKS
421                 cerr << "DOWNSAMPLE\n";
422 #endif
423                 /* the caller wants:
424
425                     - more frames-per-peak (lower resolution) than the peakfile, or to put it another way,
426                     - less peaks than the peakfile holds for the same range
427
428                     So, read a block into a staging area, and then downsample from there.
429
430                     to avoid confusion, I'll refer to the requested peaks as visual_peaks and the peakfile peaks as stored_peaks
431                 */
432
433                 const framecnt_t chunksize = (framecnt_t) min (expected_peaks, 65536.0);
434                 
435                 staging = new PeakData[chunksize];
436
437                 /* compute the rounded up frame position  */
438
439                 framepos_t current_frame = start;
440                 framepos_t current_stored_peak = (framepos_t) ceil (current_frame / (double) samples_per_file_peak);
441                 framepos_t next_visual_peak  = (framepos_t) ceil (current_frame / samples_per_visual_peak);
442                 double     next_visual_peak_frame = next_visual_peak * samples_per_visual_peak;
443                 framepos_t stored_peak_before_next_visual_peak = (framepos_t) next_visual_peak_frame / samples_per_file_peak;
444                 framecnt_t nvisual_peaks = 0;
445                 framecnt_t stored_peaks_read = 0;
446                 framecnt_t i = 0;
447
448                 /* handle the case where the initial visual peak is on a pixel boundary */
449
450                 current_stored_peak = min (current_stored_peak, stored_peak_before_next_visual_peak);
451
452                 /* open ... close during out: handling */
453
454                 if ((_peakfile = ::open (peakpath.c_str(), O_RDONLY, 0664)) < 0) {
455                         error << string_compose(_("AudioSource: cannot open peakpath (b) \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
456                         delete [] staging;
457                         return 0;
458                 }
459
460                 while (nvisual_peaks < npeaks) {
461
462                         if (i == stored_peaks_read) {
463
464                                 uint32_t       start_byte = current_stored_peak * sizeof(PeakData);
465                                 tnp = min ((framecnt_t)(_length/samples_per_file_peak - current_stored_peak), (framecnt_t) expected_peaks);
466                                 to_read = min (chunksize, tnp);
467
468 #ifdef DEBUG_READ_PEAKS
469                                 cerr << "read " << sizeof (PeakData) * to_read << " from peakfile @ " << start_byte << endl;
470 #endif
471
472                                 if ((nread = ::pread (_peakfile, staging, sizeof (PeakData) * to_read, start_byte))
473                                     != sizeof (PeakData) * to_read) {
474
475                                         off_t fend = lseek (_peakfile, 0, SEEK_END);
476
477                                         cerr << "AudioSource["
478                                              << _name
479                                              << "]: cannot read peak data from peakfile ("
480                                              << (nread / sizeof(PeakData))
481                                              << " peaks instead of "
482                                              << to_read
483                                              << ") ("
484                                              << strerror (errno)
485                                              << ')'
486                                              << " at start_byte = " << start_byte
487                                              << " _length = " << _length << " versus len = " << fend
488                                              << " expected maxpeaks = " << (_length - current_frame)/samples_per_file_peak
489                                              << " npeaks was " << npeaks
490                                              << endl;
491                                         goto out;
492                                 }
493
494                                 i = 0;
495                                 stored_peaks_read = nread / sizeof(PeakData);
496                         }
497
498                         xmax = -1.0;
499                         xmin = 1.0;
500
501                         while ((i < stored_peaks_read) && (current_stored_peak <= stored_peak_before_next_visual_peak)) {
502
503                                 xmax = max (xmax, staging[i].max);
504                                 xmin = min (xmin, staging[i].min);
505                                 ++i;
506                                 ++current_stored_peak;
507                                 --expected_peaks;
508                         }
509
510                         peaks[nvisual_peaks].max = xmax;
511                         peaks[nvisual_peaks].min = xmin;
512                         ++nvisual_peaks;
513                         ++next_visual_peak;
514
515                         //next_visual_peak_frame = min ((next_visual_peak * samples_per_visual_peak), (next_visual_peak_frame+samples_per_visual_peak) );
516                         next_visual_peak_frame =  min ((double) start+cnt, (next_visual_peak_frame+samples_per_visual_peak) );
517                         stored_peak_before_next_visual_peak = (uint32_t) next_visual_peak_frame / samples_per_file_peak;
518                 }
519
520                 if (zero_fill) {
521                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
522                 }
523
524                 ret = 0;
525
526         } else {
527
528 #ifdef DEBUG_READ_PEAKS
529                 cerr << "UPSAMPLE\n";
530 #endif
531                 /* the caller wants
532
533                      - less frames-per-peak (more resolution)
534                      - more peaks than stored in the Peakfile
535
536                    So, fetch data from the raw source, and generate peak
537                    data on the fly.
538                 */
539
540                 framecnt_t frames_read = 0;
541                 framepos_t current_frame = start;
542                 framecnt_t i = 0;
543                 framecnt_t nvisual_peaks = 0;
544                 framecnt_t chunksize = (framecnt_t) min (cnt, (framecnt_t) 4096);
545                 raw_staging = new Sample[chunksize];
546
547                 framepos_t frame_pos = start;
548                 double pixel_pos = floor (frame_pos / samples_per_visual_peak);
549                 double next_pixel_pos = ceil (frame_pos / samples_per_visual_peak);
550                 double pixels_per_frame = 1.0 / samples_per_visual_peak;
551
552                 xmin = 1.0;
553                 xmax = -1.0;
554
555                 while (nvisual_peaks < npeaks) {
556
557                         if (i == frames_read) {
558
559                                 to_read = min (chunksize, (framecnt_t)(_length - current_frame));
560
561                                 if (current_frame >= _length) {
562
563                                         /* hmm, error condition - we've reached the end of the file
564                                            without generating all the peak data. cook up a zero-filled
565                                            data buffer and then use it. this is simpler than
566                                            adjusting zero_fill and npeaks and then breaking out of
567                                            this loop early
568                                         */
569                                         
570                                         memset (raw_staging, 0, sizeof (Sample) * chunksize);
571                                         
572                                 } else {
573                                         
574                                         to_read = min (chunksize, (_length - current_frame));
575                                         
576                                         
577                                         if ((frames_read = read_unlocked (raw_staging, current_frame, to_read)) == 0) {
578                                                 error << string_compose(_("AudioSource[%1]: peak read - cannot read %2 samples at offset %3 of %4 (%5)"),
579                                                                         _name, to_read, current_frame, _length, strerror (errno))
580                                                       << endmsg;
581                                                 goto out;
582                                         }
583                                 }
584                                 
585                                 i = 0;
586                         }
587
588                         xmax = max (xmax, raw_staging[i]);
589                         xmin = min (xmin, raw_staging[i]);
590                         ++i;
591                         ++current_frame;
592                         pixel_pos += pixels_per_frame;
593
594                         if (pixel_pos >= next_pixel_pos) {
595
596                                 peaks[nvisual_peaks].max = xmax;
597                                 peaks[nvisual_peaks].min = xmin;
598                                 ++nvisual_peaks;
599                                 xmin = 1.0;
600                                 xmax = -1.0;
601
602                                 next_pixel_pos = ceil (pixel_pos + 0.5);
603                         }
604                 }
605
606                 if (zero_fill) {
607                         memset (&peaks[npeaks], 0, sizeof (PeakData) * zero_fill);
608                 }
609
610                 ret = 0;
611         }
612
613   out:
614         if (_peakfile >= 0) {
615                 close (_peakfile);
616         }
617
618         delete [] staging;
619         delete [] raw_staging;
620
621 #ifdef DEBUG_READ_PEAKS
622         cerr << "RP DONE\n";
623 #endif
624
625         return ret;
626 }
627
628 #undef DEBUG_PEAK_BUILD
629
630 int
631 AudioSource::build_peaks_from_scratch ()
632 {
633         Sample* buf = 0;
634
635         const framecnt_t bufsize = 65536; // 256kB per disk read for mono data is about ideal
636
637         int ret = -1;
638
639         {
640                 /* hold lock while building peaks */
641
642                 Glib::Mutex::Lock lp (_lock);
643
644                 if (prepare_for_peakfile_writes ()) {
645                         goto out;
646                 }
647
648                 framepos_t current_frame = 0;
649                 framecnt_t cnt = _length;
650
651                 _peaks_built = false;
652                 buf = new Sample[bufsize];
653
654                 while (cnt) {
655
656                         framecnt_t frames_to_read = min (bufsize, cnt);
657                         framecnt_t frames_read;
658
659                         if ((frames_read = read_unlocked (buf, current_frame, frames_to_read)) != frames_to_read) {
660                                 error << string_compose(_("%1: could not write read raw data for peak computation (%2)"), _name, strerror (errno)) << endmsg;
661                                 done_with_peakfile_writes (false);
662                                 goto out;
663                         }
664
665                         if (compute_and_write_peaks (buf, current_frame, frames_read, true, false, _FPP)) {
666                                 break;
667                         }
668
669                         current_frame += frames_read;
670                         cnt -= frames_read;
671                 }
672
673                 if (cnt == 0) {
674                         /* success */
675                         truncate_peakfile();
676                 }
677
678                 done_with_peakfile_writes ((cnt == 0));
679         }
680
681         {
682                 Glib::Mutex::Lock lm (_peaks_ready_lock);
683
684                 if (_peaks_built) {
685                         PeaksReady (); /* EMIT SIGNAL */
686                         ret = 0;
687                 }
688         }
689
690   out:
691         if (ret) {
692                 unlink (peakpath.c_str());
693         }
694
695         delete [] buf;
696
697         return ret;
698 }
699
700 int
701 AudioSource::prepare_for_peakfile_writes ()
702 {
703         if ((peakfile = ::open (peakpath.c_str(), O_RDWR|O_CREAT, 0664)) < 0) {
704                 error << string_compose(_("AudioSource: cannot open peakpath (c) \"%1\" (%2)"), peakpath, strerror (errno)) << endmsg;
705                 return -1;
706         }
707         return 0;
708 }
709
710 void
711 AudioSource::done_with_peakfile_writes (bool done)
712 {
713         if (peak_leftover_cnt) {
714                 compute_and_write_peaks (0, 0, 0, true, false, _FPP);
715         }
716
717         if (done) {
718                 _peaks_built = true;
719         }
720
721         if (peakfile >= 0) {
722                 close (peakfile);
723                 peakfile = -1;
724         }
725 }
726
727 int
728 AudioSource::compute_and_write_peaks (Sample* buf, framepos_t first_frame, framecnt_t cnt,
729                                       bool force, bool intermediate_peaks_ready)
730 {
731         return compute_and_write_peaks (buf, first_frame, cnt, force, intermediate_peaks_ready, _FPP);
732 }
733
734 int
735 AudioSource::compute_and_write_peaks (Sample* buf, framepos_t first_frame, framecnt_t cnt,
736                                       bool force, bool intermediate_peaks_ready, framecnt_t fpp)
737 {
738         Sample* buf2 = 0;
739         framecnt_t to_do;
740         uint32_t  peaks_computed;
741         PeakData* peakbuf = 0;
742         int ret = -1;
743         framepos_t current_frame;
744         framecnt_t frames_done;
745         const size_t blocksize = (128 * 1024);
746         off_t first_peak_byte;
747
748         if (peakfile < 0) {
749                 prepare_for_peakfile_writes ();
750         }
751
752   restart:
753         if (peak_leftover_cnt) {
754
755                 if (first_frame != peak_leftover_frame + peak_leftover_cnt) {
756
757                         /* uh-oh, ::seek() since the last ::compute_and_write_peaks(),
758                            and we have leftovers. flush a single peak (since the leftovers
759                            never represent more than that, and restart.
760                         */
761
762                         PeakData x;
763
764                         x.min = peak_leftovers[0];
765                         x.max = peak_leftovers[0];
766
767                         off_t byte = (peak_leftover_frame / fpp) * sizeof (PeakData);
768
769                         if (::pwrite (peakfile, &x, sizeof (PeakData), byte) != sizeof (PeakData)) {
770                                 error << string_compose(_("%1: could not write peak file data (%2)"), _name, strerror (errno)) << endmsg;
771                                 goto out;
772                         }
773
774                         _peak_byte_max = max (_peak_byte_max, (off_t) (byte + sizeof(PeakData)));
775
776                         {
777                                 Glib::Mutex::Lock lm (_peaks_ready_lock);
778                                 PeakRangeReady (peak_leftover_frame, peak_leftover_cnt); /* EMIT SIGNAL */
779                                 if (intermediate_peaks_ready) {
780                                         PeaksReady (); /* EMIT SIGNAL */
781                                 }
782                         }
783
784                         /* left overs are done */
785
786                         peak_leftover_cnt = 0;
787                         goto restart;
788                 }
789
790                 /* else ... had leftovers, but they immediately preceed the new data, so just
791                    merge them and compute.
792                 */
793
794                 /* make a new contiguous buffer containing leftovers and the new stuff */
795
796                 to_do = cnt + peak_leftover_cnt;
797                 buf2 = new Sample[to_do];
798
799                 /* the remnants */
800                 memcpy (buf2, peak_leftovers, peak_leftover_cnt * sizeof (Sample));
801
802                 /* the new stuff */
803                 memcpy (buf2+peak_leftover_cnt, buf, cnt * sizeof (Sample));
804
805                 /* no more leftovers */
806                 peak_leftover_cnt = 0;
807
808                 /* use the temporary buffer */
809                 buf = buf2;
810
811                 /* make sure that when we write into the peakfile, we startup where we left off */
812
813                 first_frame = peak_leftover_frame;
814
815         } else {
816                 to_do = cnt;
817         }
818
819         peakbuf = new PeakData[(to_do/fpp)+1];
820         peaks_computed = 0;
821         current_frame = first_frame;
822         frames_done = 0;
823
824         while (to_do) {
825
826                 /* if some frames were passed in (i.e. we're not flushing leftovers)
827                    and there are less than fpp to do, save them till
828                    next time
829                 */
830
831                 if (force && (to_do < fpp)) {
832                         /* keep the left overs around for next time */
833
834                         if (peak_leftover_size < to_do) {
835                                 delete [] peak_leftovers;
836                                 peak_leftovers = new Sample[to_do];
837                                 peak_leftover_size = to_do;
838                         }
839                         memcpy (peak_leftovers, buf, to_do * sizeof (Sample));
840                         peak_leftover_cnt = to_do;
841                         peak_leftover_frame = current_frame;
842
843                         /* done for now */
844
845                         break;
846                 }
847
848                 framecnt_t this_time = min (fpp, to_do);
849
850                 peakbuf[peaks_computed].max = buf[0];
851                 peakbuf[peaks_computed].min = buf[0];
852
853                 ARDOUR::find_peaks (buf+1, this_time-1, &peakbuf[peaks_computed].min, &peakbuf[peaks_computed].max);
854
855                 peaks_computed++;
856                 buf += this_time;
857                 to_do -= this_time;
858                 frames_done += this_time;
859                 current_frame += this_time;
860         }
861
862         first_peak_byte = (first_frame / fpp) * sizeof (PeakData);
863
864         if (can_truncate_peaks()) {
865
866                 /* on some filesystems (ext3, at least) this helps to reduce fragmentation of
867                    the peakfiles. its not guaranteed to do so, and even on ext3 (as of december 2006)
868                    it does not cause single-extent allocation even for peakfiles of
869                    less than BLOCKSIZE bytes.  only call ftruncate if we'll make the file larger.
870                 */
871
872                 off_t endpos = lseek (peakfile, 0, SEEK_END);
873                 off_t target_length = blocksize * ((first_peak_byte + blocksize + 1) / blocksize);
874
875                 if (endpos < target_length) {
876                         ftruncate (peakfile, target_length);
877                         /* error doesn't actually matter though, so continue on without testing */
878                 }
879         }
880
881         if (::pwrite (peakfile, peakbuf, sizeof (PeakData) * peaks_computed, first_peak_byte) != (ssize_t) (sizeof (PeakData) * peaks_computed)) {
882                 error << string_compose(_("%1: could not write peak file data (%2)"), _name, strerror (errno)) << endmsg;
883                 goto out;
884         }
885
886         _peak_byte_max = max (_peak_byte_max, (off_t) (first_peak_byte + sizeof(PeakData)*peaks_computed));
887
888         if (frames_done) {
889                 Glib::Mutex::Lock lm (_peaks_ready_lock);
890                 PeakRangeReady (first_frame, frames_done); /* EMIT SIGNAL */
891                 if (intermediate_peaks_ready) {
892                         PeaksReady (); /* EMIT SIGNAL */
893                 }
894         }
895
896         ret = 0;
897
898   out:
899         delete [] peakbuf;
900         delete [] buf2;
901
902         return ret;
903 }
904
905 void
906 AudioSource::truncate_peakfile ()
907 {
908         if (peakfile < 0) {
909                 error << string_compose (_("programming error: %1"), "AudioSource::truncate_peakfile() called without open peakfile descriptor")
910                       << endmsg;
911                 return;
912         }
913
914         /* truncate the peakfile down to its natural length if necessary */
915
916         off_t end = lseek (peakfile, 0, SEEK_END);
917
918         if (end > _peak_byte_max) {
919                 ftruncate (peakfile, _peak_byte_max);
920         }
921 }
922
923 framecnt_t
924 AudioSource::available_peaks (double zoom_factor) const
925 {
926         if (zoom_factor < _FPP) {
927                 return length(_timeline_position); // peak data will come from the audio file
928         }
929
930         /* peak data comes from peakfile, but the filesize might not represent
931            the valid data due to ftruncate optimizations, so use _peak_byte_max state.
932            XXX - there might be some atomicity issues here, we should probably add a lock,
933            but _peak_byte_max only monotonically increases after initialization.
934         */
935
936         off_t end = _peak_byte_max;
937
938         return (end/sizeof(PeakData)) * _FPP;
939 }
940