an awful lot of tweaks to drawing details
[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 <boost/scoped_array.hpp>
25
26 #include "gtkmm2ext/utils.h"
27
28 #include "pbd/compose.h"
29 #include "pbd/signals.h"
30 #include "pbd/stacktrace.h"
31
32 #include "ardour/types.h"
33 #include "ardour/dB.h"
34 #include "ardour/audioregion.h"
35
36 #include "canvas/wave_view.h"
37 #include "canvas/utils.h"
38 #include "canvas/canvas.h"
39
40 #include <gdkmm/general.h>
41
42 using namespace std;
43 using namespace ARDOUR;
44 using namespace ArdourCanvas;
45
46 double WaveView::_global_gradient_depth = 0.6;
47 bool WaveView::_global_logscaled = false;
48 WaveView::Shape WaveView::_global_shape = WaveView::Normal;
49
50 PBD::Signal0<void> WaveView::VisualPropertiesChanged;
51
52 WaveView::WaveView (Group* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
53         : Item (parent)
54         , Outline (parent)
55         , Fill (parent)
56         , _region (region)
57         , _channel (0)
58         , _samples_per_pixel (0)
59         , _height (64)
60         , _wave_color (0xffffffff)
61         , _show_zero (true)
62         , _zero_color (0xff0000ff)
63         , _clip_color (0xff0000ff)
64         , _logscaled (_global_logscaled)
65         , _shape (_global_shape)
66         , _gradient_depth (_global_gradient_depth)
67         , _shape_independent (false)
68         , _logscaled_independent (false)
69         , _gradient_depth_independent (false)
70         , _amplitude_above_axis (1.0)
71         , _region_start (region->start())
72         , _cache (0)
73 {
74         VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
75 }
76
77 WaveView::~WaveView ()
78 {
79         delete _cache;
80         _cache = 0;
81 }
82
83 void
84 WaveView::handle_visual_property_change ()
85 {
86         bool changed = false;
87
88         if (!_shape_independent && (_shape != global_shape())) {
89                 _shape = global_shape();
90                 changed = true;
91         }
92
93         if (!_logscaled_independent && (_logscaled != global_logscaled())) {
94                 _logscaled = global_logscaled();
95                 changed = true;
96         }
97
98         if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
99                 _gradient_depth = global_gradient_depth();
100                 changed = true;
101         }
102         
103         if (changed) {
104                 invalidate_image_cache ();
105         }
106 }
107
108 void
109 WaveView::set_fill_color (Color c)
110 {
111         if (c != _fill_color) {
112                 invalidate_image_cache ();
113                 Fill::set_fill_color (c);
114         }
115 }
116
117 void
118 WaveView::set_outline_color (Color c)
119 {
120         if (c != _outline_color) {
121                 invalidate_image_cache ();
122                 Outline::set_outline_color (c);
123         }
124 }
125
126 void
127 WaveView::set_samples_per_pixel (double samples_per_pixel)
128 {
129         if (samples_per_pixel != _samples_per_pixel) {
130                 begin_change ();
131
132                 _samples_per_pixel = samples_per_pixel;
133                 
134                 _bounding_box_dirty = true;
135                 
136                 end_change ();
137                 
138                 invalidate_whole_cache ();
139         }
140 }
141
142 static inline double
143 image_to_window (double wave_origin, double image_start)
144 {
145         return wave_origin + image_start;
146 }
147
148 static inline double
149 window_to_image (double wave_origin, double image_start)
150 {
151         return image_start - wave_origin;
152 }
153
154 void
155 WaveView::ensure_cache (framecnt_t start, framecnt_t end,
156                         framepos_t sample_start, framepos_t sample_end) const
157 {
158         if (_cache && _cache->sample_start() <= sample_start && _cache->sample_end() >= sample_end) {
159                 /* cache already covers required range, do nothing */
160                 return;
161         }
162
163         if (_cache) {
164                 delete _cache;
165                 _cache = 0;
166         }
167
168         /* sample position is canonical here, and we want to generate
169          * an image that spans about twice the canvas width 
170          */
171         
172         const framepos_t center = sample_start + ((sample_end - sample_start) / 2);
173         const framecnt_t canvas_samples = 2 * (_canvas->visible_area().width() * _samples_per_pixel);
174
175         /* we can request data from anywhere in the Source, between 0 and its length
176          */
177
178         sample_start = max ((framepos_t) 0, (center - canvas_samples));
179         sample_end = min (center + canvas_samples, _region->source_length (0));
180
181 #if 0
182         if (sample_end <= sample_start) {
183                 cerr << "sample start = " << sample_start << endl;
184                 cerr << "center+ = " << center<< endl;
185                 cerr << "CS = " << canvas_samples << endl;
186                 cerr << "pui = " << center + canvas_samples << endl;
187                 cerr << "sl = " << _region->source_length (0) << endl;
188                 cerr << "st = " << _region->start () << endl;
189                 cerr << "END: " << sample_end << endl;
190                 assert (false);
191         }
192 #endif
193         
194         start = floor (sample_start / (double) _samples_per_pixel);
195         end = ceil (sample_end / (double) _samples_per_pixel);
196         
197         assert (end > start);
198
199         // cerr << name << " cache miss - new CE, span " << start << " .. " << end << " (" << sample_start << " .. " << sample_end << ")\n";
200
201         _cache = new CacheEntry (this, start, end, sample_start, sample_end);
202 }
203
204 void
205 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
206 {
207         assert (_samples_per_pixel != 0);
208
209         if (!_region) {
210                 return;
211         }
212
213         Rect self = item_to_window (Rect (0.0, 0.0, floor (_region->length() / _samples_per_pixel), _height));
214         boost::optional<Rect> d = self.intersection (area);
215
216         if (!d) {
217                 return;
218         }
219         
220         Rect draw = d.get();
221
222         /* window coordinates - pixels where x=0 is the left edge of the canvas
223          * window. We round up and down in case we were asked to
224          * draw "between" pixels at the start and/or end.
225          */
226
227         const double draw_start = floor (draw.x0);
228         const double draw_end = ceil (draw.x1);
229
230         // cerr << "Need to draw " << draw_start << " .. " << draw_end << endl;
231         
232         /* image coordnates: pixels where x=0 is the start of this waveview,
233          * wherever it may be positioned. thus image_start=N means "an image
234          * that beings N pixels after the start of region that this waveview is
235          * representing. 
236          */
237
238         const framepos_t image_start = window_to_image (self.x0, draw_start);
239         const framepos_t image_end = window_to_image (self.x0, draw_end);
240
241         // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
242
243         /* sample coordinates - note, these are not subject to rounding error */
244         framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
245         framepos_t sample_end   = _region_start + (image_end * _samples_per_pixel);
246
247         // cerr << "Sample space: " << sample_start << " .. " << sample_end << endl;
248
249         ensure_cache (image_start, image_end, sample_start, sample_end);
250
251         // cerr << "Cache contains " << _cache->pixel_start() << " .. " << _cache->pixel_end() << " / " 
252         // << _cache->sample_start() << " .. " << _cache->sample_end()
253         // << endl;
254
255         double image_offset = (_cache->sample_start() - _region->start()) / _samples_per_pixel;
256
257         // cerr << "Offset into image to place at zero: " << image_offset << endl;
258
259         context->rectangle (draw_start, draw.y0, draw_end - draw_start, draw.height());
260
261         /* round image origin position to an exact pixel in device space to
262          * avoid blurring
263          */
264
265         double x  = self.x0 + image_offset;
266         double y  = self.y0;
267         context->user_to_device (x, y);
268         x = round (x);
269         y = round (y);
270         context->device_to_user (x, y);
271
272         context->set_source (_cache->image(), x, y);
273         context->fill ();
274 }
275
276 void
277 WaveView::compute_bounding_box () const
278 {
279         if (_region) {
280                 _bounding_box = Rect (0.0, 0.0, _region->length() / _samples_per_pixel, _height);
281         } else {
282                 _bounding_box = boost::optional<Rect> ();
283         }
284         
285         _bounding_box_dirty = false;
286 }
287         
288 void
289 WaveView::set_height (Distance height)
290 {
291         if (height != _height) {
292                 begin_change ();
293                 
294                 _height = height;
295                 
296                 _bounding_box_dirty = true;
297                 end_change ();
298                 
299                 invalidate_image_cache ();
300         }
301 }
302
303 void
304 WaveView::set_channel (int channel)
305 {
306         if (channel != _channel) {
307                 begin_change ();
308                 
309                 _channel = channel;
310                 
311                 _bounding_box_dirty = true;
312                 end_change ();
313                 
314                 invalidate_whole_cache ();
315         }
316 }
317
318 void
319 WaveView::invalidate_whole_cache ()
320 {
321         begin_visual_change ();
322         delete _cache;
323         _cache = 0;
324         end_visual_change ();
325 }
326
327 void
328 WaveView::invalidate_image_cache ()
329 {
330         invalidate_whole_cache ();
331 }
332
333 void
334 WaveView::set_logscaled (bool yn)
335 {
336         if (_logscaled != yn) {
337                 _logscaled = yn;
338                 invalidate_image_cache ();
339         }
340 }
341
342 void
343 WaveView::gain_changed ()
344 {
345         invalidate_whole_cache ();
346 }
347
348 void
349 WaveView::set_zero_color (Color c)
350 {
351         if (_zero_color != c) {
352                 _zero_color = c;
353                 invalidate_image_cache ();
354         }
355 }
356
357 void
358 WaveView::set_clip_color (Color c)
359 {
360         if (_clip_color != c) {
361                 _clip_color = c;
362                 invalidate_image_cache ();
363         }
364 }
365
366 void
367 WaveView::set_show_zero_line (bool yn)
368 {
369         if (_show_zero != yn) {
370                 _show_zero = yn;
371                 invalidate_image_cache ();
372         }
373 }
374
375 void
376 WaveView::set_shape (Shape s)
377 {
378         if (_shape != s) {
379                 _shape = s;
380                 invalidate_image_cache ();
381         }
382 }
383
384 void
385 WaveView::set_amplitude_above_axis (double a)
386 {
387         if (_amplitude_above_axis != a) {
388                 _amplitude_above_axis = a;
389                 invalidate_image_cache ();
390         }
391 }
392
393 void
394 WaveView::set_global_shape (Shape s)
395 {
396         if (_global_shape != s) {
397                 _global_shape = s;
398                 VisualPropertiesChanged (); /* EMIT SIGNAL */
399         }
400 }
401
402 void
403 WaveView::set_global_logscaled (bool yn)
404 {
405         if (_global_logscaled != yn) {
406                 _global_logscaled = yn;
407                 VisualPropertiesChanged (); /* EMIT SIGNAL */
408         }
409 }
410
411 void
412 WaveView::region_resized ()
413 {
414         if (!_region) {
415                 return;
416         }
417
418         /* special: do not use _region->length() here to compute
419            bounding box because it will already have changed.
420            
421            if we have a bounding box, use it.
422         */
423
424         _pre_change_bounding_box = _bounding_box;
425
426         _bounding_box_dirty = true;
427         compute_bounding_box ();
428
429         end_change ();
430 }
431
432 WaveView::CacheEntry::CacheEntry (WaveView const * wave_view, double pixel_start, double pixel_end,
433                                   framepos_t sample_start,framepos_t sample_end)
434         : _wave_view (wave_view)
435         , _pixel_start (pixel_start)
436         , _pixel_end (pixel_end)
437         , _sample_start (sample_start)
438         , _sample_end (sample_end)
439         , _n_peaks (_pixel_end - _pixel_start)
440 {
441         _peaks.reset (new PeakData[_n_peaks]);
442
443         _wave_view->_region->read_peaks (_peaks.get(), _n_peaks, 
444                                          _sample_start, _sample_end - _sample_start,
445                                          _wave_view->_channel, 
446                                          _wave_view->_samples_per_pixel);
447 }
448
449 WaveView::CacheEntry::~CacheEntry ()
450 {
451 }
452
453 static inline float
454 _log_meter (float power, double lower_db, double upper_db, double non_linearity)
455 {
456         return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
457 }
458
459 static inline float
460 alt_log_meter (float power)
461 {
462         return _log_meter (power, -192.0, 0.0, 8.0);
463 }
464
465 struct LineTips {
466     double top;
467     double bot;
468     bool clipped;
469     
470     LineTips() : top (0.0), bot (0.0), clipped (false) {}
471 };
472
473 Cairo::RefPtr<Cairo::ImageSurface>
474 WaveView::CacheEntry::image ()
475 {
476         if (!_image) {
477
478                 _image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, _n_peaks, _wave_view->_height);
479                 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (_image);
480
481 #ifdef AREA_DRAW_AND_FILL
482
483                 /* Draw the edge of the waveform, top half first, the loop back
484                  * for the bottom half to create a clockwise path
485                  */
486
487                 context->begin_new_path();
488
489                 if (_wave_view->_shape == WaveView::Rectified) {
490
491                         /* top edge of waveform is based on max (fabs (peak_min, peak_max))
492                          */
493
494                         if (_wave_view->_logscaled) {
495                                 for (int i = 0; i < _n_peaks; ++i) {
496                                         context->line_to (i + 0.5, position (alt_log_meter (fast_coefficient_to_dB (
497                                                                                                     max (fabs (_peaks[i].max), fabs (_peaks[i].min))))));
498                                 }
499                         } else {
500                                 for (int i = 0; i < _n_peaks; ++i) {
501                                         context->line_to (i + 0.5, position (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
502                                 }
503                         }
504
505                 } else {
506                         if (_wave_view->_logscaled) {
507                                 for (int i = 0; i < _n_peaks; ++i) {
508                                         Coord y = _peaks[i].max;
509                                         
510                                         if (y > 0.0) {
511                                                 y = position (alt_log_meter (fast_coefficient_to_dB (y)));
512                                         } else if (y < 0.0) {
513                                                 y = position (-alt_log_meter (fast_coefficient_to_dB (-y)));
514                                         } else {
515                                                 y = position (0.0);
516                                         }
517                                         context->line_to (i + 0.5, y);
518                                 } 
519                         } else {
520                                 for (int i = 0; i < _n_peaks; ++i) {
521                                         context->line_to (i + 0.5, position (_peaks[i].max));
522                                 }
523                         }
524                 }
525
526                 /* from final top point, move out of the clip zone */
527
528                 context->line_to (_n_peaks + 10, position (0.0));
529         
530                 /* bottom half, in reverse */
531         
532                 if (_wave_view->_shape == WaveView::Rectified) {
533                         
534                         /* lower half: drop to the bottom, then a line back to
535                          * beyond the left edge of the clip region 
536                          */
537
538                         context->line_to (_n_peaks + 10, _wave_view->_height);
539                         context->line_to (-10.0, _wave_view->_height);
540
541                 } else {
542
543                         if (_wave_view->_logscaled) {
544                                 for (int i = _n_peaks-1; i >= 0; --i) {
545                                         Coord y = _peaks[i].min;
546                                         if (y > 0.0) {
547                                                 context->line_to (i + 0.5, position (alt_log_meter (fast_coefficient_to_dB (y))));
548                                         } else if (y < 0.0) {
549                                                 context->line_to (i + 0.5, position (-alt_log_meter (fast_coefficient_to_dB (-y))));
550                                         } else {
551                                                 context->line_to (i + 0.5, position (0.0));
552                                         }
553                                 } 
554                         } else {
555                                 for (int i = _n_peaks-1; i >= 0; --i) {
556                                         context->line_to (i + 0.5, position (_peaks[i].min));
557                                 }
558                         }
559                 
560                         /* from final bottom point, move out of the clip zone */
561                         
562                         context->line_to (-10.0, position (0.0));
563                 }
564
565                 context->close_path ();
566
567                 if (_wave_view->gradient_depth() != 0.0) {
568                         
569                         Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _wave_view->_height));
570                         
571                         double stops[3];
572                         
573                         double r, g, b, a;
574
575                         if (_wave_view->_shape == Rectified) {
576                                 stops[0] = 0.1;
577                                 stops[0] = 0.3;
578                                 stops[0] = 0.9;
579                         } else {
580                                 stops[0] = 0.1;
581                                 stops[1] = 0.5;
582                                 stops[2] = 0.9;
583                         }
584
585                         color_to_rgba (_wave_view->_fill_color, r, g, b, a);
586                         gradient->add_color_stop_rgba (stops[0], r, g, b, a);
587                         gradient->add_color_stop_rgba (stops[2], r, g, b, a);
588                         
589                         /* generate a new color for the middle of the gradient */
590                         double h, s, v;
591                         color_to_hsv (_wave_view->_fill_color, h, s, v);
592                         /* tone down the saturation */
593                         s *= 1.0 - _wave_view->gradient_depth();
594                         Color center = hsv_to_color (h, s, v, a);
595                         color_to_rgba (center, r, g, b, a);
596                         gradient->add_color_stop_rgba (stops[1], r, g, b, a);
597                         
598                         context->set_source (gradient);
599                 } else {
600                         set_source_rgba (context, _wave_view->_fill_color);
601                 }
602
603                 context->fill_preserve ();
604                 _wave_view->setup_outline_context (context);
605                 context->stroke ();
606
607 #else
608                 boost::scoped_array<LineTips> tips (new LineTips[_n_peaks]);
609
610                 if (_wave_view->_shape == WaveView::Rectified) {
611
612                         /* each peak is a line from the bottom of the waveview
613                          * to a point determined by max (_peaks[i].max,
614                          * _peaks[i].min)
615                          */
616
617                         if (_wave_view->_logscaled) {
618                                 for (int i = 0; i < _n_peaks; ++i) {
619                                         tips[i].bot = _wave_view->height();
620                                         tips[i].top = position (alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min)))));
621                                 }
622                         } else {
623                                 for (int i = 0; i < _n_peaks; ++i) {
624                                         tips[i].bot = _wave_view->height();
625                                         tips[i].top = position (max (fabs (_peaks[i].max), fabs (_peaks[i].min)));
626                                 }
627                         }
628
629                 } else {
630
631                         if (_wave_view->_logscaled) {
632                                 for (int i = 0; i < _n_peaks; ++i) {
633                                         Coord top = _peaks[i].min;
634                                         Coord bot = _peaks[i].max;
635
636                                         if (top > 0.0) {
637                                                 top = position (alt_log_meter (fast_coefficient_to_dB (top)));
638                                         } else if (top < 0.0) {
639                                                 top = position (-alt_log_meter (fast_coefficient_to_dB (-top)));
640                                         } else {
641                                                 top = position (0.0);
642                                         }
643
644                                         if (bot > 0.0) {
645                                                 bot = position (alt_log_meter (fast_coefficient_to_dB (bot)));
646                                         } else if (bot < 0.0) {
647                                                 bot = position (-alt_log_meter (fast_coefficient_to_dB (-bot)));
648                                         } else {
649                                                 bot = position (0.0);
650                                         }
651
652                                         tips[i].top = top;
653                                         tips[i].bot = bot;
654
655                                 } 
656
657                         } else {
658                                 for (int i = 0; i < _n_peaks; ++i) {
659                                         tips[i].top = position (_peaks[i].min);
660                                         tips[i].bot = position (_peaks[i].max);
661                                 }
662                         }
663                 }
664
665                 if (_wave_view->gradient_depth() != 0.0) {
666                         
667                         Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _wave_view->_height));
668                         
669                         double stops[3];
670                         
671                         double r, g, b, a;
672
673                         if (_wave_view->_shape == Rectified) {
674                                 stops[0] = 0.1;
675                                 stops[0] = 0.3;
676                                 stops[0] = 0.9;
677                         } else {
678                                 stops[0] = 0.1;
679                                 stops[1] = 0.5;
680                                 stops[2] = 0.9;
681                         }
682
683                         color_to_rgba (_wave_view->_fill_color, r, g, b, a);
684                         gradient->add_color_stop_rgba (stops[0], r, g, b, a);
685                         gradient->add_color_stop_rgba (stops[2], r, g, b, a);
686
687                         /* generate a new color for the middle of the gradient */
688                         double h, s, v;
689                         color_to_hsv (_wave_view->_fill_color, h, s, v);
690                         /* change v towards white */
691                         v *= 1.0 - _wave_view->gradient_depth();
692                         Color center = hsv_to_color (h, s, v, a);
693                         color_to_rgba (center, r, g, b, a);
694                         gradient->add_color_stop_rgba (stops[1], r, g, b, a);
695                         
696                         context->set_source (gradient);
697                 } else {
698                         set_source_rgba (context, _wave_view->_fill_color);
699                 }
700
701                 /* ensure single-pixel lines */
702                 
703                 context->set_line_width (0.5);
704                 context->translate (0.5, 0.0);
705
706                 /* draw the lines */
707
708                 if (_wave_view->_shape == WaveView::Rectified) {
709                         for (int i = 0; i < _n_peaks; ++i) {
710                                 context->move_to (i, tips[i].top); /* down 1 pixel */
711                                 context->line_to (i, tips[i].bot);
712                                 context->stroke ();
713                         }
714                 } else {
715                         for (int i = 0; i < _n_peaks; ++i) {
716                                 context->move_to (i, tips[i].top);
717                                 context->line_to (i, tips[i].bot);
718                                 context->stroke ();
719                         }
720                 }
721
722                 /* now add dots to the top and bottom of each line (this is
723                  * modelled on pyramix, except that we add clipping indicators.
724                  */
725
726                 context->set_source_rgba (0, 0, 0, 1.0);
727
728                 for (int i = 0; i < _n_peaks; ++i) {
729                         context->move_to (i, tips[i].top);
730                         context->rel_line_to (0, 1.0);
731                         context->stroke ();
732                         if (_wave_view->_shape != WaveView::Rectified) {
733                                 context->move_to (i, tips[i].bot);
734                                 context->rel_line_to (0, -1.0);
735                                 context->stroke ();
736                         }
737                 }
738 #endif
739
740                 if (_wave_view->show_zero_line()) {
741                         set_source_rgba (context, _wave_view->_zero_color);
742                         context->move_to (0, position (0.0));
743                         context->line_to (_n_peaks, position (0.0));
744                         context->stroke ();
745                 }
746
747         }
748
749         return _image;
750 }
751
752
753 Coord
754 WaveView::CacheEntry::position (double s) const
755 {
756         /* it is important that this returns an integral value, so that we 
757            can ensure correct single pixel behaviour.
758          */
759
760         switch (_wave_view->_shape) {
761         case Rectified:
762                 return floor (_wave_view->_height - (s * _wave_view->_height));
763         default:
764                 break;
765         }
766         return floor ((1.0-s) * (_wave_view->_height / 2.0));
767 }
768
769 void
770 WaveView::CacheEntry::clear_image ()
771 {
772         _image.clear ();
773 }
774             
775 void
776 WaveView::set_global_gradient_depth (double depth)
777 {
778         if (_global_gradient_depth != depth) {
779                 _global_gradient_depth = depth;
780                 VisualPropertiesChanged (); /* EMIT SIGNAL */
781         }
782 }