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