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 ())
91 , _region_start (region->start())
92 , get_image_in_thread (false)
93 , always_get_image_in_thread (false)
96 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
97 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
99 ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
102 WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
106 , _samples_per_pixel (0)
109 , _zero_color (0xff0000ff)
110 , _clip_color (0xff0000ff)
111 , _logscaled (_global_logscaled)
112 , _shape (_global_shape)
113 , _gradient_depth (_global_gradient_depth)
114 , _shape_independent (false)
115 , _logscaled_independent (false)
116 , _gradient_depth_independent (false)
117 , _amplitude_above_axis (1.0)
118 , _region_amplitude (region->scale_amplitude ())
120 , idle_queued (false)
121 , _region_start (region->start())
122 , get_image_in_thread (false)
123 , always_get_image_in_thread (false)
126 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
127 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
129 ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
132 WaveView::~WaveView ()
134 invalidate_image_cache ();
138 WaveView::debug_name() const
140 return _region->name() + string (":") + PBD::to_string (_channel+1, std::dec);
144 WaveView::image_ready ()
150 WaveView::set_always_get_image_in_thread (bool yn)
152 always_get_image_in_thread = yn;
156 WaveView::handle_visual_property_change ()
158 bool changed = false;
160 if (!_shape_independent && (_shape != global_shape())) {
161 _shape = global_shape();
165 if (!_logscaled_independent && (_logscaled != global_logscaled())) {
166 _logscaled = global_logscaled();
170 if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
171 _gradient_depth = global_gradient_depth();
176 begin_visual_change ();
177 invalidate_image_cache ();
178 end_visual_change ();
183 WaveView::handle_clip_level_change ()
185 begin_visual_change ();
186 invalidate_image_cache ();
187 end_visual_change ();
191 WaveView::set_fill_color (Color c)
193 if (c != _fill_color) {
194 begin_visual_change ();
195 invalidate_image_cache ();
196 Fill::set_fill_color (c);
197 end_visual_change ();
202 WaveView::set_outline_color (Color c)
204 if (c != _outline_color) {
205 begin_visual_change ();
206 invalidate_image_cache ();
207 Outline::set_outline_color (c);
208 end_visual_change ();
213 WaveView::set_samples_per_pixel (double samples_per_pixel)
215 if (samples_per_pixel != _samples_per_pixel) {
218 invalidate_image_cache ();
219 _samples_per_pixel = samples_per_pixel;
220 _bounding_box_dirty = true;
227 _log_meter (float power, double lower_db, double upper_db, double non_linearity)
229 return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
233 alt_log_meter (float power)
235 return _log_meter (power, -192.0, 0.0, 8.0);
239 WaveView::set_clip_level (double dB)
241 const double clip_level = dB_to_coefficient (dB);
242 if (clip_level != _clip_level) {
243 _clip_level = clip_level;
249 WaveView::invalidate_image_cache ()
251 cancel_my_render_request ();
252 _current_image.reset ();
256 WaveView::y_extent (double s, bool /*round_to_lower_edge*/) const
258 /* it is important that this returns an integral value, so that we
259 * can ensure correct single pixel behaviour.
261 * we need (_height - max(wave_line_width))
262 * wave_line_width == 1 IFF top==bottom (1 sample per pixel or flat line)
263 * wave_line_width == 2 otherwise
264 * then round away from the zero line, towards peak
266 if (_shape == Rectified) {
267 // we only ever have 1 point and align to the bottom (not center)
268 return floor ((1.0 - s) * (_height - 2.0));
270 /* currently canvas rectangle is off-by-one and we
271 * cannot draw a pixel at 0 (-.5 .. +.5) without it being
272 * clipped. A value 1.0 (ideally one point at y=0) ends
273 * up a pixel down. and a value of -1.0 (ideally y = _height-1)
274 * currently is on the bottom separator line :(
275 * So to make the complete waveform appear centered in
276 * a region, we translate by +.5 (instead of -.5)
277 * and waste two pixel of height: -4 (instad of -2)
279 * This needs fixing in canvas/rectangle the intersect
280 * functions and probably a couple of other places as well...
284 pos = ceil ((1.0 - s) * .5 * (_height - 4.0));
286 pos = floor ((1.0 - s) * .5 * (_height - 4.0));
288 return min (_height - 4.0, (max (0.0, pos)));
293 WaveView::draw_absent_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
295 Cairo::RefPtr<Cairo::ImageSurface> stripe = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
297 Cairo::RefPtr<Cairo::Context> stripe_context = Cairo::Context::create (stripe);
298 stripe_context->set_antialias (Cairo::ANTIALIAS_NONE);
300 uint32_t stripe_separation = 150;
301 double start = - floor (_height / stripe_separation) * stripe_separation;
304 while (start < n_peaks) {
306 stripe_context->move_to (start, 0);
307 stripe_x = start + _height;
308 stripe_context->line_to (stripe_x, _height);
309 start += stripe_separation;
312 stripe_context->set_source_rgba (1.0, 1.0, 1.0, 1.0);
313 stripe_context->set_line_cap (Cairo::LINE_CAP_SQUARE);
314 stripe_context->set_line_width(50);
315 stripe_context->stroke();
317 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
319 context->set_source_rgba (1.0, 1.0, 0.0, 0.3);
320 context->mask (stripe, 0, 0);
331 LineTips() : top (0.0), bot (0.0), clip_max (false), clip_min (false) {}
335 Cairo::RefPtr<Cairo::ImageSurface> wave;
336 Cairo::RefPtr<Cairo::ImageSurface> outline;
337 Cairo::RefPtr<Cairo::ImageSurface> clip;
338 Cairo::RefPtr<Cairo::ImageSurface> zero;
341 wave (0), outline (0), clip (0), zero (0) {}
345 WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks, boost::shared_ptr<WaveViewThreadRequest> req) const
350 images.wave = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
351 images.outline = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
352 images.clip = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
353 images.zero = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
355 Cairo::RefPtr<Cairo::Context> wave_context = Cairo::Context::create (images.wave);
356 Cairo::RefPtr<Cairo::Context> outline_context = Cairo::Context::create (images.outline);
357 Cairo::RefPtr<Cairo::Context> clip_context = Cairo::Context::create (images.clip);
358 Cairo::RefPtr<Cairo::Context> zero_context = Cairo::Context::create (images.zero);
359 wave_context->set_antialias (Cairo::ANTIALIAS_NONE);
360 outline_context->set_antialias (Cairo::ANTIALIAS_NONE);
361 clip_context->set_antialias (Cairo::ANTIALIAS_NONE);
362 zero_context->set_antialias (Cairo::ANTIALIAS_NONE);
364 boost::scoped_array<LineTips> tips (new LineTips[n_peaks]);
366 /* Clip level nominally set to -0.9dBFS to account for inter-sample
367 interpolation possibly clipping (value may be too low).
369 We adjust by the region's own gain (but note: not by any gain
370 automation or its gain envelope) so that clip indicators are closer
371 to providing data about on-disk data. This multiplication is
372 needed because the data we get from AudioRegion::read_peaks()
373 has been scaled by scale_amplitude() already.
376 const double clip_level = _clip_level * _region_amplitude;
378 if (_shape == WaveView::Rectified) {
380 /* each peak is a line from the bottom of the waveview
381 * to a point determined by max (_peaks[i].max,
386 for (int i = 0; i < n_peaks; ++i) {
388 tips[i].bot = height() - 1.0;
389 const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
390 tips[i].top = y_extent (p, false);
391 tips[i].spread = p * (_height - 1.0);
393 if (_peaks[i].max >= clip_level) {
394 tips[i].clip_max = true;
397 if (-(_peaks[i].min) >= clip_level) {
398 tips[i].clip_min = true;
403 for (int i = 0; i < n_peaks; ++i) {
405 tips[i].bot = height() - 1.0;
406 const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
407 tips[i].top = y_extent (p, false);
408 tips[i].spread = p * (_height - 2.0);
409 if (p >= clip_level) {
410 tips[i].clip_max = true;
419 for (int i = 0; i < n_peaks; ++i) {
420 double top = _peaks[i].max;
421 double bot = _peaks[i].min;
423 if (_peaks[i].max >= clip_level) {
424 tips[i].clip_max = true;
426 if (-(_peaks[i].min) >= clip_level) {
427 tips[i].clip_min = true;
431 top = alt_log_meter (fast_coefficient_to_dB (top));
432 } else if (top < 0.0) {
433 top =-alt_log_meter (fast_coefficient_to_dB (-top));
439 bot = alt_log_meter (fast_coefficient_to_dB (bot));
440 } else if (bot < 0.0) {
441 bot = -alt_log_meter (fast_coefficient_to_dB (-bot));
446 tips[i].top = y_extent (top, false);
447 tips[i].bot = y_extent (bot, true);
448 tips[i].spread = tips[i].bot - tips[i].top;
452 for (int i = 0; i < n_peaks; ++i) {
453 if (_peaks[i].max >= clip_level) {
454 tips[i].clip_max = true;
456 if (-(_peaks[i].min) >= clip_level) {
457 tips[i].clip_min = true;
460 tips[i].top = y_extent (_peaks[i].max, false);
461 tips[i].bot = y_extent (_peaks[i].min, true);
462 tips[i].spread = tips[i].bot - tips[i].top;
468 if (req->should_stop()) {
472 Color alpha_one = rgba_to_color (0, 0, 0, 1.0);
474 set_source_rgba (wave_context, alpha_one);
475 set_source_rgba (outline_context, alpha_one);
476 set_source_rgba (clip_context, alpha_one);
477 set_source_rgba (zero_context, alpha_one);
479 /* ensure single-pixel lines */
481 wave_context->set_line_width (1.0);
482 wave_context->translate (0.5, +1.5);
484 outline_context->set_line_width (1.0);
485 outline_context->translate (0.5, +1.5);
487 clip_context->set_line_width (1.0);
488 clip_context->translate (0.5, +1.5);
490 zero_context->set_line_width (1.0);
491 zero_context->translate (0.5, +1.5);
493 /* the height of the clip-indicator should be at most 7 pixels,
494 * or 5% of the height of the waveview item.
497 const double clip_height = min (7.0, ceil (_height * 0.05));
499 /* There are 3 possible components to draw at each x-axis position: the
500 waveform "line", the zero line and an outline/clip indicator. We
501 have to decide which of the 3 to draw at each position, pixel by
502 pixel. This makes the rendering less efficient but it is the only
503 way I can see to do this correctly.
505 To avoid constant source swapping and stroking, we draw the components separately
506 onto four alpha only image surfaces for use as a mask.
508 With only 1 pixel of spread between the top and bottom of the line,
509 we just draw the upper outline/clip indicator.
511 With 2 pixels of spread, we draw the upper and lower outline clip
514 With 3 pixels of spread we draw the upper and lower outline/clip
515 indicators and at least 1 pixel of the waveform line.
517 With 5 pixels of spread, we draw all components.
519 We can do rectified as two separate passes because we have a much
520 easier decision regarding whether to draw the waveform line. We
521 always draw the clip/outline indicators.
524 if (_shape == WaveView::Rectified) {
526 for (int i = 0; i < n_peaks; ++i) {
530 if (tips[i].spread >= 1.0) {
531 wave_context->move_to (i, tips[i].top);
532 wave_context->line_to (i, tips[i].bot);
537 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
538 clip_context->move_to (i, tips[i].top);
539 /* clip-indicating upper terminal line */
540 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + .5)));
542 outline_context->move_to (i, tips[i].top);
543 /* normal upper terminal dot */
544 outline_context->rel_line_to (0, -1.0);
548 wave_context->stroke ();
549 clip_context->stroke ();
550 outline_context->stroke ();
553 const double height_2 = (_height - 2.5) * .5;
555 for (int i = 0; i < n_peaks; ++i) {
559 if (tips[i].spread >= 2.0) {
560 wave_context->move_to (i, tips[i].top);
561 wave_context->line_to (i, tips[i].bot);
563 /* draw square waves and other discontiguous points clearly */
565 if (tips[i-1].top + 2 < tips[i].top) {
566 wave_context->move_to (i-1, tips[i-1].top);
567 wave_context->line_to (i-1, (tips[i].bot + tips[i-1].top)/2);
568 wave_context->move_to (i, (tips[i].bot + tips[i-1].top)/2);
569 wave_context->line_to (i, tips[i].top);
570 } else if (tips[i-1].bot > tips[i].bot + 2) {
571 wave_context->move_to (i-1, tips[i-1].bot);
572 wave_context->line_to (i-1, (tips[i].top + tips[i-1].bot)/2);
573 wave_context->move_to (i, (tips[i].top + tips[i-1].bot)/2);
574 wave_context->line_to (i, tips[i].bot);
580 if (tips[i].spread >= 5.0 && show_zero_line()) {
581 zero_context->move_to (i, floor(height_2));
582 zero_context->rel_line_to (1.0, 0);
585 if (tips[i].spread > 1.0) {
586 bool clipped = false;
587 /* outline/clip indicators */
588 if (_global_show_waveform_clipping && tips[i].clip_max) {
589 clip_context->move_to (i, tips[i].top);
590 /* clip-indicating upper terminal line */
591 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + 0.5)));
595 if (_global_show_waveform_clipping && tips[i].clip_min) {
596 clip_context->move_to (i, tips[i].bot);
597 /* clip-indicating lower terminal line */
598 clip_context->rel_line_to (0, - min (clip_height, ceil(tips[i].spread + 0.5)));
603 outline_context->move_to (i, tips[i].bot + 1.0);
604 /* normal lower terminal dot */
605 outline_context->rel_line_to (0, -1.0);
607 outline_context->move_to (i, tips[i].top - 1.0);
608 /* normal upper terminal dot */
609 outline_context->rel_line_to (0, 1.0);
612 bool clipped = false;
613 /* outline/clip indicator */
614 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
615 clip_context->move_to (i, tips[i].top);
616 /* clip-indicating upper / lower terminal line */
617 clip_context->rel_line_to (0, 1.0);
622 wave_context->move_to (i, tips[i].top);
623 /* special case where outline only is drawn.
624 * we draw a 1px "line", pretending that the span is 1.0
626 wave_context->rel_line_to (0, 1.0);
631 wave_context->stroke ();
632 outline_context->stroke ();
633 clip_context->stroke ();
634 zero_context->stroke ();
637 if (req->should_stop()) {
641 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
643 /* Here we set a source colour and use the various components as a mask. */
645 if (gradient_depth() != 0.0) {
647 Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _height));
653 if (_shape == Rectified) {
663 color_to_rgba (_fill_color, r, g, b, a);
664 gradient->add_color_stop_rgba (stops[1], r, g, b, a);
665 /* generate a new color for the middle of the gradient */
667 color_to_hsv (_fill_color, h, s, v);
668 /* change v towards white */
669 v *= 1.0 - gradient_depth();
670 Color center = hsva_to_color (h, s, v, a);
671 color_to_rgba (center, r, g, b, a);
673 gradient->add_color_stop_rgba (stops[0], r, g, b, a);
674 gradient->add_color_stop_rgba (stops[2], r, g, b, a);
676 context->set_source (gradient);
678 set_source_rgba (context, _fill_color);
681 if (req->should_stop()) {
685 context->mask (images.wave, 0, 0);
688 set_source_rgba (context, _outline_color);
689 context->mask (images.outline, 0, 0);
692 set_source_rgba (context, _clip_color);
693 context->mask (images.clip, 0, 0);
696 set_source_rgba (context, _zero_color);
697 context->mask (images.zero, 0, 0);
701 boost::shared_ptr<WaveViewCache::Entry>
702 WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) const
704 boost::shared_ptr<WaveViewCache::Entry> ret (new WaveViewCache::Entry (req->channel,
706 req->region_amplitude,
708 req->samples_per_pixel,
713 images = new WaveViewCache;
716 images->add (_region->audio_source (_channel), ret);
718 /* consolidate cache first (removes fully-contained
722 images->consolidate_image_cache (_region->audio_source (_channel),
723 _channel, _height, _region_amplitude,
724 _fill_color, _samples_per_pixel);
729 boost::shared_ptr<WaveViewCache::Entry>
730 WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
732 boost::shared_ptr<WaveViewCache::Entry> ret;
736 /* this is called from a ::render() call, when we need an image to
740 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 needs image from %2 .. %3\n", name, start, end));
744 Glib::Threads::Mutex::Lock lmq (request_queue_lock);
746 /* if there's a draw request outstanding, check to see if we
747 * have an image there. if so, use it (and put it in the cache
751 if (current_request && !current_request->should_stop() && current_request->image) {
753 /* put the image into the cache so that other
754 * WaveViews can use it if it is useful
757 if (current_request->start <= start && current_request->end >= end) {
759 ret.reset (new WaveViewCache::Entry (current_request->channel,
760 current_request->height,
761 current_request->region_amplitude,
762 current_request->fill_color,
763 current_request->samples_per_pixel,
764 current_request->start,
765 current_request->end,
766 current_request->image));
768 cache_request_result (current_request);
769 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: got image from completed request, spans %2..%3\n",
770 name, current_request->start, current_request->end));
773 /* drop our handle on the current request */
774 current_request.reset ();
780 /* no current image draw request, so look in the cache */
782 ret = get_image_from_cache (start, end, full_image);
783 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: lookup from cache gave %2 (full %3)\n",
784 name, ret, full_image));
790 if (!ret || !full_image) {
792 if ((rendered && get_image_in_thread) || always_get_image_in_thread) {
794 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: generating image in caller thread\n", name));
796 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
798 req->type = WaveViewThreadRequest::Draw;
801 req->samples_per_pixel = _samples_per_pixel;
802 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
803 req->channel = _channel;
804 req->width = _canvas->visible_area().width();
805 req->height = _height;
806 req->fill_color = _fill_color;
807 req->region_amplitude = _region_amplitude;
809 /* draw image in this (the GUI thread) */
811 generate_image (req, false);
813 /* cache the result */
815 ret = cache_request_result (req);
817 /* reset this so that future missing images are
818 * generated in a a worker thread.
821 get_image_in_thread = false;
824 queue_get_image (_region, start, end);
829 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 got an image from %2 .. %3 (full ? %4)\n", name, ret->start, ret->end, full_image));
831 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 no useful image available\n", name));
837 boost::shared_ptr<WaveViewCache::Entry>
838 WaveView::get_image_from_cache (framepos_t start, framepos_t end, bool& full) const
841 return boost::shared_ptr<WaveViewCache::Entry>();
844 return images->lookup_image (_region->audio_source (_channel), start, end, _channel,
845 _height, _region_amplitude, _fill_color, _samples_per_pixel, full);
849 WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, framepos_t start, framepos_t end) const
851 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
853 req->type = WaveViewThreadRequest::Draw;
856 req->samples_per_pixel = _samples_per_pixel;
857 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
858 req->channel = _channel;
859 req->width = _canvas->visible_area().width();
860 req->height = _height;
861 req->fill_color = _fill_color;
862 req->region_amplitude = _region_amplitude;
864 if (current_request) {
865 /* this will stop rendering in progress (which might otherwise
866 be long lived) for any current request.
868 current_request->cancel ();
871 start_drawing_thread ();
873 /* swap requests (protected by lock) */
876 Glib::Threads::Mutex::Lock lm (request_queue_lock);
877 current_request = req;
880 /* this is always called from the GUI thread (there is only one), and
881 * the same thread runs the idle callback chain. thus we do not need
882 * any locks to protect idle_queued - it is only ever set or read in
883 * the unitary GUI thread.
887 Glib::signal_idle().connect (sigc::mem_fun (*this, &WaveView::idle_send_request));
893 WaveView::idle_send_request () const
895 Glib::Threads::Mutex::Lock lm (request_queue_lock);
897 request_queue.insert (this);
898 request_cond.signal (); /* wake thread - must be done while holding lock */
901 return false; /* do not call from idle again */
906 WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_render_thread) const
908 if (!req->should_stop()) {
910 /* sample position is canonical here, and we want to generate
911 * an image that spans about twice the canvas width
914 const framepos_t center = req->start + ((req->end - req->start) / 2);
915 const framecnt_t image_samples = req->width * req->samples_per_pixel; /* one canvas width */
917 /* we can request data from anywhere in the Source, between 0 and its length
920 framepos_t sample_start = max (_region_start, (center - image_samples));
921 framepos_t sample_end = min (center + image_samples, region_end());
922 const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
924 boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
926 /* Note that Region::read_peaks() takes a start position based on an
927 offset into the Region's **SOURCE**, rather than an offset into
931 framecnt_t peaks_read = _region->read_peaks (peaks.get(), n_peaks,
932 sample_start, sample_end - sample_start,
934 req->samples_per_pixel);
936 // apply waveform amplitude zoom multiplier
938 req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
939 /* make sure we record the sample positions that were actually used */
940 req->start = sample_start;
941 req->end = sample_end;
943 if (peaks_read > 0) {
945 for (framecnt_t i = 0; i < n_peaks; ++i) {
946 peaks[i].max *= _amplitude_above_axis;
947 peaks[i].min *= _amplitude_above_axis;
950 draw_image (req->image, peaks.get(), n_peaks, req);
952 draw_absent_image (req->image, peaks.get(), n_peaks);
956 if (in_render_thread && !req->should_stop()) {
957 const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
963 /** Given a waveform that starts at window x-coordinate @param wave_origin
964 * and the first pixel that we will actually draw @param draw_start, return
965 * the offset into an image of the entire waveform that we will need to use.
967 * Note: most of our cached images are NOT of the entire waveform, this is just
968 * computationally useful when determining which the sample range span for
972 window_to_image (double wave_origin, double image_start)
974 return image_start - wave_origin;
978 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
980 assert (_samples_per_pixel != 0);
986 /* a WaveView is intimately connected to an AudioRegion. It will
987 * display the waveform within the region, anywhere from the start of
988 * the region to its end.
990 * the area we've been aked to render may overlap with area covered
991 * by the region in any of the normal ways:
993 * - it may begin and end within the area covered by the region
994 * - it may start before and end after the area covered by region
995 * - it may start before and end within the area covered by the region
996 * - it may start within and end after the area covered by the region
997 * - it may be precisely coincident with the area covered by region.
999 * So let's start by determining the area covered by the region, in
1000 * window coordinates. It begins at zero (in item coordinates for this
1001 * waveview, and extends to region_length() / _samples_per_pixel.
1004 Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
1006 // cerr << name << " RENDER " << area << " self = " << self << endl;
1008 /* Now lets get the intersection with the area we've been asked to draw */
1010 boost::optional<Rect> d = self.intersection (area);
1016 Rect draw = d.get();
1018 /* "draw" is now a rectangle that defines the rectangle we need to
1019 * update/render the waveview into, in window coordinate space.
1022 /* window coordinates - pixels where x=0 is the left edge of the canvas
1023 * window. We round down in case we were asked to
1024 * draw "between" pixels at the start and/or end.
1027 double draw_start = floor (draw.x0);
1028 const double draw_end = floor (draw.x1);
1030 // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
1032 /* image coordnates: pixels where x=0 is the start of this waveview,
1033 * wherever it may be positioned. thus image_start=N means "an image
1034 * that begins N pixels after the start of region that this waveview is
1038 const framepos_t image_start = window_to_image (self.x0, draw_start);
1039 const framepos_t image_end = window_to_image (self.x0, draw_end);
1041 // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
1043 /* sample coordinates - note, these are not subject to rounding error
1045 * "sample_start = N" means "the first sample we need to represent is N
1046 * samples after the first sample of the region"
1049 framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
1050 framepos_t sample_end = _region_start + (image_end * _samples_per_pixel);
1052 // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
1054 /* sample_start and sample_end are bounded by the region
1055 * limits. sample_start, because of the was just computed, must already
1056 * be greater than or equal to the _region_start value.
1059 sample_end = min (region_end(), sample_end);
1061 // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
1063 double image_origin_in_self_coordinates;
1064 boost::shared_ptr<WaveViewCache::Entry> image_to_draw;
1066 if (_current_image) {
1068 /* check it covers the right sample range */
1070 if (_current_image->start > sample_start || _current_image->end < sample_end) {
1071 /* doesn't cover the area we need ... reset */
1072 _current_image.reset ();
1074 /* timestamp our continuing use of this image/cache entry */
1075 images->use (_region->audio_source (_channel), _current_image);
1076 image_to_draw = _current_image;
1080 if (!image_to_draw) {
1085 image_to_draw = get_image (sample_start, sample_end, full_image);
1087 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 image to draw = %2 (full? %3)\n", name, image_to_draw, full_image));
1089 if (!image_to_draw) {
1090 /* image not currently available. A redraw will be scheduled
1097 /* found an image that covers our entire sample range,
1098 * so keep a reference to it.
1100 _current_image = image_to_draw;
1104 /* compute the first pixel of the image that should be used when we
1105 * render the specified range.
1108 image_origin_in_self_coordinates = (image_to_draw->start - _region_start) / _samples_per_pixel;
1110 if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
1111 /* we are going to draw the first pixel for this region, but
1112 we may not want this to overlap a border around the
1113 waveform. If so, _start_shift will be set.
1115 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
1116 //draw_start += _start_shift;
1117 //image_origin_in_self_coordinates += _start_shift;
1120 /* the image may only be a best-effort ... it may not span the entire
1121 * range requested, though it is guaranteed to cover the start. So
1122 * determine how many pixels we can actually draw.
1127 if (image_to_draw != _current_image) {
1129 /* the image is guaranteed to start at or before
1130 * draw_start. But if it starts before draw_start, that reduces
1131 * the maximum available width we can render with.
1133 * so .. clamp the draw width to the smaller of what we need to
1134 * draw or the available width of the image.
1137 draw_width = min ((double) image_to_draw->image->get_width() - (draw_start - image_to_draw->start),
1138 (draw_end - draw_start));
1141 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),
1142 image_to_draw->image->get_width(), image_origin_in_self_coordinates,
1143 image_to_draw->start, _region_start));
1145 draw_width = draw_end - draw_start;
1146 DEBUG_TRACE (DEBUG::WaveView, string_compose ("use current image, span entire render width %1..%2\n", draw_start, draw_end));
1149 context->rectangle (draw_start, draw.y0, draw_width, draw.height());
1151 /* round image origin position to an exact pixel in device space to
1155 double x = self.x0 + image_origin_in_self_coordinates;
1157 context->user_to_device (x, y);
1160 context->device_to_user (x, y);
1162 /* the coordinates specify where in "user coordinates" (i.e. what we
1163 * generally call "canvas coordinates" in this code) the image origin
1164 * will appear. So specifying (10,10) will put the upper left corner of
1165 * the image at (10,10) in user space.
1168 context->set_source (image_to_draw->image, x, y);
1171 /* image obtained, some of it painted to display: we are rendered.
1172 Future calls to get_image_in_thread are now meaningful.
1179 WaveView::compute_bounding_box () const
1182 _bounding_box = Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height);
1184 _bounding_box = boost::optional<Rect> ();
1187 _bounding_box_dirty = false;
1191 WaveView::set_height (Distance height)
1193 if (height != _height) {
1196 invalidate_image_cache ();
1198 get_image_in_thread = true;
1200 _bounding_box_dirty = true;
1206 WaveView::set_channel (int channel)
1208 if (channel != _channel) {
1211 invalidate_image_cache ();
1214 _bounding_box_dirty = true;
1220 WaveView::set_logscaled (bool yn)
1222 if (_logscaled != yn) {
1223 begin_visual_change ();
1224 invalidate_image_cache ();
1226 end_visual_change ();
1231 WaveView::gain_changed ()
1233 begin_visual_change ();
1234 invalidate_image_cache ();
1235 _region_amplitude = _region->scale_amplitude ();
1236 end_visual_change ();
1240 WaveView::set_zero_color (Color c)
1242 if (_zero_color != c) {
1243 begin_visual_change ();
1244 invalidate_image_cache ();
1246 end_visual_change ();
1251 WaveView::set_clip_color (Color c)
1253 if (_clip_color != c) {
1254 begin_visual_change ();
1255 invalidate_image_cache ();
1257 end_visual_change ();
1262 WaveView::set_show_zero_line (bool yn)
1264 if (_show_zero != yn) {
1265 begin_visual_change ();
1266 invalidate_image_cache ();
1268 end_visual_change ();
1273 WaveView::set_shape (Shape s)
1276 begin_visual_change ();
1277 invalidate_image_cache ();
1279 end_visual_change ();
1284 WaveView::set_amplitude_above_axis (double a)
1286 if (fabs (_amplitude_above_axis - a) > 0.01) {
1287 begin_visual_change ();
1288 invalidate_image_cache ();
1289 _amplitude_above_axis = a;
1290 end_visual_change ();
1295 WaveView::set_global_shape (Shape s)
1297 if (_global_shape != s) {
1299 VisualPropertiesChanged (); /* EMIT SIGNAL */
1304 WaveView::set_global_logscaled (bool yn)
1306 if (_global_logscaled != yn) {
1307 _global_logscaled = yn;
1308 VisualPropertiesChanged (); /* EMIT SIGNAL */
1313 WaveView::region_length() const
1315 return _region->length() - (_region_start - _region->start());
1319 WaveView::region_end() const
1321 return _region_start + region_length();
1325 WaveView::set_region_start (frameoffset_t start)
1331 if (_region_start == start) {
1336 _region_start = start;
1337 _bounding_box_dirty = true;
1342 WaveView::region_resized ()
1344 /* Called when the region start or end (thus length) has changed.
1352 _region_start = _region->start();
1353 _bounding_box_dirty = true;
1358 WaveView::set_global_gradient_depth (double depth)
1360 if (_global_gradient_depth != depth) {
1361 _global_gradient_depth = depth;
1362 VisualPropertiesChanged (); /* EMIT SIGNAL */
1367 WaveView::set_global_show_waveform_clipping (bool yn)
1369 if (_global_show_waveform_clipping != yn) {
1370 _global_show_waveform_clipping = yn;
1371 ClipLevelChanged ();
1376 WaveView::set_start_shift (double pixels)
1382 begin_visual_change ();
1383 _start_shift = pixels;
1384 end_visual_change ();
1388 WaveView::cancel_my_render_request () const
1394 /* try to stop any current rendering of the request, or prevent it from
1398 if (current_request) {
1399 current_request->cancel ();
1402 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1404 /* now remove it from the queue and reset our request pointer so that
1405 have no outstanding request (that we know about)
1408 request_queue.erase (this);
1409 current_request.reset ();
1412 /*-------------------------------------------------*/
1415 WaveView::start_drawing_thread ()
1417 if (!_drawing_thread) {
1418 _drawing_thread = Glib::Threads::Thread::create (sigc::ptr_fun (WaveView::drawing_thread));
1423 WaveView::stop_drawing_thread ()
1425 if (_drawing_thread) {
1426 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1427 g_atomic_int_set (&drawing_thread_should_quit, 1);
1428 request_cond.signal ();
1433 WaveView::drawing_thread ()
1435 using namespace Glib::Threads;
1437 WaveView const * requestor;
1438 Mutex::Lock lm (request_queue_lock);
1443 /* remember that we hold the lock at this point, no matter what */
1445 if (g_atomic_int_get (&drawing_thread_should_quit)) {
1449 if (request_queue.empty()) {
1450 request_cond.wait (request_queue_lock);
1453 /* remove the request from the queue (remember: the "request"
1454 * is just a pointer to a WaveView object)
1457 requestor = *(request_queue.begin());
1458 request_queue.erase (request_queue.begin());
1460 boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
1466 /* Generate an image. Unlock the request queue lock
1467 * while we do this, so that other things can happen
1468 * as we do rendering.
1471 request_queue_lock.unlock (); /* some RAII would be good here */
1474 requestor->generate_image (req, true);
1476 req->image.clear(); /* just in case it was set before the exception, whatever it was */
1479 request_queue_lock.lock ();
1481 req.reset (); /* drop/delete request as appropriate */
1484 /* thread is vanishing */
1485 _drawing_thread = 0;
1488 /*-------------------------------------------------*/
1490 WaveViewCache::WaveViewCache ()
1491 : image_cache_size (0)
1492 , _image_cache_threshold (100 * 1048576) /* bytes */
1496 WaveViewCache::~WaveViewCache ()
1501 boost::shared_ptr<WaveViewCache::Entry>
1502 WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
1503 framepos_t start, framepos_t end,
1508 double samples_per_pixel,
1509 bool& full_coverage)
1511 ImageCache::iterator x;
1513 if ((x = cache_map.find (src)) == cache_map.end ()) {
1514 /* nothing in the cache for this audio source at all */
1515 return boost::shared_ptr<WaveViewCache::Entry> ();
1518 CacheLine& caches = x->second;
1519 boost::shared_ptr<Entry> best_partial;
1520 framecnt_t max_coverage = 0;
1522 /* Find a suitable ImageSurface, if it exists.
1525 for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
1527 boost::shared_ptr<Entry> e (*c);
1529 if (channel != e->channel
1530 || height != e->height
1531 || amplitude != e->amplitude
1532 || samples_per_pixel != e->samples_per_pixel
1533 || fill_color != e->fill_color) {
1537 if (end <= e->end && start >= e->start) {
1538 /* found an image that covers the range we need */
1539 DEBUG_TRACE (DEBUG::WaveView, string_compose ("found image spanning %1..%2 covers %3..%4\n",
1540 e->start, e->end, start, end));
1542 full_coverage = true;
1546 if (start >= e->start) {
1547 /* found an image that covers the start, but not the
1548 * end. See if it is longer than any other similar
1549 * partial image that we've found so far.
1552 if ((e->end - e->start) > max_coverage) {
1554 max_coverage = e->end - e->start;
1560 DEBUG_TRACE (DEBUG::WaveView, string_compose ("found PARTIAL image spanning %1..%2 partially covers %3..%4\n",
1561 best_partial->start, best_partial->end, start, end));
1562 use (src, best_partial);
1563 full_coverage = false;
1564 return best_partial;
1567 return boost::shared_ptr<Entry> ();
1571 WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> src,
1576 double samples_per_pixel)
1578 list <uint32_t> deletion_list;
1579 uint32_t other_entries = 0;
1580 ImageCache::iterator x;
1582 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1584 if ((x = cache_map.find (src)) == cache_map.end ()) {
1588 CacheLine& caches = x->second;
1590 for (CacheLine::iterator c1 = caches.begin(); c1 != caches.end(); ) {
1592 CacheLine::iterator nxt = c1;
1595 boost::shared_ptr<Entry> e1 (*c1);
1597 if (channel != e1->channel
1598 || height != e1->height
1599 || amplitude != e1->amplitude
1600 || samples_per_pixel != e1->samples_per_pixel
1601 || fill_color != e1->fill_color) {
1603 /* doesn't match current properties, ignore and move on
1612 /* c1 now points to a cached image entry that matches current
1613 * properties. Check all subsequent cached imaged entries to
1614 * see if there are others that also match but represent
1615 * subsets of the range covered by this one.
1618 for (CacheLine::iterator c2 = c1; c2 != caches.end(); ) {
1620 CacheLine::iterator nxt2 = c2;
1623 boost::shared_ptr<Entry> e2 (*c2);
1625 if (e1 == e2 || channel != e2->channel
1626 || height != e2->height
1627 || amplitude != e2->amplitude
1628 || samples_per_pixel != e2->samples_per_pixel
1629 || fill_color != e2->fill_color) {
1631 /* properties do not match, ignore for the
1632 * purposes of consolidation.
1638 if (e2->start >= e1->start && e2->end <= e1->end) {
1639 /* c2 is fully contained by c1, so delete it */
1640 c2 = caches.erase (c2);
1652 WaveViewCache::use (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1654 ce->timestamp = g_get_monotonic_time ();
1658 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1660 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1662 Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
1664 image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1670 ce->timestamp = g_get_monotonic_time ();
1672 cache_map[src].push_back (ce);
1673 cache_list.push_back (make_pair (src, ce));
1677 WaveViewCache::compute_image_cache_size()
1680 for (ImageCache::iterator s = cache_map.begin(); s != cache_map.end(); ++s) {
1681 CacheLine& per_source_cache (s->second);
1682 for (CacheLine::iterator c = per_source_cache.begin(); c != per_source_cache.end(); ++c) {
1683 Cairo::RefPtr<Cairo::ImageSurface> img ((*c)->image);
1684 total += img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1691 WaveViewCache::cache_full()
1693 return image_cache_size > _image_cache_threshold;
1697 WaveViewCache::cache_flush ()
1699 SortByTimestamp sorter;
1701 /* sort list in LRU order */
1703 sort (cache_list.begin(), cache_list.end(), sorter);
1705 while (image_cache_size > _image_cache_threshold) {
1707 ListEntry& le (cache_list.front());
1709 ImageCache::iterator x;
1711 if ((x = cache_map.find (le.first)) == cache_map.end ()) {
1712 /* wierd ... no entry for this AudioSource */
1716 CacheLine& cl = x->second;
1718 for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
1720 if (*c == le.second) {
1722 /* Remove this entry from this cache line */
1726 /* remove cache line from main cache: no more entries */
1727 cache_map.erase (x);
1734 Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
1735 uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1737 if (image_cache_size > size) {
1738 image_cache_size -= size;
1740 image_cache_size = 0;
1743 /* Remove from the linear list */
1744 cache_list.erase (cache_list.begin());
1749 WaveViewCache::set_image_cache_threshold (uint64_t sz)
1751 _image_cache_threshold = sz;