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