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)
97 images = new WaveViewCache;
100 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
101 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
103 ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
106 WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
110 , _samples_per_pixel (0)
113 , _zero_color (0xff0000ff)
114 , _clip_color (0xff0000ff)
115 , _logscaled (_global_logscaled)
116 , _shape (_global_shape)
117 , _gradient_depth (_global_gradient_depth)
118 , _shape_independent (false)
119 , _logscaled_independent (false)
120 , _gradient_depth_independent (false)
121 , _amplitude_above_axis (1.0)
122 , _region_amplitude (region->scale_amplitude ())
124 , idle_queued (false)
125 , _region_start (region->start())
126 , get_image_in_thread (false)
127 , always_get_image_in_thread (false)
131 images = new WaveViewCache;
134 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
135 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
137 ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
140 WaveView::~WaveView ()
142 invalidate_image_cache ();
146 WaveView::debug_name() const
148 return _region->name() + string (":") + PBD::to_string (_channel+1, std::dec);
152 WaveView::image_ready ()
158 WaveView::set_always_get_image_in_thread (bool yn)
160 always_get_image_in_thread = yn;
164 WaveView::handle_visual_property_change ()
166 bool changed = false;
168 if (!_shape_independent && (_shape != global_shape())) {
169 _shape = global_shape();
173 if (!_logscaled_independent && (_logscaled != global_logscaled())) {
174 _logscaled = global_logscaled();
178 if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
179 _gradient_depth = global_gradient_depth();
184 begin_visual_change ();
185 invalidate_image_cache ();
186 end_visual_change ();
191 WaveView::handle_clip_level_change ()
193 begin_visual_change ();
194 invalidate_image_cache ();
195 end_visual_change ();
199 WaveView::set_fill_color (Color c)
201 if (c != _fill_color) {
202 begin_visual_change ();
203 invalidate_image_cache ();
204 Fill::set_fill_color (c);
205 end_visual_change ();
210 WaveView::set_outline_color (Color c)
212 if (c != _outline_color) {
213 begin_visual_change ();
214 invalidate_image_cache ();
215 Outline::set_outline_color (c);
216 end_visual_change ();
221 WaveView::set_samples_per_pixel (double samples_per_pixel)
223 if (samples_per_pixel != _samples_per_pixel) {
226 invalidate_image_cache ();
227 _samples_per_pixel = samples_per_pixel;
228 _bounding_box_dirty = true;
235 _log_meter (float power, double lower_db, double upper_db, double non_linearity)
237 return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
241 alt_log_meter (float power)
243 return _log_meter (power, -192.0, 0.0, 8.0);
247 WaveView::set_clip_level (double dB)
249 const double clip_level = dB_to_coefficient (dB);
250 if (clip_level != _clip_level) {
251 _clip_level = clip_level;
257 WaveView::invalidate_image_cache ()
259 cancel_my_render_request ();
260 _current_image.reset ();
264 WaveView::compute_tips (PeakData const & peak, WaveView::LineTips& tips) const
266 const double effective_height = _height;
268 /* remember: canvas (and cairo) coordinate space puts the origin at the upper left.
270 So, a sample value of 1.0 (0dbFS) will be computed as:
272 (1.0 - 1.0) * 0.5 * effective_height
274 which evaluates to 0, or the top of the image.
276 A sample value of -1.0 will be computed as
278 (1.0 + 1.0) * 0.5 * effective height
280 which evaluates to effective height, or the bottom of the image.
283 const double pmax = (1.0 - peak.max) * 0.5 * effective_height;
284 const double pmin = (1.0 - peak.min) * 0.5 * effective_height;
286 /* remember that the bottom of the image (pmin) has larger y-coordinates
290 double spread = (pmin - pmax) * 0.5;
292 /* find the nearest pixel to the nominal center. */
293 const double center = round (pmin - spread);
296 /* minimum distance between line ends is 1 pixel, and we want it "centered" on a pixel,
297 as per cairo single-pixel line issues.
299 NOTE: the caller will not draw a line between these two points if the spread is
300 less than 2 pixels. So only the tips.top value matters, which is where we will
301 draw a single pixel as part of the outline.
304 tips.bot = center + 1.0;
306 /* round spread above and below center to an integer number of pixels */
307 spread = round (spread);
308 /* top and bottom are located equally either side of the center */
309 tips.top = center - spread;
310 tips.bot = center + spread;
313 tips.top = min (effective_height, max (0.0, tips.top));
314 tips.bot = min (effective_height, max (0.0, tips.bot));
319 WaveView::y_extent (double s) const
321 assert (_shape == Rectified);
322 return floor ((1.0 - s) * _height);
326 WaveView::draw_absent_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
328 Cairo::RefPtr<Cairo::ImageSurface> stripe = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
330 Cairo::RefPtr<Cairo::Context> stripe_context = Cairo::Context::create (stripe);
331 stripe_context->set_antialias (Cairo::ANTIALIAS_NONE);
333 uint32_t stripe_separation = 150;
334 double start = - floor (_height / stripe_separation) * stripe_separation;
337 while (start < n_peaks) {
339 stripe_context->move_to (start, 0);
340 stripe_x = start + _height;
341 stripe_context->line_to (stripe_x, _height);
342 start += stripe_separation;
345 stripe_context->set_source_rgba (1.0, 1.0, 1.0, 1.0);
346 stripe_context->set_line_cap (Cairo::LINE_CAP_SQUARE);
347 stripe_context->set_line_width(50);
348 stripe_context->stroke();
350 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
352 context->set_source_rgba (1.0, 1.0, 0.0, 0.3);
353 context->mask (stripe, 0, 0);
358 Cairo::RefPtr<Cairo::ImageSurface> wave;
359 Cairo::RefPtr<Cairo::ImageSurface> outline;
360 Cairo::RefPtr<Cairo::ImageSurface> clip;
361 Cairo::RefPtr<Cairo::ImageSurface> zero;
364 wave (0), outline (0), clip (0), zero (0) {}
368 WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks, boost::shared_ptr<WaveViewThreadRequest> req) const
373 images.wave = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
374 images.outline = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
375 images.clip = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
376 images.zero = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
378 Cairo::RefPtr<Cairo::Context> wave_context = Cairo::Context::create (images.wave);
379 Cairo::RefPtr<Cairo::Context> outline_context = Cairo::Context::create (images.outline);
380 Cairo::RefPtr<Cairo::Context> clip_context = Cairo::Context::create (images.clip);
381 Cairo::RefPtr<Cairo::Context> zero_context = Cairo::Context::create (images.zero);
382 wave_context->set_antialias (Cairo::ANTIALIAS_NONE);
383 outline_context->set_antialias (Cairo::ANTIALIAS_NONE);
384 clip_context->set_antialias (Cairo::ANTIALIAS_NONE);
385 zero_context->set_antialias (Cairo::ANTIALIAS_NONE);
387 boost::scoped_array<LineTips> tips (new LineTips[n_peaks]);
389 /* Clip level nominally set to -0.9dBFS to account for inter-sample
390 interpolation possibly clipping (value may be too low).
392 We adjust by the region's own gain (but note: not by any gain
393 automation or its gain envelope) so that clip indicators are closer
394 to providing data about on-disk data. This multiplication is
395 needed because the data we get from AudioRegion::read_peaks()
396 has been scaled by scale_amplitude() already.
399 const double clip_level = _clip_level * _region_amplitude;
401 if (_shape == WaveView::Rectified) {
403 /* each peak is a line from the bottom of the waveview
404 * to a point determined by max (_peaks[i].max,
409 for (int i = 0; i < n_peaks; ++i) {
411 tips[i].bot = height() - 1.0;
412 const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
413 tips[i].top = y_extent (p);
414 tips[i].spread = p * _height;
416 if (_peaks[i].max >= clip_level) {
417 tips[i].clip_max = true;
420 if (-(_peaks[i].min) >= clip_level) {
421 tips[i].clip_min = true;
426 for (int i = 0; i < n_peaks; ++i) {
428 tips[i].bot = height() - 1.0;
429 const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
430 tips[i].top = y_extent (p);
431 tips[i].spread = p * _height;
432 if (p >= clip_level) {
433 tips[i].clip_max = true;
442 for (int i = 0; i < n_peaks; ++i) {
444 p.max = _peaks[i].max;
445 p.min = _peaks[i].min;
447 if (_peaks[i].max >= clip_level) {
448 tips[i].clip_max = true;
450 if (-(_peaks[i].min) >= clip_level) {
451 tips[i].clip_min = true;
455 p.max = alt_log_meter (fast_coefficient_to_dB (p.max));
456 } else if (p.max < 0.0) {
457 p.max =-alt_log_meter (fast_coefficient_to_dB (-p.max));
463 p.min = alt_log_meter (fast_coefficient_to_dB (p.min));
464 } else if (p.min < 0.0) {
465 p.min = -alt_log_meter (fast_coefficient_to_dB (-p.min));
470 compute_tips (p, tips[i]);
471 tips[i].spread = tips[i].bot - tips[i].top;
475 for (int i = 0; i < n_peaks; ++i) {
476 if (_peaks[i].max >= clip_level) {
477 tips[i].clip_max = true;
479 if (-(_peaks[i].min) >= clip_level) {
480 tips[i].clip_min = true;
483 compute_tips (_peaks[i], tips[i]);
484 tips[i].spread = tips[i].bot - tips[i].top;
490 if (req->should_stop()) {
494 Color alpha_one = rgba_to_color (0, 0, 0, 1.0);
496 set_source_rgba (wave_context, alpha_one);
497 set_source_rgba (outline_context, alpha_one);
498 set_source_rgba (clip_context, alpha_one);
499 set_source_rgba (zero_context, alpha_one);
501 /* ensure single-pixel lines */
503 wave_context->set_line_width (1.0);
504 wave_context->translate (0.5, 0.5);
506 outline_context->set_line_width (1.0);
507 outline_context->translate (0.5, 0.5);
509 clip_context->set_line_width (1.0);
510 clip_context->translate (0.5, 0.5);
512 zero_context->set_line_width (1.0);
513 zero_context->translate (0.5, 0.5);
515 /* the height of the clip-indicator should be at most 7 pixels,
516 * or 5% of the height of the waveview item.
519 const double clip_height = min (7.0, ceil (_height * 0.05));
521 /* There are 3 possible components to draw at each x-axis position: the
522 waveform "line", the zero line and an outline/clip indicator. We
523 have to decide which of the 3 to draw at each position, pixel by
524 pixel. This makes the rendering less efficient but it is the only
525 way I can see to do this correctly.
527 To avoid constant source swapping and stroking, we draw the components separately
528 onto four alpha only image surfaces for use as a mask.
530 With only 1 pixel of spread between the top and bottom of the line,
531 we just draw the upper outline/clip indicator.
533 With 2 pixels of spread, we draw the upper and lower outline clip
536 With 3 pixels of spread we draw the upper and lower outline/clip
537 indicators and at least 1 pixel of the waveform line.
539 With 5 pixels of spread, we draw all components.
541 We can do rectified as two separate passes because we have a much
542 easier decision regarding whether to draw the waveform line. We
543 always draw the clip/outline indicators.
546 if (_shape == WaveView::Rectified) {
548 for (int i = 0; i < n_peaks; ++i) {
552 if (tips[i].spread >= 1.0) {
553 wave_context->move_to (i, tips[i].top);
554 wave_context->line_to (i, tips[i].bot);
559 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
560 clip_context->move_to (i, tips[i].top);
561 /* clip-indicating upper terminal line */
562 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + .5)));
564 outline_context->move_to (i, tips[i].top);
565 /* normal upper terminal dot */
566 outline_context->rel_line_to (0, -1.0);
570 wave_context->stroke ();
571 clip_context->stroke ();
572 outline_context->stroke ();
575 const double height_2 = _height * .5;
577 for (int i = 0; i < n_peaks; ++i) {
581 if (tips[i].spread >= 2.0) {
582 wave_context->move_to (i, tips[i].top);
583 wave_context->line_to (i, tips[i].bot);
586 /* draw square waves and other discontiguous points clearly */
588 if (tips[i-1].top + 2 < tips[i].top) {
589 wave_context->move_to (i-1, tips[i-1].top);
590 wave_context->line_to (i-1, (tips[i].bot + tips[i-1].top)/2);
591 wave_context->move_to (i, (tips[i].bot + tips[i-1].top)/2);
592 wave_context->line_to (i, tips[i].top);
593 } else if (tips[i-1].bot > tips[i].bot + 2) {
594 wave_context->move_to (i-1, tips[i-1].bot);
595 wave_context->line_to (i-1, (tips[i].top + tips[i-1].bot)/2);
596 wave_context->move_to (i, (tips[i].top + tips[i-1].bot)/2);
597 wave_context->line_to (i, tips[i].bot);
601 /* zero line, show only if there is enough spread */
603 if (tips[i].spread >= 5.0 && show_zero_line()) {
604 zero_context->move_to (i, floor(height_2));
605 zero_context->rel_line_to (1.0, 0);
608 if (tips[i].spread > 1.0) {
609 bool clipped = false;
610 /* outline/clip indicators */
611 if (_global_show_waveform_clipping && tips[i].clip_max) {
612 clip_context->move_to (i, tips[i].top);
613 /* clip-indicating upper terminal line */
614 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + 0.5)));
618 if (_global_show_waveform_clipping && tips[i].clip_min) {
619 clip_context->move_to (i, tips[i].bot);
620 /* clip-indicating lower terminal line */
621 clip_context->rel_line_to (0, - min (clip_height, ceil(tips[i].spread + 0.5)));
626 outline_context->move_to (i, tips[i].bot);
627 /* normal lower terminal dot; line moves up */
628 outline_context->rel_line_to (0, -1.0);
630 outline_context->move_to (i, tips[i].top);
631 /* normal upper terminal dot, line moves down */
632 outline_context->rel_line_to (0, 1.0);
635 bool clipped = false;
636 /* outline/clip indicator */
637 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
638 clip_context->move_to (i, tips[i].top);
639 /* clip-indicating upper / lower terminal line */
640 clip_context->rel_line_to (0, 1.0);
645 wave_context->move_to (i, tips[i].top);
646 /* special case where outline only is drawn.
647 * we draw a 1px "line", pretending that the span is 1.0
649 wave_context->rel_line_to (0, 1.0);
654 wave_context->stroke ();
655 outline_context->stroke ();
656 clip_context->stroke ();
657 zero_context->stroke ();
660 if (req->should_stop()) {
664 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
666 /* Here we set a source colour and use the various components as a mask. */
668 if (gradient_depth() != 0.0) {
670 Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _height));
676 if (_shape == Rectified) {
686 color_to_rgba (_fill_color, r, g, b, a);
687 gradient->add_color_stop_rgba (stops[1], r, g, b, a);
688 /* generate a new color for the middle of the gradient */
690 color_to_hsv (_fill_color, h, s, v);
691 /* change v towards white */
692 v *= 1.0 - gradient_depth();
693 Color center = hsva_to_color (h, s, v, a);
694 color_to_rgba (center, r, g, b, a);
696 gradient->add_color_stop_rgba (stops[0], r, g, b, a);
697 gradient->add_color_stop_rgba (stops[2], r, g, b, a);
699 context->set_source (gradient);
701 set_source_rgba (context, _fill_color);
704 if (req->should_stop()) {
708 context->mask (images.wave, 0, 0);
711 set_source_rgba (context, _outline_color);
712 context->mask (images.outline, 0, 0);
715 set_source_rgba (context, _clip_color);
716 context->mask (images.clip, 0, 0);
719 set_source_rgba (context, _zero_color);
720 context->mask (images.zero, 0, 0);
724 boost::shared_ptr<WaveViewCache::Entry>
725 WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) const
727 boost::shared_ptr<WaveViewCache::Entry> ret (new WaveViewCache::Entry (req->channel,
731 req->samples_per_pixel,
735 images->add (_region->audio_source (_channel), ret);
737 /* consolidate cache first (removes fully-contained
741 images->consolidate_image_cache (_region->audio_source (_channel),
742 req->channel, req->height, req->amplitude,
743 req->fill_color, req->samples_per_pixel);
748 boost::shared_ptr<WaveViewCache::Entry>
749 WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
751 boost::shared_ptr<WaveViewCache::Entry> ret;
755 /* this is called from a ::render() call, when we need an image to
759 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 needs image from %2 .. %3\n", name, start, end));
763 Glib::Threads::Mutex::Lock lmq (request_queue_lock);
765 /* if there's a draw request outstanding, check to see if we
766 * have an image there. if so, use it (and put it in the cache
770 if (current_request && !current_request->should_stop() && current_request->image) {
772 /* put the image into the cache so that other
773 * WaveViews can use it if it is useful
776 if (current_request->start <= start && current_request->end >= end) {
778 ret.reset (new WaveViewCache::Entry (current_request->channel,
779 current_request->height,
780 current_request->amplitude,
781 current_request->fill_color,
782 current_request->samples_per_pixel,
783 current_request->start,
784 current_request->end,
785 current_request->image));
787 cache_request_result (current_request);
788 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: got image from completed request, spans %2..%3\n",
789 name, current_request->start, current_request->end));
792 /* drop our handle on the current request */
793 current_request.reset ();
799 /* no current image draw request, so look in the cache */
801 ret = get_image_from_cache (start, end, full_image);
802 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: lookup from cache gave %2 (full %3)\n",
803 name, ret, full_image));
809 if (!ret || !full_image) {
811 if ((rendered && get_image_in_thread) || always_get_image_in_thread) {
813 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: generating image in caller thread\n", name));
815 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
817 req->type = WaveViewThreadRequest::Draw;
820 req->samples_per_pixel = _samples_per_pixel;
821 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
822 req->channel = _channel;
823 req->width = _canvas->visible_area().width();
824 req->height = _height;
825 req->fill_color = _fill_color;
826 req->amplitude = _region_amplitude * _amplitude_above_axis;
828 /* draw image in this (the GUI thread) */
830 generate_image (req, false);
832 /* cache the result */
834 ret = cache_request_result (req);
836 /* reset this so that future missing images are
837 * generated in a a worker thread.
840 get_image_in_thread = false;
843 queue_get_image (_region, start, end);
848 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 got an image from %2 .. %3 (full ? %4)\n", name, ret->start, ret->end, full_image));
850 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 no useful image available\n", name));
856 boost::shared_ptr<WaveViewCache::Entry>
857 WaveView::get_image_from_cache (framepos_t start, framepos_t end, bool& full) const
860 return boost::shared_ptr<WaveViewCache::Entry>();
863 return images->lookup_image (_region->audio_source (_channel), start, end, _channel,
864 _height, _region_amplitude * _amplitude_above_axis, _fill_color, _samples_per_pixel, full);
868 WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, framepos_t start, framepos_t end) const
870 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
872 req->type = WaveViewThreadRequest::Draw;
875 req->samples_per_pixel = _samples_per_pixel;
876 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
877 req->channel = _channel;
878 req->width = _canvas->visible_area().width();
879 req->height = _height;
880 req->fill_color = _fill_color;
881 req->amplitude = _region_amplitude * _amplitude_above_axis;
883 if (current_request) {
884 /* this will stop rendering in progress (which might otherwise
885 be long lived) for any current request.
887 current_request->cancel ();
890 start_drawing_thread ();
892 /* swap requests (protected by lock) */
895 Glib::Threads::Mutex::Lock lm (request_queue_lock);
896 current_request = req;
899 /* this is always called from the GUI thread (there is only one), and
900 * the same thread runs the idle callback chain. thus we do not need
901 * any locks to protect idle_queued - it is only ever set or read in
902 * the unitary GUI thread.
906 Glib::signal_idle().connect (sigc::mem_fun (*this, &WaveView::idle_send_request));
912 WaveView::idle_send_request () const
914 Glib::Threads::Mutex::Lock lm (request_queue_lock);
916 request_queue.insert (this);
917 request_cond.signal (); /* wake thread - must be done while holding lock */
920 return false; /* do not call from idle again */
925 WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_render_thread) const
927 if (!req->should_stop()) {
929 /* sample position is canonical here, and we want to generate
930 * an image that spans about twice the canvas width
933 const framepos_t center = req->start + ((req->end - req->start) / 2);
934 const framecnt_t image_samples = req->width * req->samples_per_pixel; /* one canvas width */
936 /* we can request data from anywhere in the Source, between 0 and its length
939 framepos_t sample_start = max (_region_start, (center - image_samples));
940 framepos_t sample_end = min (center + image_samples, region_end());
941 const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
943 boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
945 /* Note that Region::read_peaks() takes a start position based on an
946 offset into the Region's **SOURCE**, rather than an offset into
950 framecnt_t peaks_read = _region->read_peaks (peaks.get(), n_peaks,
951 sample_start, sample_end - sample_start,
953 req->samples_per_pixel);
955 req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
956 /* make sure we record the sample positions that were actually used */
957 req->start = sample_start;
958 req->end = sample_end;
960 if (peaks_read > 0) {
962 if (_amplitude_above_axis != 1.0) {
963 for (framecnt_t i = 0; i < n_peaks; ++i) {
964 peaks[i].max *= _amplitude_above_axis;
965 peaks[i].min *= _amplitude_above_axis;
969 draw_image (req->image, peaks.get(), n_peaks, req);
971 draw_absent_image (req->image, peaks.get(), n_peaks);
975 if (in_render_thread && !req->should_stop()) {
976 const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
982 /** Given a waveform that starts at window x-coordinate @param wave_origin
983 * and the first pixel that we will actually draw @param draw_start, return
984 * the offset into an image of the entire waveform that we will need to use.
986 * Note: most of our cached images are NOT of the entire waveform, this is just
987 * computationally useful when determining which the sample range span for
991 window_to_image (double wave_origin, double image_start)
993 return image_start - wave_origin;
997 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
999 assert (_samples_per_pixel != 0);
1005 /* a WaveView is intimately connected to an AudioRegion. It will
1006 * display the waveform within the region, anywhere from the start of
1007 * the region to its end.
1009 * the area we've been aked to render may overlap with area covered
1010 * by the region in any of the normal ways:
1012 * - it may begin and end within the area covered by the region
1013 * - it may start before and end after the area covered by region
1014 * - it may start before and end within the area covered by the region
1015 * - it may start within and end after the area covered by the region
1016 * - it may be precisely coincident with the area covered by region.
1018 * So let's start by determining the area covered by the region, in
1019 * window coordinates. It begins at zero (in item coordinates for this
1020 * waveview, and extends to region_length() / _samples_per_pixel.
1023 Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
1025 // cerr << name << " RENDER " << area << " self = " << self << endl;
1027 /* Now lets get the intersection with the area we've been asked to draw */
1029 boost::optional<Rect> d = self.intersection (area);
1035 Rect draw = d.get();
1037 /* "draw" is now a rectangle that defines the rectangle we need to
1038 * update/render the waveview into, in window coordinate space.
1041 /* window coordinates - pixels where x=0 is the left edge of the canvas
1042 * window. We round down in case we were asked to
1043 * draw "between" pixels at the start and/or end.
1046 double draw_start = floor (draw.x0);
1047 const double draw_end = floor (draw.x1);
1049 // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
1051 /* image coordnates: pixels where x=0 is the start of this waveview,
1052 * wherever it may be positioned. thus image_start=N means "an image
1053 * that begins N pixels after the start of region that this waveview is
1057 const framepos_t image_start = window_to_image (self.x0, draw_start);
1058 const framepos_t image_end = window_to_image (self.x0, draw_end);
1060 // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
1062 /* sample coordinates - note, these are not subject to rounding error
1064 * "sample_start = N" means "the first sample we need to represent is N
1065 * samples after the first sample of the region"
1068 framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
1069 framepos_t sample_end = _region_start + (image_end * _samples_per_pixel);
1071 // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
1073 /* sample_start and sample_end are bounded by the region
1074 * limits. sample_start, because of the was just computed, must already
1075 * be greater than or equal to the _region_start value.
1078 sample_end = min (region_end(), sample_end);
1080 // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
1082 double image_origin_in_self_coordinates;
1083 boost::shared_ptr<WaveViewCache::Entry> image_to_draw;
1085 if (_current_image) {
1087 /* check it covers the right sample range */
1089 if (_current_image->start > sample_start || _current_image->end < sample_end) {
1090 /* doesn't cover the area we need ... reset */
1091 _current_image.reset ();
1093 /* timestamp our continuing use of this image/cache entry */
1094 images->use (_region->audio_source (_channel), _current_image);
1095 image_to_draw = _current_image;
1099 if (!image_to_draw) {
1104 image_to_draw = get_image (sample_start, sample_end, full_image);
1106 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 image to draw = %2 (full? %3)\n", name, image_to_draw, full_image));
1108 if (!image_to_draw) {
1109 /* image not currently available. A redraw will be scheduled
1116 /* found an image that covers our entire sample range,
1117 * so keep a reference to it.
1119 _current_image = image_to_draw;
1123 /* compute the first pixel of the image that should be used when we
1124 * render the specified range.
1127 image_origin_in_self_coordinates = (image_to_draw->start - _region_start) / _samples_per_pixel;
1129 if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
1130 /* we are going to draw the first pixel for this region, but
1131 we may not want this to overlap a border around the
1132 waveform. If so, _start_shift will be set.
1134 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
1135 //draw_start += _start_shift;
1136 //image_origin_in_self_coordinates += _start_shift;
1139 /* the image may only be a best-effort ... it may not span the entire
1140 * range requested, though it is guaranteed to cover the start. So
1141 * determine how many pixels we can actually draw.
1146 if (image_to_draw != _current_image) {
1148 /* the image is guaranteed to start at or before
1149 * draw_start. But if it starts before draw_start, that reduces
1150 * the maximum available width we can render with.
1152 * so .. clamp the draw width to the smaller of what we need to
1153 * draw or the available width of the image.
1156 draw_width = min ((double) image_to_draw->image->get_width() - (draw_start - image_to_draw->start),
1157 (draw_end - draw_start));
1160 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),
1161 image_to_draw->image->get_width(), image_origin_in_self_coordinates,
1162 image_to_draw->start, _region_start));
1164 draw_width = draw_end - draw_start;
1165 DEBUG_TRACE (DEBUG::WaveView, string_compose ("use current image, span entire render width %1..%2\n", draw_start, draw_end));
1168 context->rectangle (draw_start, draw.y0, draw_width, draw.height());
1170 /* round image origin position to an exact pixel in device space to
1174 double x = self.x0 + image_origin_in_self_coordinates;
1176 context->user_to_device (x, y);
1179 context->device_to_user (x, y);
1181 /* the coordinates specify where in "user coordinates" (i.e. what we
1182 * generally call "canvas coordinates" in this code) the image origin
1183 * will appear. So specifying (10,10) will put the upper left corner of
1184 * the image at (10,10) in user space.
1187 context->set_source (image_to_draw->image, x, y);
1190 /* image obtained, some of it painted to display: we are rendered.
1191 Future calls to get_image_in_thread are now meaningful.
1198 WaveView::compute_bounding_box () const
1201 _bounding_box = Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height);
1203 _bounding_box = boost::optional<Rect> ();
1206 _bounding_box_dirty = false;
1210 WaveView::set_height (Distance height)
1212 if (height != _height) {
1215 invalidate_image_cache ();
1217 get_image_in_thread = true;
1219 _bounding_box_dirty = true;
1225 WaveView::set_channel (int channel)
1227 if (channel != _channel) {
1230 invalidate_image_cache ();
1233 _bounding_box_dirty = true;
1239 WaveView::set_logscaled (bool yn)
1241 if (_logscaled != yn) {
1242 begin_visual_change ();
1243 invalidate_image_cache ();
1245 end_visual_change ();
1250 WaveView::gain_changed ()
1252 begin_visual_change ();
1253 invalidate_image_cache ();
1254 _region_amplitude = _region->scale_amplitude ();
1255 get_image_in_thread = true;
1256 end_visual_change ();
1260 WaveView::set_zero_color (Color c)
1262 if (_zero_color != c) {
1263 begin_visual_change ();
1264 invalidate_image_cache ();
1266 end_visual_change ();
1271 WaveView::set_clip_color (Color c)
1273 if (_clip_color != c) {
1274 begin_visual_change ();
1275 invalidate_image_cache ();
1277 end_visual_change ();
1282 WaveView::set_show_zero_line (bool yn)
1284 if (_show_zero != yn) {
1285 begin_visual_change ();
1286 invalidate_image_cache ();
1288 end_visual_change ();
1293 WaveView::set_shape (Shape s)
1296 begin_visual_change ();
1297 invalidate_image_cache ();
1299 end_visual_change ();
1304 WaveView::set_amplitude_above_axis (double a)
1306 if (fabs (_amplitude_above_axis - a) > 0.01) {
1307 begin_visual_change ();
1308 invalidate_image_cache ();
1309 _amplitude_above_axis = a;
1310 get_image_in_thread = true;
1311 end_visual_change ();
1316 WaveView::set_global_shape (Shape s)
1318 if (_global_shape != s) {
1320 VisualPropertiesChanged (); /* EMIT SIGNAL */
1325 WaveView::set_global_logscaled (bool yn)
1327 if (_global_logscaled != yn) {
1328 _global_logscaled = yn;
1329 VisualPropertiesChanged (); /* EMIT SIGNAL */
1334 WaveView::region_length() const
1336 return _region->length() - (_region_start - _region->start());
1340 WaveView::region_end() const
1342 return _region_start + region_length();
1346 WaveView::set_region_start (frameoffset_t start)
1352 if (_region_start == start) {
1357 _region_start = start;
1358 _bounding_box_dirty = true;
1363 WaveView::region_resized ()
1365 /* Called when the region start or end (thus length) has changed.
1373 _region_start = _region->start();
1374 _bounding_box_dirty = true;
1379 WaveView::set_global_gradient_depth (double depth)
1381 if (_global_gradient_depth != depth) {
1382 _global_gradient_depth = depth;
1383 VisualPropertiesChanged (); /* EMIT SIGNAL */
1388 WaveView::set_global_show_waveform_clipping (bool yn)
1390 if (_global_show_waveform_clipping != yn) {
1391 _global_show_waveform_clipping = yn;
1392 ClipLevelChanged ();
1397 WaveView::set_start_shift (double pixels)
1403 begin_visual_change ();
1404 _start_shift = pixels;
1405 end_visual_change ();
1409 WaveView::cancel_my_render_request () const
1415 /* try to stop any current rendering of the request, or prevent it from
1419 if (current_request) {
1420 current_request->cancel ();
1423 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1425 /* now remove it from the queue and reset our request pointer so that
1426 have no outstanding request (that we know about)
1429 request_queue.erase (this);
1430 current_request.reset ();
1434 WaveView::set_image_cache_size (uint64_t sz)
1437 images = new WaveViewCache;
1440 images->set_image_cache_threshold (sz);
1443 /*-------------------------------------------------*/
1446 WaveView::start_drawing_thread ()
1448 if (!_drawing_thread) {
1449 _drawing_thread = Glib::Threads::Thread::create (sigc::ptr_fun (WaveView::drawing_thread));
1454 WaveView::stop_drawing_thread ()
1456 if (_drawing_thread) {
1457 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1458 g_atomic_int_set (&drawing_thread_should_quit, 1);
1459 request_cond.signal ();
1464 WaveView::drawing_thread ()
1466 using namespace Glib::Threads;
1468 WaveView const * requestor;
1469 Mutex::Lock lm (request_queue_lock);
1474 /* remember that we hold the lock at this point, no matter what */
1476 if (g_atomic_int_get (&drawing_thread_should_quit)) {
1480 if (request_queue.empty()) {
1481 request_cond.wait (request_queue_lock);
1484 /* remove the request from the queue (remember: the "request"
1485 * is just a pointer to a WaveView object)
1488 requestor = *(request_queue.begin());
1489 request_queue.erase (request_queue.begin());
1491 boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
1497 /* Generate an image. Unlock the request queue lock
1498 * while we do this, so that other things can happen
1499 * as we do rendering.
1502 request_queue_lock.unlock (); /* some RAII would be good here */
1505 requestor->generate_image (req, true);
1507 req->image.clear(); /* just in case it was set before the exception, whatever it was */
1510 request_queue_lock.lock ();
1512 req.reset (); /* drop/delete request as appropriate */
1515 /* thread is vanishing */
1516 _drawing_thread = 0;
1519 /*-------------------------------------------------*/
1521 WaveViewCache::WaveViewCache ()
1522 : image_cache_size (0)
1523 , _image_cache_threshold (100 * 1048576) /* bytes */
1527 WaveViewCache::~WaveViewCache ()
1532 boost::shared_ptr<WaveViewCache::Entry>
1533 WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
1534 framepos_t start, framepos_t end,
1539 double samples_per_pixel,
1540 bool& full_coverage)
1542 ImageCache::iterator x;
1544 if ((x = cache_map.find (src)) == cache_map.end ()) {
1545 /* nothing in the cache for this audio source at all */
1546 return boost::shared_ptr<WaveViewCache::Entry> ();
1549 CacheLine& caches = x->second;
1550 boost::shared_ptr<Entry> best_partial;
1551 framecnt_t max_coverage = 0;
1553 /* Find a suitable ImageSurface, if it exists.
1556 for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
1558 boost::shared_ptr<Entry> e (*c);
1560 if (channel != e->channel
1561 || height != e->height
1562 || amplitude != e->amplitude
1563 || samples_per_pixel != e->samples_per_pixel
1564 || fill_color != e->fill_color) {
1568 if (end <= e->end && start >= e->start) {
1569 /* found an image that covers the range we need */
1570 DEBUG_TRACE (DEBUG::WaveView, string_compose ("found image spanning %1..%2 covers %3..%4\n",
1571 e->start, e->end, start, end));
1573 full_coverage = true;
1577 if (start >= e->start) {
1578 /* found an image that covers the start, but not the
1579 * end. See if it is longer than any other similar
1580 * partial image that we've found so far.
1583 if ((e->end - e->start) > max_coverage) {
1585 max_coverage = e->end - e->start;
1591 DEBUG_TRACE (DEBUG::WaveView, string_compose ("found PARTIAL image spanning %1..%2 partially covers %3..%4\n",
1592 best_partial->start, best_partial->end, start, end));
1593 use (src, best_partial);
1594 full_coverage = false;
1595 return best_partial;
1598 return boost::shared_ptr<Entry> ();
1602 WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> src,
1607 double samples_per_pixel)
1609 list <uint32_t> deletion_list;
1610 uint32_t other_entries = 0;
1611 ImageCache::iterator x;
1613 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1615 if ((x = cache_map.find (src)) == cache_map.end ()) {
1619 CacheLine& caches = x->second;
1621 for (CacheLine::iterator c1 = caches.begin(); c1 != caches.end(); ) {
1623 CacheLine::iterator nxt = c1;
1626 boost::shared_ptr<Entry> e1 (*c1);
1628 if (channel != e1->channel
1629 || height != e1->height
1630 || amplitude != e1->amplitude
1631 || samples_per_pixel != e1->samples_per_pixel
1632 || fill_color != e1->fill_color) {
1634 /* doesn't match current properties, ignore and move on
1643 /* c1 now points to a cached image entry that matches current
1644 * properties. Check all subsequent cached imaged entries to
1645 * see if there are others that also match but represent
1646 * subsets of the range covered by this one.
1649 for (CacheLine::iterator c2 = c1; c2 != caches.end(); ) {
1651 CacheLine::iterator nxt2 = c2;
1654 boost::shared_ptr<Entry> e2 (*c2);
1656 if (e1 == e2 || channel != e2->channel
1657 || height != e2->height
1658 || amplitude != e2->amplitude
1659 || samples_per_pixel != e2->samples_per_pixel
1660 || fill_color != e2->fill_color) {
1662 /* properties do not match, ignore for the
1663 * purposes of consolidation.
1669 if (e2->start >= e1->start && e2->end <= e1->end) {
1670 /* c2 is fully contained by c1, so delete it */
1673 /* and re-start the whole iteration */
1674 nxt = caches.begin ();
1686 WaveViewCache::use (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1688 ce->timestamp = g_get_monotonic_time ();
1692 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1694 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1696 Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
1698 image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1704 ce->timestamp = g_get_monotonic_time ();
1706 cache_map[src].push_back (ce);
1710 WaveViewCache::compute_image_cache_size()
1713 for (ImageCache::iterator s = cache_map.begin(); s != cache_map.end(); ++s) {
1714 CacheLine& per_source_cache (s->second);
1715 for (CacheLine::iterator c = per_source_cache.begin(); c != per_source_cache.end(); ++c) {
1716 Cairo::RefPtr<Cairo::ImageSurface> img ((*c)->image);
1717 total += img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1724 WaveViewCache::cache_full()
1726 return image_cache_size > _image_cache_threshold;
1730 WaveViewCache::cache_flush ()
1732 /* Build a sortable list of all cache entries */
1734 CacheList cache_list;
1736 for (ImageCache::const_iterator cm = cache_map.begin(); cm != cache_map.end(); ++cm) {
1737 for (CacheLine::const_iterator cl = cm->second.begin(); cl != cm->second.end(); ++cl) {
1738 cache_list.push_back (make_pair (cm->first, *cl));
1742 /* sort list in LRU order */
1743 SortByTimestamp sorter;
1744 sort (cache_list.begin(), cache_list.end(), sorter);
1746 while (image_cache_size > _image_cache_threshold && !cache_map.empty() && !cache_list.empty()) {
1748 ListEntry& le (cache_list.front());
1750 ImageCache::iterator x;
1752 if ((x = cache_map.find (le.first)) != cache_map.end ()) {
1754 CacheLine& cl = x->second;
1756 for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
1758 if (*c == le.second) {
1760 DEBUG_TRACE (DEBUG::WaveView, string_compose ("Removing cache line entry for %1\n", x->first->name()));
1762 /* Remove this entry from this cache line */
1766 /* remove cache line from main cache: no more entries */
1767 cache_map.erase (x);
1774 Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
1775 uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1777 if (image_cache_size > size) {
1778 image_cache_size -= size;
1780 image_cache_size = 0;
1782 DEBUG_TRACE (DEBUG::WaveView, string_compose ("cache shrunk to %1\n", image_cache_size));
1785 /* Remove from the linear list, even if we didn't find it in
1786 * the actual cache_mao
1788 cache_list.erase (cache_list.begin());
1793 WaveViewCache::set_image_cache_threshold (uint64_t sz)
1795 DEBUG_TRACE (DEBUG::WaveView, string_compose ("new image cache size \n", sz));
1796 _image_cache_threshold = sz;