a3bbd04ab2c66266e1c5691c76455b359981aa1a
[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 (true)
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                 set_source_rgba (context, _zero_color);
394                 context->move_to (0, position (0.0));
395                 context->line_to (n_peaks, position (0.0));
396                 context->stroke ();
397         }
398 }
399
400 void
401 WaveView::ensure_cache (framepos_t start, framepos_t end) const
402 {
403         if (_image && _sample_start <= start && _sample_end >= end) {
404                 /* cache already covers required range, do nothing */
405                 return;
406         }
407
408         /* sample position is canonical here, and we want to generate
409          * an image that spans about twice the canvas width 
410          */
411         
412         const framepos_t center = start + ((end - start) / 2);
413         const framecnt_t canvas_samples = 2 * (_canvas->visible_area().width() * _samples_per_pixel);
414
415         /* we can request data from anywhere in the Source, between 0 and its length
416          */
417
418         _sample_start = max ((framepos_t) 0, (center - canvas_samples));
419         _sample_end = min (center + canvas_samples, _region->source_length (0));
420
421         double pixel_start = floor (_sample_start / (double) _samples_per_pixel);
422         double pixel_end = ceil (_sample_end / (double) _samples_per_pixel);
423         int n_peaks = llrintf (pixel_end - pixel_start);
424
425         boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
426
427         _region->read_peaks (peaks.get(), n_peaks, 
428                              _sample_start, _sample_end - _sample_start,
429                              _channel, 
430                              _samples_per_pixel);
431
432         draw_image (peaks.get(), n_peaks);
433 }
434
435 void
436 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
437 {
438         assert (_samples_per_pixel != 0);
439
440         if (!_region) {
441                 return;
442         }
443
444         Rect self = item_to_window (Rect (0.0, 0.0, floor (_region->length() / _samples_per_pixel), _height));
445         boost::optional<Rect> d = self.intersection (area);
446
447         if (!d) {
448                 return;
449         }
450         
451         Rect draw = d.get();
452
453         /* window coordinates - pixels where x=0 is the left edge of the canvas
454          * window. We round up and down in case we were asked to
455          * draw "between" pixels at the start and/or end.
456          */
457
458         const double draw_start = floor (draw.x0);
459         const double draw_end = ceil (draw.x1);
460
461         // cerr << "Need to draw " << draw_start << " .. " << draw_end << endl;
462         
463         /* image coordnates: pixels where x=0 is the start of this waveview,
464          * wherever it may be positioned. thus image_start=N means "an image
465          * that beings N pixels after the start of region that this waveview is
466          * representing. 
467          */
468
469         const framepos_t image_start = window_to_image (self.x0, draw_start);
470         const framepos_t image_end = window_to_image (self.x0, draw_end);
471
472         // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
473
474         /* sample coordinates - note, these are not subject to rounding error */
475         framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
476         framepos_t sample_end   = _region_start + (image_end * _samples_per_pixel);
477
478         // cerr << "Sample space: " << sample_start << " .. " << sample_end << endl;
479
480         ensure_cache (sample_start, sample_end);
481
482         // cerr << "Cache contains " << _cache->pixel_start() << " .. " << _cache->pixel_end() << " / " 
483         // << _cache->sample_start() << " .. " << _cache->sample_end()
484         // << endl;
485
486         double image_offset = (_sample_start - _region->start()) / _samples_per_pixel;
487
488         // cerr << "Offset into image to place at zero: " << image_offset << endl;
489
490         context->rectangle (draw_start, draw.y0, draw_end - draw_start, draw.height());
491
492         /* round image origin position to an exact pixel in device space to
493          * avoid blurring
494          */
495
496         double x  = self.x0 + image_offset;
497         double y  = self.y0;
498         context->user_to_device (x, y);
499         x = round (x);
500         y = round (y);
501         context->device_to_user (x, y);
502
503         context->set_source (_image, x, y);
504         context->fill ();
505 }
506
507 void
508 WaveView::compute_bounding_box () const
509 {
510         if (_region) {
511                 _bounding_box = Rect (0.0, 0.0, _region->length() / _samples_per_pixel, _height);
512         } else {
513                 _bounding_box = boost::optional<Rect> ();
514         }
515         
516         _bounding_box_dirty = false;
517 }
518         
519 void
520 WaveView::set_height (Distance height)
521 {
522         if (height != _height) {
523                 begin_change ();
524                 
525                 _height = height;
526                 
527                 _bounding_box_dirty = true;
528                 end_change ();
529                 
530                 invalidate_image ();
531         }
532 }
533
534 void
535 WaveView::set_channel (int channel)
536 {
537         if (channel != _channel) {
538                 begin_change ();
539                 
540                 _channel = channel;
541                 
542                 _bounding_box_dirty = true;
543                 end_change ();
544                 
545                 invalidate_image ();
546         }
547 }
548
549 void
550 WaveView::invalidate_image ()
551 {
552         begin_visual_change ();
553
554         _image.clear ();
555         _sample_start  = -1;
556         _sample_end = -1;
557         
558         end_visual_change ();
559 }
560
561
562 void
563 WaveView::set_logscaled (bool yn)
564 {
565         if (_logscaled != yn) {
566                 _logscaled = yn;
567                 invalidate_image ();
568         }
569 }
570
571 void
572 WaveView::gain_changed ()
573 {
574         invalidate_image ();
575 }
576
577 void
578 WaveView::set_zero_color (Color c)
579 {
580         if (_zero_color != c) {
581                 _zero_color = c;
582                 invalidate_image ();
583         }
584 }
585
586 void
587 WaveView::set_clip_color (Color c)
588 {
589         if (_clip_color != c) {
590                 _clip_color = c;
591                 invalidate_image ();
592         }
593 }
594
595 void
596 WaveView::set_show_zero_line (bool yn)
597 {
598         if (_show_zero != yn) {
599                 _show_zero = yn;
600                 invalidate_image ();
601         }
602 }
603
604 void
605 WaveView::set_shape (Shape s)
606 {
607         if (_shape != s) {
608                 _shape = s;
609                 invalidate_image ();
610         }
611 }
612
613 void
614 WaveView::set_amplitude_above_axis (double a)
615 {
616         if (_amplitude_above_axis != a) {
617                 _amplitude_above_axis = a;
618                 invalidate_image ();
619         }
620 }
621
622 void
623 WaveView::set_global_shape (Shape s)
624 {
625         if (_global_shape != s) {
626                 _global_shape = s;
627                 VisualPropertiesChanged (); /* EMIT SIGNAL */
628         }
629 }
630
631 void
632 WaveView::set_global_logscaled (bool yn)
633 {
634         if (_global_logscaled != yn) {
635                 _global_logscaled = yn;
636                 VisualPropertiesChanged (); /* EMIT SIGNAL */
637         }
638 }
639
640 void
641 WaveView::region_resized ()
642 {
643         if (!_region) {
644                 return;
645         }
646
647         /* special: do not use _region->length() here to compute
648            bounding box because it will already have changed.
649            
650            if we have a bounding box, use it.
651         */
652
653         _pre_change_bounding_box = _bounding_box;
654
655         _bounding_box_dirty = true;
656         compute_bounding_box ();
657
658         end_change ();
659 }
660
661 Coord
662 WaveView::position (double s) const
663 {
664         /* it is important that this returns an integral value, so that we 
665            can ensure correct single pixel behaviour.
666          */
667
668         Coord pos;
669
670         switch (_shape) {
671         case Rectified:
672                 pos = floor (_height - (s * _height));
673         default:
674                 pos = floor ((1.0-s) * (_height / 2.0));
675                 break;
676         }
677
678         return min (_height, (max (0.0, pos)));
679 }
680
681 void
682 WaveView::set_global_gradient_depth (double depth)
683 {
684         if (_global_gradient_depth != depth) {
685                 _global_gradient_depth = depth;
686                 VisualPropertiesChanged (); /* EMIT SIGNAL */
687         }
688 }
689
690 void
691 WaveView::set_global_show_waveform_clipping (bool yn)
692 {
693         if (_global_show_waveform_clipping != yn) {
694                 _global_show_waveform_clipping = yn;
695                 VisualPropertiesChanged (); /* EMIT SIGNAL */
696         }
697 }
698