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