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