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