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