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