8fda5ff0aa9bf99657bb1a26c22e532edaf761f1
[ardour.git] / libs / canvas / wave_view.cc
1 /*
2     Copyright (C) 2011-2013 Paul Davis
3     Author: Carl Hetherington <cth@carlh.net>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <cmath>
22 #include <cairomm/cairomm.h>
23
24 #include "gtkmm2ext/utils.h"
25
26 #include "pbd/compose.h"
27 #include "pbd/signals.h"
28 #include "pbd/stacktrace.h"
29
30 #include "ardour/types.h"
31 #include "ardour/dB.h"
32 #include "ardour/lmath.h"
33 #include "ardour/audioregion.h"
34
35 #include "canvas/wave_view.h"
36 #include "canvas/utils.h"
37 #include "canvas/canvas.h"
38 #include "canvas/colors.h"
39
40 #include <gdkmm/general.h>
41
42 #include "gtkmm2ext/gui_thread.h"
43
44 using namespace std;
45 using namespace ARDOUR;
46 using namespace ArdourCanvas;
47
48 #define CACHE_HIGH_WATER (2)
49
50 std::map <boost::shared_ptr<AudioSource>, std::vector<WaveView::CacheEntry> >  WaveView::_image_cache;
51 double WaveView::_global_gradient_depth = 0.6;
52 bool WaveView::_global_logscaled = false;
53 WaveView::Shape WaveView::_global_shape = WaveView::Normal;
54 bool WaveView::_global_show_waveform_clipping = true;
55 double WaveView::_clip_level = 0.98853;
56
57 PBD::Signal0<void> WaveView::VisualPropertiesChanged;
58 PBD::Signal0<void> WaveView::ClipLevelChanged;
59
60 WaveView::WaveView (Canvas* c, boost::shared_ptr<ARDOUR::AudioRegion> region)
61         : Item (c)
62         , _region (region)
63         , _channel (0)
64         , _samples_per_pixel (0)
65         , _height (64)
66         , _show_zero (false)
67         , _zero_color (0xff0000ff)
68         , _clip_color (0xff0000ff)
69         , _logscaled (_global_logscaled)
70         , _shape (_global_shape)
71         , _gradient_depth (_global_gradient_depth)
72         , _shape_independent (false)
73         , _logscaled_independent (false)
74         , _gradient_depth_independent (false)
75         , _amplitude_above_axis (1.0)
76         , _region_amplitude (_region->scale_amplitude ())
77         , _start_shift (0.0)
78         , _region_start (region->start())
79 {
80         _region->DropReferences.connect (_source_invalidated_connection, MISSING_INVALIDATOR,
81                                                      boost::bind (&ArdourCanvas::WaveView::invalidate_source,
82                                                                   this, boost::weak_ptr<AudioSource>(_region->audio_source())), gui_context());
83
84         VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
85         ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
86 }
87
88 WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
89         : Item (parent)
90         , _region (region)
91         , _channel (0)
92         , _samples_per_pixel (0)
93         , _height (64)
94         , _show_zero (false)
95         , _zero_color (0xff0000ff)
96         , _clip_color (0xff0000ff)
97         , _logscaled (_global_logscaled)
98         , _shape (_global_shape)
99         , _gradient_depth (_global_gradient_depth)
100         , _shape_independent (false)
101         , _logscaled_independent (false)
102         , _gradient_depth_independent (false)
103         , _amplitude_above_axis (1.0)
104         , _region_amplitude (_region->scale_amplitude ())
105         , _region_start (region->start())
106 {
107         _region->DropReferences.connect (_source_invalidated_connection, MISSING_INVALIDATOR,
108                                                      boost::bind (&ArdourCanvas::WaveView::invalidate_source,
109                                                                   this, boost::weak_ptr<AudioSource>(_region->audio_source())), gui_context());
110
111         VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
112         ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
113 }
114
115 WaveView::~WaveView ()
116 {
117         _source_invalidated_connection.disconnect();
118         invalidate_image_cache ();
119 }
120
121 void
122 WaveView::handle_visual_property_change ()
123 {
124         bool changed = false;
125
126         if (!_shape_independent && (_shape != global_shape())) {
127                 _shape = global_shape();
128                 changed = true;
129         }
130
131         if (!_logscaled_independent && (_logscaled != global_logscaled())) {
132                 _logscaled = global_logscaled();
133                 changed = true;
134         }
135
136         if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
137                 _gradient_depth = global_gradient_depth();
138                 changed = true;
139         }
140
141         if (changed) {
142                 begin_visual_change ();
143                 invalidate_image_cache ();
144                 end_visual_change ();
145         }
146 }
147
148 void
149 WaveView::handle_clip_level_change ()
150 {
151         begin_visual_change ();
152         invalidate_image_cache ();
153         end_visual_change ();
154 }
155
156 void
157 WaveView::set_fill_color (Color c)
158 {
159         if (c != _fill_color) {
160                 begin_visual_change ();
161                 invalidate_image_cache ();
162                 Fill::set_fill_color (c);
163                 end_visual_change ();
164         }
165 }
166
167 void
168 WaveView::set_outline_color (Color c)
169 {
170         if (c != _outline_color) {
171                 begin_visual_change ();
172                 invalidate_image_cache ();
173                 Outline::set_outline_color (c);
174                 end_visual_change ();
175         }
176 }
177
178 void
179 WaveView::set_samples_per_pixel (double samples_per_pixel)
180 {
181         if (samples_per_pixel != _samples_per_pixel) {
182                 begin_change ();
183
184                 invalidate_image_cache ();
185                 _samples_per_pixel = samples_per_pixel;
186                 _bounding_box_dirty = true;
187
188                 end_change ();
189         }
190 }
191
192 static inline double
193 window_to_image (double wave_origin, double image_start)
194 {
195         return image_start - wave_origin;
196 }
197
198 static inline float
199 _log_meter (float power, double lower_db, double upper_db, double non_linearity)
200 {
201         return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
202 }
203
204 static inline float
205 alt_log_meter (float power)
206 {
207         return _log_meter (power, -192.0, 0.0, 8.0);
208 }
209
210 void
211 WaveView::set_clip_level (double dB)
212 {
213         const double clip_level = dB_to_coefficient (dB);
214         if (clip_level != _clip_level) {
215                 _clip_level = clip_level;
216                 ClipLevelChanged ();
217         }
218 }
219
220 void
221 WaveView::invalidate_source (boost::weak_ptr<AudioSource> src)
222 {
223         if (boost::shared_ptr<AudioSource> source = src.lock()) {
224
225                 std::map <boost::shared_ptr<ARDOUR::AudioSource>, std::vector <CacheEntry> >::iterator i;
226                 for (i = _image_cache.begin (); i != _image_cache.end (); ++i) {
227                         if (i->first == source) {
228                                 for (uint32_t n = 0; n < i->second.size (); ++n) {
229                                         i->second[n].image.clear ();
230                                 }
231                                 i->second.clear ();
232                                 _image_cache.erase (i->first);
233                         }
234                 }
235         }
236 }
237
238 void
239 WaveView::invalidate_image_cache ()
240 {
241         vector <uint32_t> deletion_list;
242         vector <CacheEntry> caches;
243
244         /* The source may have disappeared.*/
245
246         if (_region->n_channels() == 0) {
247                 return;
248         }
249
250         if (_image_cache.find (_region->audio_source ()) != _image_cache.end ()) {
251                 caches = _image_cache.find (_region->audio_source ())->second;
252         } else {
253                 return;
254         }
255
256         for (uint32_t i = 0; i < caches.size (); ++i) {
257
258                 if (_channel != caches[i].channel
259                     || _height != caches[i].height
260                     || _region_amplitude != caches[i].amplitude
261                     || _fill_color != caches[i].fill_color) {
262
263                         continue;
264                 }
265
266                 deletion_list.push_back (i);
267         }
268
269         while (deletion_list.size() > 0) {
270                 caches[deletion_list.back ()].image.clear ();
271                 caches.erase (caches.begin() + deletion_list.back());
272                 deletion_list.pop_back();
273         }
274
275         if (caches.size () == 0) {
276                 _image_cache.erase(_region->audio_source ());
277         } else {
278                 _image_cache[_region->audio_source ()] = caches;
279         }
280 }
281
282 void
283 WaveView::consolidate_image_cache () const
284 {
285         list <uint32_t> deletion_list;
286         vector <CacheEntry> caches;
287         uint32_t other_entries = 0;
288
289         if (_image_cache.find (_region->audio_source ()) != _image_cache.end ()) {
290                 caches  = _image_cache.find (_region->audio_source ())->second;
291         }
292
293         for (uint32_t i = 0; i < caches.size (); ++i) {
294
295                 if (_channel != caches[i].channel
296                     || _height != caches[i].height
297                     || _region_amplitude != caches[i].amplitude
298                     || _fill_color != caches[i].fill_color) {
299
300                         other_entries++;
301                         continue;
302                 }
303
304                 framepos_t segment_start = caches[i].start;
305                 framepos_t segment_end = caches[i].end;
306
307                 for (uint32_t j = i; j < caches.size (); ++j) {
308
309                         if (i == j || _channel != caches[j].channel
310                             || _height != caches[i].height
311                             || _region_amplitude != caches[i].amplitude
312                             || _fill_color != caches[i].fill_color) {
313
314                                 continue;
315                         }
316
317                         if (caches[j].start >= segment_start && caches[j].end <= segment_end) {
318
319                                 deletion_list.push_back (j);
320                         }
321                 }
322         }
323
324         deletion_list.sort ();
325         deletion_list.unique ();
326
327         while (deletion_list.size() > 0) {
328                 caches[deletion_list.back ()].image.clear ();
329                 caches.erase (caches.begin() + deletion_list.back ());
330                 deletion_list.pop_back();
331         }
332
333         /* We don't care if this channel/height/amplitude has anything in the cache - just drop the Last Added entries
334            until we reach a size where there is a maximum of CACHE_HIGH_WATER + other entries.
335         */
336
337         while (caches.size() > CACHE_HIGH_WATER + other_entries) {
338                 caches.front ().image.clear ();
339                 caches.erase(caches.begin ());
340         }
341
342         if (caches.size () == 0) {
343                 _image_cache.erase (_region->audio_source ());
344         } else {
345                 _image_cache[_region->audio_source ()] = caches;
346         }
347 }
348
349 Coord
350 WaveView::y_extent (double s, bool /*round_to_lower_edge*/) const
351 {
352         /* it is important that this returns an integral value, so that we
353          * can ensure correct single pixel behaviour.
354          *
355          * we need (_height - max(wave_line_width))
356          * wave_line_width == 1 IFF top==bottom (1 sample per pixel or flat line)
357          * wave_line_width == 2 otherwise
358          * then round away from the zero line, towards peak
359          */
360         if (_shape == Rectified) {
361                 // we only ever have 1 point and align to the bottom (not center)
362                 return floor ((1.0 - s) * (_height - 2.0));
363         } else {
364                 /* currently canvas rectangle is off-by-one and we
365                  * cannot draw a pixel at 0 (-.5 .. +.5) without it being
366                  * clipped. A value 1.0 (ideally one point at y=0) ends
367                  * up a pixel down. and a value of -1.0 (ideally y = _height-1)
368                  * currently is on the bottom separator line :(
369                  * So to make the complete waveform appear centered in
370                  * a region, we translate by +1.5 (instead of -.5)
371                  * and scale to height - 2.5 (if we scale to height - 2.0
372                  * then the bottom most pixel may bleed into the selection rect
373                  * by 0.5 px)
374                  *
375                  */
376                 Coord pos;
377                 pos = floor ((1.0 - s) * .5 * (_height - 2.5));
378
379                 return min (_height - 2.5, (max (0.0, pos)));
380         }
381 }
382
383 void
384 WaveView::draw_absent_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
385 {
386         Cairo::RefPtr<Cairo::ImageSurface> stripe = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
387
388         Cairo::RefPtr<Cairo::Context> stripe_context = Cairo::Context::create (stripe);
389         stripe_context->set_antialias (Cairo::ANTIALIAS_NONE);
390
391         uint32_t stripe_separation = 150;
392         double start = - floor (_height / stripe_separation) * stripe_separation;
393         int stripe_x = 0;
394
395         while (start < n_peaks) {
396
397                 stripe_context->move_to (start, 0);
398                 stripe_x = start + _height;
399                 stripe_context->line_to (stripe_x, _height);
400                 start += stripe_separation;
401         }
402
403         stripe_context->set_source_rgba (1.0, 1.0, 1.0, 1.0);
404         stripe_context->set_line_cap (Cairo::LINE_CAP_SQUARE);
405         stripe_context->set_line_width(50);
406         stripe_context->stroke();
407
408         Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
409
410         context->set_source_rgba (1.0, 1.0, 0.0, 0.3);
411         context->mask (stripe, 0, 0);
412         context->fill ();
413 }
414
415 struct LineTips {
416         double top;
417         double bot;
418         double spread;
419         bool clip_max;
420         bool clip_min;
421
422         LineTips() : top (0.0), bot (0.0), clip_max (false), clip_min (false) {}
423 };
424
425 struct ImageSet {
426         Cairo::RefPtr<Cairo::ImageSurface> wave;
427         Cairo::RefPtr<Cairo::ImageSurface> outline;
428         Cairo::RefPtr<Cairo::ImageSurface> clip;
429         Cairo::RefPtr<Cairo::ImageSurface> zero;
430
431         ImageSet() :
432                 wave (0), outline (0), clip (0), zero (0) {}
433 };
434
435 void
436 WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
437 {
438
439         ImageSet images;
440
441         images.wave = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
442         images.outline = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
443         images.clip = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
444         images.zero = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
445
446         Cairo::RefPtr<Cairo::Context> wave_context = Cairo::Context::create (images.wave);
447         Cairo::RefPtr<Cairo::Context> outline_context = Cairo::Context::create (images.outline);
448         Cairo::RefPtr<Cairo::Context> clip_context = Cairo::Context::create (images.clip);
449         Cairo::RefPtr<Cairo::Context> zero_context = Cairo::Context::create (images.zero);
450         wave_context->set_antialias (Cairo::ANTIALIAS_NONE);
451         outline_context->set_antialias (Cairo::ANTIALIAS_NONE);
452         clip_context->set_antialias (Cairo::ANTIALIAS_NONE);
453         zero_context->set_antialias (Cairo::ANTIALIAS_NONE);
454
455         boost::scoped_array<LineTips> tips (new LineTips[n_peaks]);
456
457         /* Clip level nominally set to -0.9dBFS to account for inter-sample
458            interpolation possibly clipping (value may be too low).
459
460            We adjust by the region's own gain (but note: not by any gain
461            automation or its gain envelope) so that clip indicators are closer
462            to providing data about on-disk data. This multiplication is
463            needed because the data we get from AudioRegion::read_peaks()
464            has been scaled by scale_amplitude() already.
465         */
466
467         const double clip_level = _clip_level * _region_amplitude;
468
469         if (_shape == WaveView::Rectified) {
470
471                 /* each peak is a line from the bottom of the waveview
472                  * to a point determined by max (_peaks[i].max,
473                  * _peaks[i].min)
474                  */
475
476                 if (_logscaled) {
477                         for (int i = 0; i < n_peaks; ++i) {
478
479                                 tips[i].bot = height() - 1.0;
480                                 const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
481                                 tips[i].top = y_extent (p, false);
482                                 tips[i].spread = p * (_height - 1.0);
483
484                                 if (_peaks[i].max >= clip_level) {
485                                         tips[i].clip_max = true;
486                                 }
487
488                                 if (-(_peaks[i].min) >= clip_level) {
489                                         tips[i].clip_min = true;
490                                 }
491                         }
492
493                 } else {
494                         for (int i = 0; i < n_peaks; ++i) {
495
496                                 tips[i].bot = height() - 1.0;
497                                 const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
498                                 tips[i].top = y_extent (p, false);
499                                 tips[i].spread = p * (_height - 2.0);
500                                 if (p >= clip_level) {
501                                         tips[i].clip_max = true;
502                                 }
503                         }
504
505                 }
506
507         } else {
508
509                 if (_logscaled) {
510                         for (int i = 0; i < n_peaks; ++i) {
511                                 double top = _peaks[i].max;
512                                 double bot = _peaks[i].min;
513
514                                 if (_peaks[i].max >= clip_level) {
515                                                 tips[i].clip_max = true;
516                                 }
517                                 if (-(_peaks[i].min) >= clip_level) {
518                                         tips[i].clip_min = true;
519                                 }
520
521                                 if (top > 0.0) {
522                                         top = alt_log_meter (fast_coefficient_to_dB (top));
523                                 } else if (top < 0.0) {
524                                         top =-alt_log_meter (fast_coefficient_to_dB (-top));
525                                 } else {
526                                         top = 0.0;
527                                 }
528
529                                 if (bot > 0.0) {
530                                         bot = alt_log_meter (fast_coefficient_to_dB (bot));
531                                 } else if (bot < 0.0) {
532                                         bot = -alt_log_meter (fast_coefficient_to_dB (-bot));
533                                 } else {
534                                         bot = 0.0;
535                                 }
536
537                                 tips[i].top = y_extent (top, false);
538                                 tips[i].bot = y_extent (bot, true);
539                                 tips[i].spread = tips[i].bot - tips[i].top;
540                         }
541
542                 } else {
543                         for (int i = 0; i < n_peaks; ++i) {
544                                 if (_peaks[i].max >= clip_level) {
545                                         tips[i].clip_max = true;
546                                 }
547                                 if (-(_peaks[i].min) >= clip_level) {
548                                         tips[i].clip_min = true;
549                                 }
550
551                                 tips[i].top = y_extent (_peaks[i].max, false);
552                                 tips[i].bot = y_extent (_peaks[i].min, true);
553                                 tips[i].spread = tips[i].bot - tips[i].top;
554                         }
555
556                 }
557         }
558         Color alpha_one = rgba_to_color (0, 0, 0, 1.0);
559
560         set_source_rgba (wave_context, alpha_one);
561         set_source_rgba (outline_context, alpha_one);
562         set_source_rgba (clip_context, alpha_one);
563         set_source_rgba (zero_context, alpha_one);
564
565         /* ensure single-pixel lines */
566
567         wave_context->set_line_width (1.0);
568         wave_context->translate (0.5, +1.5);
569
570         outline_context->set_line_width (1.0);
571         outline_context->translate (0.5, +1.5);
572
573         clip_context->set_line_width (1.0);
574         clip_context->translate (0.5, +1.5);
575
576         zero_context->set_line_width (1.0);
577         zero_context->translate (0.5, +1.5);
578
579         /* the height of the clip-indicator should be at most 7 pixels,
580          * or 5% of the height of the waveview item.
581          */
582
583         const double clip_height = min (7.0, ceil (_height * 0.05));
584
585         /* There are 3 possible components to draw at each x-axis position: the
586            waveform "line", the zero line and an outline/clip indicator.  We
587            have to decide which of the 3 to draw at each position, pixel by
588            pixel. This makes the rendering less efficient but it is the only
589            way I can see to do this correctly.
590
591            To avoid constant source swapping and stroking, we draw the components separately
592            onto four alpha only image surfaces for use as a mask.
593
594            With only 1 pixel of spread between the top and bottom of the line,
595            we just draw the upper outline/clip indicator.
596
597            With 2 pixels of spread, we draw the upper and lower outline clip
598            indicators.
599
600            With 3 pixels of spread we draw the upper and lower outline/clip
601            indicators and at least 1 pixel of the waveform line.
602
603            With 5 pixels of spread, we draw all components.
604
605            We can do rectified as two separate passes because we have a much
606            easier decision regarding whether to draw the waveform line. We
607            always draw the clip/outline indicators.
608         */
609
610         if (_shape == WaveView::Rectified) {
611
612                 for (int i = 0; i < n_peaks; ++i) {
613
614                         /* waveform line */
615
616                         if (tips[i].spread >= 1.0) {
617                                 wave_context->move_to (i, tips[i].top);
618                                 wave_context->line_to (i, tips[i].bot);
619                         }
620
621                         /* clip indicator */
622
623                         if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
624                                 clip_context->move_to (i, tips[i].top);
625                                 /* clip-indicating upper terminal line */
626                                 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + .5)));
627                         } else {
628                                 outline_context->move_to (i, tips[i].top);
629                                 /* normal upper terminal dot */
630                                 outline_context->rel_line_to (0, -1.0);
631                         }
632                 }
633
634                 wave_context->stroke ();
635                 clip_context->stroke ();
636                 outline_context->stroke ();
637
638         } else {
639                 const double height_2 = (_height - 2.5) * .5;
640
641                 for (int i = 0; i < n_peaks; ++i) {
642
643                         /* waveform line */
644
645                         if (tips[i].spread >= 2.0) {
646                                 wave_context->move_to (i, tips[i].top);
647                                 wave_context->line_to (i, tips[i].bot);
648                         }
649                         /* draw square waves and other discontiguous points clearly */
650                         if (i > 0) {
651                                 if (tips[i-1].top + 2 < tips[i].top) {
652                                         wave_context->move_to (i-1, tips[i-1].top);
653                                         wave_context->line_to (i-1, (tips[i].bot + tips[i-1].top)/2);
654                                         wave_context->move_to (i, (tips[i].bot + tips[i-1].top)/2);
655                                         wave_context->line_to (i, tips[i].top);
656                                 } else if (tips[i-1].bot > tips[i].bot + 2) {
657                                         wave_context->move_to (i-1, tips[i-1].bot);
658                                         wave_context->line_to (i-1, (tips[i].top + tips[i-1].bot)/2);
659                                         wave_context->move_to (i, (tips[i].top + tips[i-1].bot)/2);
660                                         wave_context->line_to (i, tips[i].bot);
661                                 }
662                         }
663
664                         /* zero line */
665
666                         if (tips[i].spread >= 5.0 && show_zero_line()) {
667                                 zero_context->move_to (i, floor(height_2));
668                                 zero_context->rel_line_to (1.0, 0);
669                         }
670
671                         if (tips[i].spread > 1.0) {
672                                 bool clipped = false;
673                                 /* outline/clip indicators */
674                                 if (_global_show_waveform_clipping && tips[i].clip_max) {
675                                         clip_context->move_to (i, tips[i].top);
676                                         /* clip-indicating upper terminal line */
677                                         clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + 0.5)));
678                                         clipped = true;
679                                 }
680
681                                 if (_global_show_waveform_clipping && tips[i].clip_min) {
682                                         clip_context->move_to (i, tips[i].bot);
683                                         /* clip-indicating lower terminal line */
684                                         clip_context->rel_line_to (0, - min (clip_height, ceil(tips[i].spread + 0.5)));
685                                         clipped = true;
686                                 }
687
688                                 if (!clipped) {
689                                         outline_context->move_to (i, tips[i].bot + 1.0);
690                                         /* normal lower terminal dot */
691                                         outline_context->rel_line_to (0, -1.0);
692
693                                         outline_context->move_to (i, tips[i].top - 1.0);
694                                         /* normal upper terminal dot */
695                                         outline_context->rel_line_to (0, 1.0);
696                                 }
697                         } else {
698                                 bool clipped = false;
699                                 /* outline/clip indicator */
700                                 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
701                                         clip_context->move_to (i, tips[i].top);
702                                         /* clip-indicating upper / lower terminal line */
703                                         clip_context->rel_line_to (0, 1.0);
704                                         clipped = true;
705                                 }
706
707                                 if (!clipped) {
708                                         wave_context->move_to (i, tips[i].top);
709                                         /* special case where outline only is drawn.
710                                          * we draw a 1px "line", pretending that the span is 1.0
711                                         */
712                                         wave_context->rel_line_to (0, 1.0);
713                                 }
714                         }
715                 }
716
717                 wave_context->stroke ();
718                 outline_context->stroke ();
719                 clip_context->stroke ();
720                 zero_context->stroke ();
721         }
722
723         Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
724
725         /* Here we set a source colour and use the various components as a mask. */
726
727         if (gradient_depth() != 0.0) {
728
729                 Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _height));
730
731                 double stops[3];
732
733                 double r, g, b, a;
734
735                 if (_shape == Rectified) {
736                         stops[0] = 0.1;
737                         stops[1] = 0.3;
738                         stops[2] = 0.9;
739                 } else {
740                         stops[0] = 0.1;
741                         stops[1] = 0.5;
742                         stops[2] = 0.9;
743                 }
744
745                 color_to_rgba (_fill_color, r, g, b, a);
746                 gradient->add_color_stop_rgba (stops[1], r, g, b, a);
747                 /* generate a new color for the middle of the gradient */
748                 double h, s, v;
749                 color_to_hsv (_fill_color, h, s, v);
750                 /* change v towards white */
751                 v *= 1.0 - gradient_depth();
752                 Color center = hsva_to_color (h, s, v, a);
753                 color_to_rgba (center, r, g, b, a);
754
755                 gradient->add_color_stop_rgba (stops[0], r, g, b, a);
756                 gradient->add_color_stop_rgba (stops[2], r, g, b, a);
757
758                 context->set_source (gradient);
759         } else {
760                 set_source_rgba (context, _fill_color);
761         }
762
763         context->mask (images.wave, 0, 0);
764         context->fill ();
765
766         set_source_rgba (context, _outline_color);
767         context->mask (images.outline, 0, 0);
768         context->fill ();
769
770         set_source_rgba (context, _clip_color);
771         context->mask (images.clip, 0, 0);
772         context->fill ();
773
774         set_source_rgba (context, _zero_color);
775         context->mask (images.zero, 0, 0);
776         context->fill ();
777
778 }
779
780 void
781 WaveView::get_image (Cairo::RefPtr<Cairo::ImageSurface>& image, framepos_t start, framepos_t end, double& image_offset) const
782 {
783         vector <CacheEntry> caches;
784
785         if (_image_cache.find (_region->audio_source ()) != _image_cache.end ()) {
786
787                 caches = _image_cache.find (_region->audio_source ())->second;
788         }
789
790         /* Find a suitable ImageSurface.
791         */
792         for (uint32_t i = 0; i < caches.size (); ++i) {
793
794                 if (_channel != caches[i].channel
795                     || _height != caches[i].height
796                     || _region_amplitude != caches[i].amplitude
797                     || _fill_color != caches[i].fill_color) {
798
799                         continue;
800                 }
801
802                 framepos_t segment_start = caches[i].start;
803                 framepos_t segment_end = caches[i].end;
804
805                 if (end <= segment_end && start >= segment_start) {
806                         image_offset = (segment_start - _region_start) / _samples_per_pixel;
807                         image = caches[i].image;
808
809                         return;
810                 }
811         }
812
813         consolidate_image_cache ();
814
815         /* sample position is canonical here, and we want to generate
816          * an image that spans about twice the canvas width
817          */
818
819         const framepos_t center = start + ((end - start) / 2);
820         const framecnt_t canvas_samples = _canvas->visible_area().width() * _samples_per_pixel; /* one canvas width */
821
822         /* we can request data from anywhere in the Source, between 0 and its length
823          */
824
825         framepos_t sample_start = max ((framepos_t) 0, (center - canvas_samples));
826         framepos_t sample_end = min (center + canvas_samples, _region->source_length (0));
827
828         const int n_peaks = llrintf ((sample_end - sample_start)/ (double) _samples_per_pixel);
829
830         boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
831
832         framecnt_t peaks_read;
833         peaks_read = _region->read_peaks (peaks.get(), n_peaks,
834                              sample_start, sample_end - sample_start,
835                              _channel,
836                              _samples_per_pixel);
837
838         image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, _height);
839
840         if (peaks_read > 0) {
841                 draw_image (image, peaks.get(), n_peaks);
842         } else {
843                 draw_absent_image (image, peaks.get(), n_peaks);
844         }
845
846         _image_cache[_region->audio_source ()].push_back (CacheEntry (_channel, _height, _region_amplitude, _fill_color, sample_start,  sample_end, image));
847
848         image_offset = (sample_start - _region->start()) / _samples_per_pixel;
849
850         //cerr << "_image_cache size is : " << _image_cache.size() << " entries for this audiosource : " << _image_cache.find (_region->audio_source ())->second.size() << endl;
851
852         return;
853 }
854
855 void
856 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
857 {
858         assert (_samples_per_pixel != 0);
859
860         if (!_region) {
861                 return;
862         }
863
864         Rect self = item_to_window (Rect (0.0, 0.0, _region->length() / _samples_per_pixel, _height));
865         boost::optional<Rect> d = self.intersection (area);
866
867         if (!d) {
868                 return;
869         }
870
871         Rect draw = d.get();
872
873         /* window coordinates - pixels where x=0 is the left edge of the canvas
874          * window. We round down in case we were asked to
875          * draw "between" pixels at the start and/or end.
876          */
877         
878         double draw_start = floor (draw.x0);
879         const double draw_end = floor (draw.x1);
880
881         // cerr << "Need to draw " << draw_start << " .. " << draw_end << endl;
882
883         /* image coordnates: pixels where x=0 is the start of this waveview,
884          * wherever it may be positioned. thus image_start=N means "an image
885          * that beings N pixels after the start of region that this waveview is
886          * representing.
887          */
888
889         const framepos_t image_start = window_to_image (self.x0, draw_start);
890         const framepos_t image_end = window_to_image (self.x0, draw_end);
891
892         // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
893
894         /* sample coordinates - note, these are not subject to rounding error */
895         framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
896         framepos_t sample_end   = _region_start + (image_end * _samples_per_pixel);
897         
898         // cerr << "Sample space: " << sample_start << " .. " << sample_end << endl;
899
900         Cairo::RefPtr<Cairo::ImageSurface> image;
901         double image_offset = 0;
902
903         get_image (image, sample_start, sample_end, image_offset);
904
905         // cerr << "Offset into image to place at zero: " << image_offset << endl;
906
907         if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
908                 /* we are going to draw the first pixel for this region, but 
909                    we may not want this to overlap a border around the
910                    waveform. If so, _start_shift will be set.
911                 */
912                 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
913                 //draw_start += _start_shift;
914                 //image_offset += _start_shift;
915         }
916         
917         context->rectangle (draw_start, draw.y0, draw_end - draw_start, draw.height());
918
919         /* round image origin position to an exact pixel in device space to
920          * avoid blurring
921          */
922
923         double x  = self.x0 + image_offset;
924         double y  = self.y0;
925         context->user_to_device (x, y);
926         x = round (x);
927         y = round (y);
928         context->device_to_user (x, y);
929
930         context->set_source (image, x, y);
931         context->fill ();
932
933 }
934
935 void
936 WaveView::compute_bounding_box () const
937 {
938         if (_region) {
939                 _bounding_box = Rect (0.0, 0.0, _region->length() / _samples_per_pixel, _height);
940         } else {
941                 _bounding_box = boost::optional<Rect> ();
942         }
943
944         _bounding_box_dirty = false;
945 }
946
947 void
948 WaveView::set_height (Distance height)
949 {
950         if (height != _height) {
951                 begin_change ();
952
953                 invalidate_image_cache ();
954                 _height = height;
955
956                 _bounding_box_dirty = true;
957                 end_change ();
958         }
959 }
960
961 void
962 WaveView::set_channel (int channel)
963 {
964         if (channel != _channel) {
965                 begin_change ();
966
967                 invalidate_image_cache ();
968                 _channel = channel;
969
970                 _bounding_box_dirty = true;
971                 end_change ();
972         }
973 }
974
975 void
976 WaveView::set_logscaled (bool yn)
977 {
978         if (_logscaled != yn) {
979                 begin_visual_change ();
980                 invalidate_image_cache ();
981                 _logscaled = yn;
982                 end_visual_change ();
983         }
984 }
985
986 void
987 WaveView::gain_changed ()
988 {
989         begin_visual_change ();
990         invalidate_image_cache ();
991         _region_amplitude = _region->scale_amplitude ();
992         end_visual_change ();
993 }
994
995 void
996 WaveView::set_zero_color (Color c)
997 {
998         if (_zero_color != c) {
999                 begin_visual_change ();
1000                 invalidate_image_cache ();
1001                 _zero_color = c;
1002                 end_visual_change ();
1003         }
1004 }
1005
1006 void
1007 WaveView::set_clip_color (Color c)
1008 {
1009         if (_clip_color != c) {
1010                 begin_visual_change ();
1011                 invalidate_image_cache ();
1012                 _clip_color = c;
1013                 end_visual_change ();
1014         }
1015 }
1016
1017 void
1018 WaveView::set_show_zero_line (bool yn)
1019 {
1020         if (_show_zero != yn) {
1021                 begin_visual_change ();
1022                 invalidate_image_cache ();
1023                 _show_zero = yn;
1024                 end_visual_change ();
1025         }
1026 }
1027
1028 void
1029 WaveView::set_shape (Shape s)
1030 {
1031         if (_shape != s) {
1032                 begin_visual_change ();
1033                 invalidate_image_cache ();
1034                 _shape = s;
1035                 end_visual_change ();
1036         }
1037 }
1038
1039 void
1040 WaveView::set_amplitude_above_axis (double a)
1041 {
1042         if (_amplitude_above_axis != a) {
1043                 begin_visual_change ();
1044                 invalidate_image_cache ();
1045                 _amplitude_above_axis = a;
1046                 end_visual_change ();
1047         }
1048 }
1049
1050 void
1051 WaveView::set_global_shape (Shape s)
1052 {
1053         if (_global_shape != s) {
1054                 _global_shape = s;
1055                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1056         }
1057 }
1058
1059 void
1060 WaveView::set_global_logscaled (bool yn)
1061 {
1062         if (_global_logscaled != yn) {
1063                 _global_logscaled = yn;
1064                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1065         }
1066 }
1067
1068 void
1069 WaveView::set_region_start (frameoffset_t start)
1070 {
1071         if (!_region) {
1072                 return;
1073         }
1074
1075         if (_region_start == start) {
1076                 return;
1077         }
1078
1079         begin_change ();
1080         _region_start = start;
1081         _bounding_box_dirty = true;
1082         end_change ();
1083 }
1084
1085 void
1086 WaveView::region_resized ()
1087 {
1088         /* Called when the region start or end (thus length) has changed.
1089         */
1090
1091         if (!_region) {
1092                 return;
1093         }
1094
1095         begin_change ();
1096         _region_start = _region->start();
1097         _bounding_box_dirty = true;
1098         end_change ();
1099 }
1100
1101 void
1102 WaveView::set_global_gradient_depth (double depth)
1103 {
1104         if (_global_gradient_depth != depth) {
1105                 _global_gradient_depth = depth;
1106                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1107         }
1108 }
1109
1110 void
1111 WaveView::set_global_show_waveform_clipping (bool yn)
1112 {
1113         if (_global_show_waveform_clipping != yn) {
1114                 _global_show_waveform_clipping = yn;
1115                 ClipLevelChanged ();
1116         }
1117 }
1118
1119 void
1120 WaveView::set_start_shift (double pixels)
1121 {
1122         if (pixels < 0) {
1123                 return;
1124         }
1125
1126         begin_visual_change ();
1127         _start_shift = pixels;
1128         end_visual_change ();
1129 }
1130