2 Copyright (C) 2011-2013 Paul Davis
3 Author: Carl Hetherington <cth@carlh.net>
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.
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.
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.
22 #include <cairomm/cairomm.h>
24 #include <glibmm/threads.h>
26 #include "gtkmm2ext/utils.h"
27 #include "gtkmm2ext/gui_thread.h"
29 #include "pbd/base_ui.h"
30 #include "pbd/compose.h"
31 #include "pbd/convert.h"
32 #include "pbd/signals.h"
33 #include "pbd/stacktrace.h"
35 #include "ardour/types.h"
36 #include "ardour/dB.h"
37 #include "ardour/lmath.h"
38 #include "ardour/audioregion.h"
39 #include "ardour/audiosource.h"
41 #include "canvas/canvas.h"
42 #include "canvas/colors.h"
43 #include "canvas/debug.h"
44 #include "canvas/utils.h"
45 #include "canvas/wave_view.h"
47 #include <gdkmm/general.h>
49 #include "gtkmm2ext/gui_thread.h"
52 using namespace ARDOUR;
54 using namespace ArdourCanvas;
56 double WaveView::_global_gradient_depth = 0.6;
57 bool WaveView::_global_logscaled = false;
58 WaveView::Shape WaveView::_global_shape = WaveView::Normal;
59 bool WaveView::_global_show_waveform_clipping = true;
60 double WaveView::_clip_level = 0.98853;
62 WaveViewCache* WaveView::images = 0;
63 gint WaveView::drawing_thread_should_quit = 0;
64 Glib::Threads::Mutex WaveView::request_queue_lock;
65 Glib::Threads::Cond WaveView::request_cond;
66 Glib::Threads::Thread* WaveView::_drawing_thread = 0;
67 WaveView::DrawingRequestQueue WaveView::request_queue;
69 PBD::Signal0<void> WaveView::VisualPropertiesChanged;
70 PBD::Signal0<void> WaveView::ClipLevelChanged;
72 WaveView::WaveView (Canvas* c, boost::shared_ptr<ARDOUR::AudioRegion> region)
76 , _samples_per_pixel (0)
79 , _zero_color (0xff0000ff)
80 , _clip_color (0xff0000ff)
81 , _logscaled (_global_logscaled)
82 , _shape (_global_shape)
83 , _gradient_depth (_global_gradient_depth)
84 , _shape_independent (false)
85 , _logscaled_independent (false)
86 , _gradient_depth_independent (false)
87 , _amplitude_above_axis (1.0)
88 , _region_amplitude (region->scale_amplitude ())
90 , _region_start (region->start())
91 , get_image_in_thread (false)
92 , always_get_image_in_thread (false)
95 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
96 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
98 ImageReady.connect (image_ready_connection, MISSING_INVALIDATOR, boost::bind (&WaveView::image_ready, this), gui_context());
101 WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
105 , _samples_per_pixel (0)
108 , _zero_color (0xff0000ff)
109 , _clip_color (0xff0000ff)
110 , _logscaled (_global_logscaled)
111 , _shape (_global_shape)
112 , _gradient_depth (_global_gradient_depth)
113 , _shape_independent (false)
114 , _logscaled_independent (false)
115 , _gradient_depth_independent (false)
116 , _amplitude_above_axis (1.0)
117 , _region_amplitude (region->scale_amplitude ())
118 , _region_start (region->start())
119 , get_image_in_thread (false)
120 , always_get_image_in_thread (false)
123 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
124 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
126 ImageReady.connect (image_ready_connection, MISSING_INVALIDATOR, boost::bind (&WaveView::image_ready, this), gui_context());
129 WaveView::~WaveView ()
131 invalidate_image_cache ();
135 WaveView::debug_name() const
137 return _region->name() + string (":") + PBD::to_string (_channel+1, std::dec);
141 WaveView::image_ready ()
147 WaveView::set_always_get_image_in_thread (bool yn)
149 always_get_image_in_thread = yn;
153 WaveView::handle_visual_property_change ()
155 bool changed = false;
157 if (!_shape_independent && (_shape != global_shape())) {
158 _shape = global_shape();
162 if (!_logscaled_independent && (_logscaled != global_logscaled())) {
163 _logscaled = global_logscaled();
167 if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
168 _gradient_depth = global_gradient_depth();
173 begin_visual_change ();
174 invalidate_image_cache ();
175 end_visual_change ();
180 WaveView::handle_clip_level_change ()
182 begin_visual_change ();
183 invalidate_image_cache ();
184 end_visual_change ();
188 WaveView::set_fill_color (Color c)
190 if (c != _fill_color) {
191 begin_visual_change ();
192 invalidate_image_cache ();
193 Fill::set_fill_color (c);
194 end_visual_change ();
199 WaveView::set_outline_color (Color c)
201 if (c != _outline_color) {
202 begin_visual_change ();
203 invalidate_image_cache ();
204 Outline::set_outline_color (c);
205 end_visual_change ();
210 WaveView::set_samples_per_pixel (double samples_per_pixel)
212 if (samples_per_pixel != _samples_per_pixel) {
215 invalidate_image_cache ();
216 _samples_per_pixel = samples_per_pixel;
217 _bounding_box_dirty = true;
224 _log_meter (float power, double lower_db, double upper_db, double non_linearity)
226 return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
230 alt_log_meter (float power)
232 return _log_meter (power, -192.0, 0.0, 8.0);
236 WaveView::set_clip_level (double dB)
238 const double clip_level = dB_to_coefficient (dB);
239 if (clip_level != _clip_level) {
240 _clip_level = clip_level;
246 WaveView::invalidate_image_cache ()
248 cancel_my_render_request ();
249 _current_image.reset ();
253 WaveView::y_extent (double s, bool /*round_to_lower_edge*/) const
255 /* it is important that this returns an integral value, so that we
256 * can ensure correct single pixel behaviour.
258 * we need (_height - max(wave_line_width))
259 * wave_line_width == 1 IFF top==bottom (1 sample per pixel or flat line)
260 * wave_line_width == 2 otherwise
261 * then round away from the zero line, towards peak
263 if (_shape == Rectified) {
264 // we only ever have 1 point and align to the bottom (not center)
265 return floor ((1.0 - s) * (_height - 2.0));
267 /* currently canvas rectangle is off-by-one and we
268 * cannot draw a pixel at 0 (-.5 .. +.5) without it being
269 * clipped. A value 1.0 (ideally one point at y=0) ends
270 * up a pixel down. and a value of -1.0 (ideally y = _height-1)
271 * currently is on the bottom separator line :(
272 * So to make the complete waveform appear centered in
273 * a region, we translate by +.5 (instead of -.5)
274 * and waste two pixel of height: -4 (instad of -2)
276 * This needs fixing in canvas/rectangle the intersect
277 * functions and probably a couple of other places as well...
281 pos = ceil ((1.0 - s) * .5 * (_height - 4.0));
283 pos = floor ((1.0 - s) * .5 * (_height - 4.0));
285 return min (_height - 4.0, (max (0.0, pos)));
290 WaveView::draw_absent_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
292 Cairo::RefPtr<Cairo::ImageSurface> stripe = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
294 Cairo::RefPtr<Cairo::Context> stripe_context = Cairo::Context::create (stripe);
295 stripe_context->set_antialias (Cairo::ANTIALIAS_NONE);
297 uint32_t stripe_separation = 150;
298 double start = - floor (_height / stripe_separation) * stripe_separation;
301 while (start < n_peaks) {
303 stripe_context->move_to (start, 0);
304 stripe_x = start + _height;
305 stripe_context->line_to (stripe_x, _height);
306 start += stripe_separation;
309 stripe_context->set_source_rgba (1.0, 1.0, 1.0, 1.0);
310 stripe_context->set_line_cap (Cairo::LINE_CAP_SQUARE);
311 stripe_context->set_line_width(50);
312 stripe_context->stroke();
314 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
316 context->set_source_rgba (1.0, 1.0, 0.0, 0.3);
317 context->mask (stripe, 0, 0);
328 LineTips() : top (0.0), bot (0.0), clip_max (false), clip_min (false) {}
332 Cairo::RefPtr<Cairo::ImageSurface> wave;
333 Cairo::RefPtr<Cairo::ImageSurface> outline;
334 Cairo::RefPtr<Cairo::ImageSurface> clip;
335 Cairo::RefPtr<Cairo::ImageSurface> zero;
338 wave (0), outline (0), clip (0), zero (0) {}
342 WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks, boost::shared_ptr<WaveViewThreadRequest> req) const
347 images.wave = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
348 images.outline = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
349 images.clip = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
350 images.zero = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
352 Cairo::RefPtr<Cairo::Context> wave_context = Cairo::Context::create (images.wave);
353 Cairo::RefPtr<Cairo::Context> outline_context = Cairo::Context::create (images.outline);
354 Cairo::RefPtr<Cairo::Context> clip_context = Cairo::Context::create (images.clip);
355 Cairo::RefPtr<Cairo::Context> zero_context = Cairo::Context::create (images.zero);
356 wave_context->set_antialias (Cairo::ANTIALIAS_NONE);
357 outline_context->set_antialias (Cairo::ANTIALIAS_NONE);
358 clip_context->set_antialias (Cairo::ANTIALIAS_NONE);
359 zero_context->set_antialias (Cairo::ANTIALIAS_NONE);
361 boost::scoped_array<LineTips> tips (new LineTips[n_peaks]);
363 /* Clip level nominally set to -0.9dBFS to account for inter-sample
364 interpolation possibly clipping (value may be too low).
366 We adjust by the region's own gain (but note: not by any gain
367 automation or its gain envelope) so that clip indicators are closer
368 to providing data about on-disk data. This multiplication is
369 needed because the data we get from AudioRegion::read_peaks()
370 has been scaled by scale_amplitude() already.
373 const double clip_level = _clip_level * _region_amplitude;
375 if (_shape == WaveView::Rectified) {
377 /* each peak is a line from the bottom of the waveview
378 * to a point determined by max (_peaks[i].max,
383 for (int i = 0; i < n_peaks; ++i) {
385 tips[i].bot = height() - 1.0;
386 const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
387 tips[i].top = y_extent (p, false);
388 tips[i].spread = p * (_height - 1.0);
390 if (_peaks[i].max >= clip_level) {
391 tips[i].clip_max = true;
394 if (-(_peaks[i].min) >= clip_level) {
395 tips[i].clip_min = true;
400 for (int i = 0; i < n_peaks; ++i) {
402 tips[i].bot = height() - 1.0;
403 const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
404 tips[i].top = y_extent (p, false);
405 tips[i].spread = p * (_height - 2.0);
406 if (p >= clip_level) {
407 tips[i].clip_max = true;
416 for (int i = 0; i < n_peaks; ++i) {
417 double top = _peaks[i].max;
418 double bot = _peaks[i].min;
420 if (_peaks[i].max >= clip_level) {
421 tips[i].clip_max = true;
423 if (-(_peaks[i].min) >= clip_level) {
424 tips[i].clip_min = true;
428 top = alt_log_meter (fast_coefficient_to_dB (top));
429 } else if (top < 0.0) {
430 top =-alt_log_meter (fast_coefficient_to_dB (-top));
436 bot = alt_log_meter (fast_coefficient_to_dB (bot));
437 } else if (bot < 0.0) {
438 bot = -alt_log_meter (fast_coefficient_to_dB (-bot));
443 tips[i].top = y_extent (top, false);
444 tips[i].bot = y_extent (bot, true);
445 tips[i].spread = tips[i].bot - tips[i].top;
449 for (int i = 0; i < n_peaks; ++i) {
450 if (_peaks[i].max >= clip_level) {
451 tips[i].clip_max = true;
453 if (-(_peaks[i].min) >= clip_level) {
454 tips[i].clip_min = true;
457 tips[i].top = y_extent (_peaks[i].max, false);
458 tips[i].bot = y_extent (_peaks[i].min, true);
459 tips[i].spread = tips[i].bot - tips[i].top;
465 if (req->should_stop()) {
469 Color alpha_one = rgba_to_color (0, 0, 0, 1.0);
471 set_source_rgba (wave_context, alpha_one);
472 set_source_rgba (outline_context, alpha_one);
473 set_source_rgba (clip_context, alpha_one);
474 set_source_rgba (zero_context, alpha_one);
476 /* ensure single-pixel lines */
478 wave_context->set_line_width (1.0);
479 wave_context->translate (0.5, +1.5);
481 outline_context->set_line_width (1.0);
482 outline_context->translate (0.5, +1.5);
484 clip_context->set_line_width (1.0);
485 clip_context->translate (0.5, +1.5);
487 zero_context->set_line_width (1.0);
488 zero_context->translate (0.5, +1.5);
490 /* the height of the clip-indicator should be at most 7 pixels,
491 * or 5% of the height of the waveview item.
494 const double clip_height = min (7.0, ceil (_height * 0.05));
496 /* There are 3 possible components to draw at each x-axis position: the
497 waveform "line", the zero line and an outline/clip indicator. We
498 have to decide which of the 3 to draw at each position, pixel by
499 pixel. This makes the rendering less efficient but it is the only
500 way I can see to do this correctly.
502 To avoid constant source swapping and stroking, we draw the components separately
503 onto four alpha only image surfaces for use as a mask.
505 With only 1 pixel of spread between the top and bottom of the line,
506 we just draw the upper outline/clip indicator.
508 With 2 pixels of spread, we draw the upper and lower outline clip
511 With 3 pixels of spread we draw the upper and lower outline/clip
512 indicators and at least 1 pixel of the waveform line.
514 With 5 pixels of spread, we draw all components.
516 We can do rectified as two separate passes because we have a much
517 easier decision regarding whether to draw the waveform line. We
518 always draw the clip/outline indicators.
521 if (_shape == WaveView::Rectified) {
523 for (int i = 0; i < n_peaks; ++i) {
527 if (tips[i].spread >= 1.0) {
528 wave_context->move_to (i, tips[i].top);
529 wave_context->line_to (i, tips[i].bot);
534 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
535 clip_context->move_to (i, tips[i].top);
536 /* clip-indicating upper terminal line */
537 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + .5)));
539 outline_context->move_to (i, tips[i].top);
540 /* normal upper terminal dot */
541 outline_context->rel_line_to (0, -1.0);
545 wave_context->stroke ();
546 clip_context->stroke ();
547 outline_context->stroke ();
550 const double height_2 = (_height - 2.5) * .5;
552 for (int i = 0; i < n_peaks; ++i) {
556 if (tips[i].spread >= 2.0) {
557 wave_context->move_to (i, tips[i].top);
558 wave_context->line_to (i, tips[i].bot);
560 /* draw square waves and other discontiguous points clearly */
562 if (tips[i-1].top + 2 < tips[i].top) {
563 wave_context->move_to (i-1, tips[i-1].top);
564 wave_context->line_to (i-1, (tips[i].bot + tips[i-1].top)/2);
565 wave_context->move_to (i, (tips[i].bot + tips[i-1].top)/2);
566 wave_context->line_to (i, tips[i].top);
567 } else if (tips[i-1].bot > tips[i].bot + 2) {
568 wave_context->move_to (i-1, tips[i-1].bot);
569 wave_context->line_to (i-1, (tips[i].top + tips[i-1].bot)/2);
570 wave_context->move_to (i, (tips[i].top + tips[i-1].bot)/2);
571 wave_context->line_to (i, tips[i].bot);
577 if (tips[i].spread >= 5.0 && show_zero_line()) {
578 zero_context->move_to (i, floor(height_2));
579 zero_context->rel_line_to (1.0, 0);
582 if (tips[i].spread > 1.0) {
583 bool clipped = false;
584 /* outline/clip indicators */
585 if (_global_show_waveform_clipping && tips[i].clip_max) {
586 clip_context->move_to (i, tips[i].top);
587 /* clip-indicating upper terminal line */
588 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + 0.5)));
592 if (_global_show_waveform_clipping && tips[i].clip_min) {
593 clip_context->move_to (i, tips[i].bot);
594 /* clip-indicating lower terminal line */
595 clip_context->rel_line_to (0, - min (clip_height, ceil(tips[i].spread + 0.5)));
600 outline_context->move_to (i, tips[i].bot + 1.0);
601 /* normal lower terminal dot */
602 outline_context->rel_line_to (0, -1.0);
604 outline_context->move_to (i, tips[i].top - 1.0);
605 /* normal upper terminal dot */
606 outline_context->rel_line_to (0, 1.0);
609 bool clipped = false;
610 /* outline/clip indicator */
611 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
612 clip_context->move_to (i, tips[i].top);
613 /* clip-indicating upper / lower terminal line */
614 clip_context->rel_line_to (0, 1.0);
619 wave_context->move_to (i, tips[i].top);
620 /* special case where outline only is drawn.
621 * we draw a 1px "line", pretending that the span is 1.0
623 wave_context->rel_line_to (0, 1.0);
628 wave_context->stroke ();
629 outline_context->stroke ();
630 clip_context->stroke ();
631 zero_context->stroke ();
634 if (req->should_stop()) {
638 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
640 /* Here we set a source colour and use the various components as a mask. */
642 if (gradient_depth() != 0.0) {
644 Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _height));
650 if (_shape == Rectified) {
660 color_to_rgba (_fill_color, r, g, b, a);
661 gradient->add_color_stop_rgba (stops[1], r, g, b, a);
662 /* generate a new color for the middle of the gradient */
664 color_to_hsv (_fill_color, h, s, v);
665 /* change v towards white */
666 v *= 1.0 - gradient_depth();
667 Color center = hsva_to_color (h, s, v, a);
668 color_to_rgba (center, r, g, b, a);
670 gradient->add_color_stop_rgba (stops[0], r, g, b, a);
671 gradient->add_color_stop_rgba (stops[2], r, g, b, a);
673 context->set_source (gradient);
675 set_source_rgba (context, _fill_color);
678 if (req->should_stop()) {
682 context->mask (images.wave, 0, 0);
685 set_source_rgba (context, _outline_color);
686 context->mask (images.outline, 0, 0);
689 set_source_rgba (context, _clip_color);
690 context->mask (images.clip, 0, 0);
693 set_source_rgba (context, _zero_color);
694 context->mask (images.zero, 0, 0);
698 boost::shared_ptr<WaveViewCache::Entry>
699 WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) const
701 boost::shared_ptr<WaveViewCache::Entry> ret (new WaveViewCache::Entry (req->channel,
703 req->region_amplitude,
705 req->samples_per_pixel,
710 images = new WaveViewCache;
713 images->add (_region->audio_source (_channel), ret);
715 /* consolidate cache first (removes fully-contained
719 images->consolidate_image_cache (_region->audio_source (_channel),
720 _channel, _height, _region_amplitude,
721 _fill_color, _samples_per_pixel);
726 boost::shared_ptr<WaveViewCache::Entry>
727 WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
729 boost::shared_ptr<WaveViewCache::Entry> ret;
733 /* this is called from a ::render() call, when we need an image to
737 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 needs image from %2 .. %3\n", name, start, end));
741 Glib::Threads::Mutex::Lock lmq (request_queue_lock);
743 /* if there's a draw request outstanding, check to see if we
744 * have an image there. if so, use it (and put it in the cache
748 if (current_request && !current_request->should_stop() && current_request->image) {
750 /* put the image into the cache so that other
751 * WaveViews can use it if it is useful
754 if (current_request->start <= start && current_request->end >= end) {
756 ret.reset (new WaveViewCache::Entry (current_request->channel,
757 current_request->height,
758 current_request->region_amplitude,
759 current_request->fill_color,
760 current_request->samples_per_pixel,
761 current_request->start,
762 current_request->end,
763 current_request->image));
765 cache_request_result (current_request);
766 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: got image from completed request, spans %2..%3\n",
767 name, current_request->start, current_request->end));
770 /* drop our handle on the current request */
771 current_request.reset ();
777 /* no current image draw request, so look in the cache */
779 ret = get_image_from_cache (start, end, full_image);
780 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: lookup from cache gave %2 (full %3)\n",
781 name, ret, full_image));
787 if (!ret || !full_image) {
789 if ((rendered && get_image_in_thread) || always_get_image_in_thread) {
791 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: generating image in caller thread\n", name));
793 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
795 req->type = WaveViewThreadRequest::Draw;
798 req->samples_per_pixel = _samples_per_pixel;
799 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
800 req->channel = _channel;
801 req->width = _canvas->visible_area().width();
802 req->height = _height;
803 req->fill_color = _fill_color;
804 req->region_amplitude = _region_amplitude;
806 /* draw image in this (the GUI thread) */
808 generate_image (req, false);
810 /* cache the result */
812 ret = cache_request_result (req);
814 /* reset this so that future missing images are
815 * generated in a a worker thread.
818 get_image_in_thread = false;
821 queue_get_image (_region, start, end);
826 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 got an image from %2 .. %3 (full ? %4)\n", name, ret->start, ret->end, full_image));
828 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 no useful image available\n", name));
834 boost::shared_ptr<WaveViewCache::Entry>
835 WaveView::get_image_from_cache (framepos_t start, framepos_t end, bool& full) const
838 return boost::shared_ptr<WaveViewCache::Entry>();
841 return images->lookup_image (_region->audio_source (_channel), start, end, _channel,
842 _height, _region_amplitude, _fill_color, _samples_per_pixel, full);
846 WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, framepos_t start, framepos_t end) const
848 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
850 req->type = WaveViewThreadRequest::Draw;
853 req->samples_per_pixel = _samples_per_pixel;
854 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
855 req->channel = _channel;
856 req->width = _canvas->visible_area().width();
857 req->height = _height;
858 req->fill_color = _fill_color;
859 req->region_amplitude = _region_amplitude;
865 WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_render_thread) const
867 if (!req->should_stop()) {
869 /* sample position is canonical here, and we want to generate
870 * an image that spans about twice the canvas width
873 const framepos_t center = req->start + ((req->end - req->start) / 2);
874 const framecnt_t image_samples = req->width * req->samples_per_pixel; /* one canvas width */
876 /* we can request data from anywhere in the Source, between 0 and its length
879 framepos_t sample_start = max (_region_start, (center - image_samples));
880 framepos_t sample_end = min (center + image_samples, region_end());
881 const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
883 boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
885 /* Note that Region::read_peaks() takes a start position based on an
886 offset into the Region's **SOURCE**, rather than an offset into
890 framecnt_t peaks_read = _region->read_peaks (peaks.get(), n_peaks,
891 sample_start, sample_end - sample_start,
893 req->samples_per_pixel);
895 // apply waveform amplitude zoom multiplier
897 req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
898 /* make sure we record the sample positions that were actually used */
899 req->start = sample_start;
900 req->end = sample_end;
902 if (peaks_read > 0) {
904 for (framecnt_t i = 0; i < n_peaks; ++i) {
905 peaks[i].max *= _amplitude_above_axis;
906 peaks[i].min *= _amplitude_above_axis;
909 draw_image (req->image, peaks.get(), n_peaks, req);
911 draw_absent_image (req->image, peaks.get(), n_peaks);
915 if (in_render_thread && !req->should_stop()) {
916 const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
922 /** Given a waveform that starts at window x-coordinate @param wave_origin
923 * and the first pixel that we will actually draw @param draw_start, return
924 * the offset into an image of the entire waveform that we will need to use.
926 * Note: most of our cached images are NOT of the entire waveform, this is just
927 * computationally useful when determining which the sample range span for
931 window_to_image (double wave_origin, double image_start)
933 return image_start - wave_origin;
937 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
939 assert (_samples_per_pixel != 0);
945 /* a WaveView is intimately connected to an AudioRegion. It will
946 * display the waveform within the region, anywhere from the start of
947 * the region to its end.
949 * the area we've been aked to render may overlap with area covered
950 * by the region in any of the normal ways:
952 * - it may begin and end within the area covered by the region
953 * - it may start before and end after the area covered by region
954 * - it may start before and end within the area covered by the region
955 * - it may start within and end after the area covered by the region
956 * - it may be precisely coincident with the area covered by region.
958 * So let's start by determining the area covered by the region, in
959 * window coordinates. It begins at zero (in item coordinates for this
960 * waveview, and extends to region_length() / _samples_per_pixel.
963 Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
965 // cerr << name << " RENDER " << area << " self = " << self << endl;
967 /* Now lets get the intersection with the area we've been asked to draw */
969 boost::optional<Rect> d = self.intersection (area);
977 /* "draw" is now a rectangle that defines the rectangle we need to
978 * update/render the waveview into, in window coordinate space.
981 /* window coordinates - pixels where x=0 is the left edge of the canvas
982 * window. We round down in case we were asked to
983 * draw "between" pixels at the start and/or end.
986 double draw_start = floor (draw.x0);
987 const double draw_end = floor (draw.x1);
989 // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
991 /* image coordnates: pixels where x=0 is the start of this waveview,
992 * wherever it may be positioned. thus image_start=N means "an image
993 * that begins N pixels after the start of region that this waveview is
997 const framepos_t image_start = window_to_image (self.x0, draw_start);
998 const framepos_t image_end = window_to_image (self.x0, draw_end);
1000 // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
1002 /* sample coordinates - note, these are not subject to rounding error
1004 * "sample_start = N" means "the first sample we need to represent is N
1005 * samples after the first sample of the region"
1008 framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
1009 framepos_t sample_end = _region_start + (image_end * _samples_per_pixel);
1011 // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
1013 /* sample_start and sample_end are bounded by the region
1014 * limits. sample_start, because of the was just computed, must already
1015 * be greater than or equal to the _region_start value.
1018 sample_end = min (region_end(), sample_end);
1020 // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
1022 double image_origin_in_self_coordinates;
1023 boost::shared_ptr<WaveViewCache::Entry> image_to_draw;
1025 if (_current_image) {
1027 /* check it covers the right sample range */
1029 if (_current_image->start > sample_start || _current_image->end < sample_end) {
1030 /* doesn't cover the area we need ... reset */
1031 _current_image.reset ();
1033 /* timestamp our continuing use of this image/cache entry */
1034 images->use (_region->audio_source (_channel), _current_image);
1035 image_to_draw = _current_image;
1039 if (!image_to_draw) {
1044 image_to_draw = get_image (sample_start, sample_end, full_image);
1046 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 image to draw = %2 (full? %3)\n", name, image_to_draw, full_image));
1048 if (!image_to_draw) {
1049 /* image not currently available. A redraw will be scheduled
1056 /* found an image that covers our entire sample range,
1057 * so keep a reference to it.
1059 _current_image = image_to_draw;
1063 /* compute the first pixel of the image that should be used when we
1064 * render the specified range.
1067 image_origin_in_self_coordinates = (image_to_draw->start - _region_start) / _samples_per_pixel;
1069 if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
1070 /* we are going to draw the first pixel for this region, but
1071 we may not want this to overlap a border around the
1072 waveform. If so, _start_shift will be set.
1074 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
1075 //draw_start += _start_shift;
1076 //image_origin_in_self_coordinates += _start_shift;
1079 /* the image may only be a best-effort ... it may not span the entire
1080 * range requested, though it is guaranteed to cover the start. So
1081 * determine how many pixels we can actually draw.
1086 if (image_to_draw != _current_image) {
1088 /* the image is guaranteed to start at or before
1089 * draw_start. But if it starts before draw_start, that reduces
1090 * the maximum available width we can render with.
1092 * so .. clamp the draw width to the smaller of what we need to
1093 * draw or the available width of the image.
1096 draw_width = min ((double) image_to_draw->image->get_width() - (draw_start - image_to_draw->start),
1097 (draw_end - draw_start));
1100 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 draw just %2 of %3 (iwidth %4 off %5 img @ %6 rs @ %7)\n", name, draw_width, (draw_end - draw_start),
1101 image_to_draw->image->get_width(), image_origin_in_self_coordinates,
1102 image_to_draw->start, _region_start));
1104 draw_width = draw_end - draw_start;
1105 DEBUG_TRACE (DEBUG::WaveView, string_compose ("use current image, span entire render width %1..%2\n", draw_start, draw_end));
1108 context->rectangle (draw_start, draw.y0, draw_width, draw.height());
1110 /* round image origin position to an exact pixel in device space to
1114 double x = self.x0 + image_origin_in_self_coordinates;
1116 context->user_to_device (x, y);
1119 context->device_to_user (x, y);
1121 /* the coordinates specify where in "user coordinates" (i.e. what we
1122 * generally call "canvas coordinates" in this code) the image origin
1123 * will appear. So specifying (10,10) will put the upper left corner of
1124 * the image at (10,10) in user space.
1127 context->set_source (image_to_draw->image, x, y);
1130 /* image obtained, some of it painted to display: we are rendered.
1131 Future calls to get_image_in_thread are now meaningful.
1138 WaveView::compute_bounding_box () const
1141 _bounding_box = Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height);
1143 _bounding_box = boost::optional<Rect> ();
1146 _bounding_box_dirty = false;
1150 WaveView::set_height (Distance height)
1152 if (height != _height) {
1155 invalidate_image_cache ();
1157 get_image_in_thread = true;
1159 _bounding_box_dirty = true;
1165 WaveView::set_channel (int channel)
1167 if (channel != _channel) {
1170 invalidate_image_cache ();
1173 _bounding_box_dirty = true;
1179 WaveView::set_logscaled (bool yn)
1181 if (_logscaled != yn) {
1182 begin_visual_change ();
1183 invalidate_image_cache ();
1185 end_visual_change ();
1190 WaveView::gain_changed ()
1192 begin_visual_change ();
1193 invalidate_image_cache ();
1194 _region_amplitude = _region->scale_amplitude ();
1195 end_visual_change ();
1199 WaveView::set_zero_color (Color c)
1201 if (_zero_color != c) {
1202 begin_visual_change ();
1203 invalidate_image_cache ();
1205 end_visual_change ();
1210 WaveView::set_clip_color (Color c)
1212 if (_clip_color != c) {
1213 begin_visual_change ();
1214 invalidate_image_cache ();
1216 end_visual_change ();
1221 WaveView::set_show_zero_line (bool yn)
1223 if (_show_zero != yn) {
1224 begin_visual_change ();
1225 invalidate_image_cache ();
1227 end_visual_change ();
1232 WaveView::set_shape (Shape s)
1235 begin_visual_change ();
1236 invalidate_image_cache ();
1238 end_visual_change ();
1243 WaveView::set_amplitude_above_axis (double a)
1245 if (fabs (_amplitude_above_axis - a) > 0.01) {
1246 begin_visual_change ();
1247 invalidate_image_cache ();
1248 _amplitude_above_axis = a;
1249 end_visual_change ();
1254 WaveView::set_global_shape (Shape s)
1256 if (_global_shape != s) {
1258 VisualPropertiesChanged (); /* EMIT SIGNAL */
1263 WaveView::set_global_logscaled (bool yn)
1265 if (_global_logscaled != yn) {
1266 _global_logscaled = yn;
1267 VisualPropertiesChanged (); /* EMIT SIGNAL */
1272 WaveView::region_length() const
1274 return _region->length() - (_region_start - _region->start());
1278 WaveView::region_end() const
1280 return _region_start + region_length();
1284 WaveView::set_region_start (frameoffset_t start)
1290 if (_region_start == start) {
1295 _region_start = start;
1296 _bounding_box_dirty = true;
1301 WaveView::region_resized ()
1303 /* Called when the region start or end (thus length) has changed.
1311 _region_start = _region->start();
1312 _bounding_box_dirty = true;
1317 WaveView::set_global_gradient_depth (double depth)
1319 if (_global_gradient_depth != depth) {
1320 _global_gradient_depth = depth;
1321 VisualPropertiesChanged (); /* EMIT SIGNAL */
1326 WaveView::set_global_show_waveform_clipping (bool yn)
1328 if (_global_show_waveform_clipping != yn) {
1329 _global_show_waveform_clipping = yn;
1330 ClipLevelChanged ();
1335 WaveView::set_start_shift (double pixels)
1341 begin_visual_change ();
1342 _start_shift = pixels;
1343 end_visual_change ();
1348 WaveView::cancel_my_render_request () const
1354 /* try to stop any current rendering of the request, or prevent it from
1358 if (current_request) {
1359 current_request->cancel ();
1362 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1364 /* now remove it from the queue and reset our request pointer so that
1365 have no outstanding request (that we know about)
1368 request_queue.erase (this);
1369 current_request.reset ();
1373 WaveView::send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1375 if (req->type == WaveViewThreadRequest::Draw && current_request) {
1376 /* this will stop rendering in progress (which might otherwise
1377 be long lived) for any current request.
1379 current_request->cancel ();
1382 start_drawing_thread ();
1384 Glib::signal_idle().connect (sigc::bind (sigc::mem_fun (*this, &WaveView::idle_send_request), req));
1388 WaveView::idle_send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1391 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1392 /* swap requests (protected by lock) */
1393 current_request = req;
1394 request_queue.insert (this);
1397 request_cond.signal (); /* wake thread */
1399 return false; /* do not call from idle again */
1402 /*-------------------------------------------------*/
1405 WaveView::start_drawing_thread ()
1407 if (!_drawing_thread) {
1408 _drawing_thread = Glib::Threads::Thread::create (sigc::ptr_fun (WaveView::drawing_thread));
1413 WaveView::stop_drawing_thread ()
1415 if (_drawing_thread) {
1416 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1417 g_atomic_int_set (&drawing_thread_should_quit, 1);
1418 request_cond.signal ();
1423 WaveView::drawing_thread ()
1425 using namespace Glib::Threads;
1427 WaveView const * requestor;
1428 Mutex::Lock lm (request_queue_lock);
1433 /* remember that we hold the lock at this point, no matter what */
1435 if (g_atomic_int_get (&drawing_thread_should_quit)) {
1439 if (request_queue.empty()) {
1440 request_cond.wait (request_queue_lock);
1443 /* remove the request from the queue (remember: the "request"
1444 * is just a pointer to a WaveView object)
1447 requestor = *(request_queue.begin());
1448 request_queue.erase (request_queue.begin());
1450 boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
1456 /* Generate an image. Unlock the request queue lock
1457 * while we do this, so that other things can happen
1458 * as we do rendering.
1461 request_queue_lock.unlock (); /* some RAII would be good here */
1464 requestor->generate_image (req, true);
1466 req->image.clear(); /* just in case it was set before the exception, whatever it was */
1469 request_queue_lock.lock ();
1471 req.reset (); /* drop/delete request as appropriate */
1474 /* thread is vanishing */
1475 _drawing_thread = 0;
1478 /*-------------------------------------------------*/
1480 WaveViewCache::WaveViewCache ()
1481 : image_cache_size (0)
1482 , _image_cache_threshold (100 * 1048576) /* bytes */
1486 WaveViewCache::~WaveViewCache ()
1491 boost::shared_ptr<WaveViewCache::Entry>
1492 WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
1493 framepos_t start, framepos_t end,
1498 double samples_per_pixel,
1499 bool& full_coverage)
1501 ImageCache::iterator x;
1503 if ((x = cache_map.find (src)) == cache_map.end ()) {
1504 /* nothing in the cache for this audio source at all */
1505 return boost::shared_ptr<WaveViewCache::Entry> ();
1508 CacheLine& caches = x->second;
1509 boost::shared_ptr<Entry> best_partial;
1510 framecnt_t max_coverage = 0;
1512 /* Find a suitable ImageSurface, if it exists.
1515 for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
1517 boost::shared_ptr<Entry> e (*c);
1519 if (channel != e->channel
1520 || height != e->height
1521 || amplitude != e->amplitude
1522 || samples_per_pixel != e->samples_per_pixel
1523 || fill_color != e->fill_color) {
1527 if (end <= e->end && start >= e->start) {
1528 /* found an image that covers the range we need */
1529 DEBUG_TRACE (DEBUG::WaveView, string_compose ("found image spanning %1..%2 covers %3..%4\n",
1530 e->start, e->end, start, end));
1532 full_coverage = true;
1536 if (start >= e->start) {
1537 /* found an image that covers the start, but not the
1538 * end. See if it is longer than any other similar
1539 * partial image that we've found so far.
1542 if ((e->end - e->start) > max_coverage) {
1544 max_coverage = e->end - e->start;
1550 DEBUG_TRACE (DEBUG::WaveView, string_compose ("found PARTIAL image spanning %1..%2 partially covers %3..%4\n",
1551 best_partial->start, best_partial->end, start, end));
1552 use (src, best_partial);
1553 full_coverage = false;
1554 return best_partial;
1557 return boost::shared_ptr<Entry> ();
1561 WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> src,
1566 double samples_per_pixel)
1568 list <uint32_t> deletion_list;
1569 uint32_t other_entries = 0;
1570 ImageCache::iterator x;
1572 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1574 if ((x = cache_map.find (src)) == cache_map.end ()) {
1578 CacheLine& caches = x->second;
1580 for (CacheLine::iterator c1 = caches.begin(); c1 != caches.end(); ) {
1582 CacheLine::iterator nxt = c1;
1585 boost::shared_ptr<Entry> e1 (*c1);
1587 if (channel != e1->channel
1588 || height != e1->height
1589 || amplitude != e1->amplitude
1590 || samples_per_pixel != e1->samples_per_pixel
1591 || fill_color != e1->fill_color) {
1593 /* doesn't match current properties, ignore and move on
1602 /* c1 now points to a cached image entry that matches current
1603 * properties. Check all subsequent cached imaged entries to
1604 * see if there are others that also match but represent
1605 * subsets of the range covered by this one.
1608 for (CacheLine::iterator c2 = c1; c2 != caches.end(); ) {
1610 CacheLine::iterator nxt2 = c2;
1613 boost::shared_ptr<Entry> e2 (*c2);
1615 if (e1 == e2 || channel != e2->channel
1616 || height != e2->height
1617 || amplitude != e2->amplitude
1618 || samples_per_pixel != e2->samples_per_pixel
1619 || fill_color != e2->fill_color) {
1621 /* properties do not match, ignore for the
1622 * purposes of consolidation.
1628 if (e2->start >= e1->start && e2->end <= e1->end) {
1629 /* c2 is fully contained by c1, so delete it */
1630 c2 = caches.erase (c2);
1642 WaveViewCache::use (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1644 ce->timestamp = g_get_monotonic_time ();
1648 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1650 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1652 Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
1654 image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1660 ce->timestamp = g_get_monotonic_time ();
1662 cache_map[src].push_back (ce);
1663 cache_list.push_back (make_pair (src, ce));
1667 WaveViewCache::compute_image_cache_size()
1670 for (ImageCache::iterator s = cache_map.begin(); s != cache_map.end(); ++s) {
1671 CacheLine& per_source_cache (s->second);
1672 for (CacheLine::iterator c = per_source_cache.begin(); c != per_source_cache.end(); ++c) {
1673 Cairo::RefPtr<Cairo::ImageSurface> img ((*c)->image);
1674 total += img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1681 WaveViewCache::cache_full()
1683 return image_cache_size > _image_cache_threshold;
1687 WaveViewCache::cache_flush ()
1689 SortByTimestamp sorter;
1691 /* sort list in LRU order */
1693 sort (cache_list.begin(), cache_list.end(), sorter);
1695 while (image_cache_size > _image_cache_threshold) {
1697 ListEntry& le (cache_list.front());
1699 ImageCache::iterator x;
1701 if ((x = cache_map.find (le.first)) == cache_map.end ()) {
1702 /* wierd ... no entry for this AudioSource */
1706 CacheLine& cl = x->second;
1708 for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
1710 if (*c == le.second) {
1712 /* Remove this entry from this cache line */
1716 /* remove cache line from main cache: no more entries */
1717 cache_map.erase (x);
1724 Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
1725 uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1727 if (image_cache_size > size) {
1728 image_cache_size -= size;
1730 image_cache_size = 0;
1733 /* Remove from the linear list */
1734 cache_list.erase (cache_list.begin());
1739 WaveViewCache::set_image_cache_threshold (uint64_t sz)
1741 _image_cache_threshold = sz;