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/wave_view.h"
42 #include "canvas/utils.h"
43 #include "canvas/canvas.h"
44 #include "canvas/colors.h"
46 #include <gdkmm/general.h>
48 #include "gtkmm2ext/gui_thread.h"
51 using namespace ARDOUR;
52 using namespace ArdourCanvas;
54 double WaveView::_global_gradient_depth = 0.6;
55 bool WaveView::_global_logscaled = false;
56 WaveView::Shape WaveView::_global_shape = WaveView::Normal;
57 bool WaveView::_global_show_waveform_clipping = true;
58 double WaveView::_clip_level = 0.98853;
60 WaveViewCache* WaveView::images = 0;
61 gint WaveView::drawing_thread_should_quit = 0;
62 Glib::Threads::Mutex WaveView::request_queue_lock;
63 Glib::Threads::Cond WaveView::request_cond;
64 Glib::Threads::Thread* WaveView::_drawing_thread = 0;
65 WaveView::DrawingRequestQueue WaveView::request_queue;
67 PBD::Signal0<void> WaveView::VisualPropertiesChanged;
68 PBD::Signal0<void> WaveView::ClipLevelChanged;
70 WaveView::WaveView (Canvas* c, boost::shared_ptr<ARDOUR::AudioRegion> region)
74 , _samples_per_pixel (0)
77 , _zero_color (0xff0000ff)
78 , _clip_color (0xff0000ff)
79 , _logscaled (_global_logscaled)
80 , _shape (_global_shape)
81 , _gradient_depth (_global_gradient_depth)
82 , _shape_independent (false)
83 , _logscaled_independent (false)
84 , _gradient_depth_independent (false)
85 , _amplitude_above_axis (1.0)
86 , _region_amplitude (region->scale_amplitude ())
88 , _region_start (region->start())
89 , get_image_in_thread (false)
92 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
93 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
95 ImageReady.connect (image_ready_connection, MISSING_INVALIDATOR, boost::bind (&WaveView::image_ready, this), gui_context());
98 WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
102 , _samples_per_pixel (0)
105 , _zero_color (0xff0000ff)
106 , _clip_color (0xff0000ff)
107 , _logscaled (_global_logscaled)
108 , _shape (_global_shape)
109 , _gradient_depth (_global_gradient_depth)
110 , _shape_independent (false)
111 , _logscaled_independent (false)
112 , _gradient_depth_independent (false)
113 , _amplitude_above_axis (1.0)
114 , _region_amplitude (region->scale_amplitude ())
115 , _region_start (region->start())
116 , get_image_in_thread (false)
119 VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
120 ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
122 ImageReady.connect (image_ready_connection, MISSING_INVALIDATOR, boost::bind (&WaveView::image_ready, this), gui_context());
125 WaveView::~WaveView ()
127 invalidate_image_cache ();
131 WaveView::debug_name() const
133 return _region->name() + string (":") + PBD::to_string (_channel+1, std::dec);
137 WaveView::image_ready ()
143 WaveView::handle_visual_property_change ()
145 bool changed = false;
147 if (!_shape_independent && (_shape != global_shape())) {
148 _shape = global_shape();
152 if (!_logscaled_independent && (_logscaled != global_logscaled())) {
153 _logscaled = global_logscaled();
157 if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
158 _gradient_depth = global_gradient_depth();
163 begin_visual_change ();
164 invalidate_image_cache ();
165 end_visual_change ();
170 WaveView::handle_clip_level_change ()
172 begin_visual_change ();
173 invalidate_image_cache ();
174 end_visual_change ();
178 WaveView::set_fill_color (Color c)
180 if (c != _fill_color) {
181 begin_visual_change ();
182 invalidate_image_cache ();
183 Fill::set_fill_color (c);
184 end_visual_change ();
189 WaveView::set_outline_color (Color c)
191 if (c != _outline_color) {
192 begin_visual_change ();
193 invalidate_image_cache ();
194 Outline::set_outline_color (c);
195 end_visual_change ();
200 WaveView::set_samples_per_pixel (double samples_per_pixel)
202 if (samples_per_pixel != _samples_per_pixel) {
205 invalidate_image_cache ();
206 _samples_per_pixel = samples_per_pixel;
207 _bounding_box_dirty = true;
214 _log_meter (float power, double lower_db, double upper_db, double non_linearity)
216 return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
220 alt_log_meter (float power)
222 return _log_meter (power, -192.0, 0.0, 8.0);
226 WaveView::set_clip_level (double dB)
228 const double clip_level = dB_to_coefficient (dB);
229 if (clip_level != _clip_level) {
230 _clip_level = clip_level;
236 WaveView::invalidate_image_cache ()
238 cancel_my_render_request ();
239 _current_image.reset ();
243 WaveView::y_extent (double s, bool /*round_to_lower_edge*/) const
245 /* it is important that this returns an integral value, so that we
246 * can ensure correct single pixel behaviour.
248 * we need (_height - max(wave_line_width))
249 * wave_line_width == 1 IFF top==bottom (1 sample per pixel or flat line)
250 * wave_line_width == 2 otherwise
251 * then round away from the zero line, towards peak
253 if (_shape == Rectified) {
254 // we only ever have 1 point and align to the bottom (not center)
255 return floor ((1.0 - s) * (_height - 2.0));
257 /* currently canvas rectangle is off-by-one and we
258 * cannot draw a pixel at 0 (-.5 .. +.5) without it being
259 * clipped. A value 1.0 (ideally one point at y=0) ends
260 * up a pixel down. and a value of -1.0 (ideally y = _height-1)
261 * currently is on the bottom separator line :(
262 * So to make the complete waveform appear centered in
263 * a region, we translate by +.5 (instead of -.5)
264 * and waste two pixel of height: -4 (instad of -2)
266 * This needs fixing in canvas/rectangle the intersect
267 * functions and probably a couple of other places as well...
271 pos = ceil ((1.0 - s) * .5 * (_height - 4.0));
273 pos = floor ((1.0 - s) * .5 * (_height - 4.0));
275 return min (_height - 4.0, (max (0.0, pos)));
280 WaveView::draw_absent_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
282 Cairo::RefPtr<Cairo::ImageSurface> stripe = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
284 Cairo::RefPtr<Cairo::Context> stripe_context = Cairo::Context::create (stripe);
285 stripe_context->set_antialias (Cairo::ANTIALIAS_NONE);
287 uint32_t stripe_separation = 150;
288 double start = - floor (_height / stripe_separation) * stripe_separation;
291 while (start < n_peaks) {
293 stripe_context->move_to (start, 0);
294 stripe_x = start + _height;
295 stripe_context->line_to (stripe_x, _height);
296 start += stripe_separation;
299 stripe_context->set_source_rgba (1.0, 1.0, 1.0, 1.0);
300 stripe_context->set_line_cap (Cairo::LINE_CAP_SQUARE);
301 stripe_context->set_line_width(50);
302 stripe_context->stroke();
304 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
306 context->set_source_rgba (1.0, 1.0, 0.0, 0.3);
307 context->mask (stripe, 0, 0);
318 LineTips() : top (0.0), bot (0.0), clip_max (false), clip_min (false) {}
322 Cairo::RefPtr<Cairo::ImageSurface> wave;
323 Cairo::RefPtr<Cairo::ImageSurface> outline;
324 Cairo::RefPtr<Cairo::ImageSurface> clip;
325 Cairo::RefPtr<Cairo::ImageSurface> zero;
328 wave (0), outline (0), clip (0), zero (0) {}
332 WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks, boost::shared_ptr<WaveViewThreadRequest> req) const
337 images.wave = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
338 images.outline = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
339 images.clip = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
340 images.zero = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
342 Cairo::RefPtr<Cairo::Context> wave_context = Cairo::Context::create (images.wave);
343 Cairo::RefPtr<Cairo::Context> outline_context = Cairo::Context::create (images.outline);
344 Cairo::RefPtr<Cairo::Context> clip_context = Cairo::Context::create (images.clip);
345 Cairo::RefPtr<Cairo::Context> zero_context = Cairo::Context::create (images.zero);
346 wave_context->set_antialias (Cairo::ANTIALIAS_NONE);
347 outline_context->set_antialias (Cairo::ANTIALIAS_NONE);
348 clip_context->set_antialias (Cairo::ANTIALIAS_NONE);
349 zero_context->set_antialias (Cairo::ANTIALIAS_NONE);
351 boost::scoped_array<LineTips> tips (new LineTips[n_peaks]);
353 /* Clip level nominally set to -0.9dBFS to account for inter-sample
354 interpolation possibly clipping (value may be too low).
356 We adjust by the region's own gain (but note: not by any gain
357 automation or its gain envelope) so that clip indicators are closer
358 to providing data about on-disk data. This multiplication is
359 needed because the data we get from AudioRegion::read_peaks()
360 has been scaled by scale_amplitude() already.
363 const double clip_level = _clip_level * _region_amplitude;
365 if (_shape == WaveView::Rectified) {
367 /* each peak is a line from the bottom of the waveview
368 * to a point determined by max (_peaks[i].max,
373 for (int i = 0; i < n_peaks; ++i) {
375 tips[i].bot = height() - 1.0;
376 const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
377 tips[i].top = y_extent (p, false);
378 tips[i].spread = p * (_height - 1.0);
380 if (_peaks[i].max >= clip_level) {
381 tips[i].clip_max = true;
384 if (-(_peaks[i].min) >= clip_level) {
385 tips[i].clip_min = true;
390 for (int i = 0; i < n_peaks; ++i) {
392 tips[i].bot = height() - 1.0;
393 const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
394 tips[i].top = y_extent (p, false);
395 tips[i].spread = p * (_height - 2.0);
396 if (p >= clip_level) {
397 tips[i].clip_max = true;
406 for (int i = 0; i < n_peaks; ++i) {
407 double top = _peaks[i].max;
408 double bot = _peaks[i].min;
410 if (_peaks[i].max >= clip_level) {
411 tips[i].clip_max = true;
413 if (-(_peaks[i].min) >= clip_level) {
414 tips[i].clip_min = true;
418 top = alt_log_meter (fast_coefficient_to_dB (top));
419 } else if (top < 0.0) {
420 top =-alt_log_meter (fast_coefficient_to_dB (-top));
426 bot = alt_log_meter (fast_coefficient_to_dB (bot));
427 } else if (bot < 0.0) {
428 bot = -alt_log_meter (fast_coefficient_to_dB (-bot));
433 tips[i].top = y_extent (top, false);
434 tips[i].bot = y_extent (bot, true);
435 tips[i].spread = tips[i].bot - tips[i].top;
439 for (int i = 0; i < n_peaks; ++i) {
440 if (_peaks[i].max >= clip_level) {
441 tips[i].clip_max = true;
443 if (-(_peaks[i].min) >= clip_level) {
444 tips[i].clip_min = true;
447 tips[i].top = y_extent (_peaks[i].max, false);
448 tips[i].bot = y_extent (_peaks[i].min, true);
449 tips[i].spread = tips[i].bot - tips[i].top;
455 if (req->should_stop()) {
459 Color alpha_one = rgba_to_color (0, 0, 0, 1.0);
461 set_source_rgba (wave_context, alpha_one);
462 set_source_rgba (outline_context, alpha_one);
463 set_source_rgba (clip_context, alpha_one);
464 set_source_rgba (zero_context, alpha_one);
466 /* ensure single-pixel lines */
468 wave_context->set_line_width (1.0);
469 wave_context->translate (0.5, +1.5);
471 outline_context->set_line_width (1.0);
472 outline_context->translate (0.5, +1.5);
474 clip_context->set_line_width (1.0);
475 clip_context->translate (0.5, +1.5);
477 zero_context->set_line_width (1.0);
478 zero_context->translate (0.5, +1.5);
480 /* the height of the clip-indicator should be at most 7 pixels,
481 * or 5% of the height of the waveview item.
484 const double clip_height = min (7.0, ceil (_height * 0.05));
486 /* There are 3 possible components to draw at each x-axis position: the
487 waveform "line", the zero line and an outline/clip indicator. We
488 have to decide which of the 3 to draw at each position, pixel by
489 pixel. This makes the rendering less efficient but it is the only
490 way I can see to do this correctly.
492 To avoid constant source swapping and stroking, we draw the components separately
493 onto four alpha only image surfaces for use as a mask.
495 With only 1 pixel of spread between the top and bottom of the line,
496 we just draw the upper outline/clip indicator.
498 With 2 pixels of spread, we draw the upper and lower outline clip
501 With 3 pixels of spread we draw the upper and lower outline/clip
502 indicators and at least 1 pixel of the waveform line.
504 With 5 pixels of spread, we draw all components.
506 We can do rectified as two separate passes because we have a much
507 easier decision regarding whether to draw the waveform line. We
508 always draw the clip/outline indicators.
511 if (_shape == WaveView::Rectified) {
513 for (int i = 0; i < n_peaks; ++i) {
517 if (tips[i].spread >= 1.0) {
518 wave_context->move_to (i, tips[i].top);
519 wave_context->line_to (i, tips[i].bot);
524 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
525 clip_context->move_to (i, tips[i].top);
526 /* clip-indicating upper terminal line */
527 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + .5)));
529 outline_context->move_to (i, tips[i].top);
530 /* normal upper terminal dot */
531 outline_context->rel_line_to (0, -1.0);
535 wave_context->stroke ();
536 clip_context->stroke ();
537 outline_context->stroke ();
540 const double height_2 = (_height - 2.5) * .5;
542 for (int i = 0; i < n_peaks; ++i) {
546 if (tips[i].spread >= 2.0) {
547 wave_context->move_to (i, tips[i].top);
548 wave_context->line_to (i, tips[i].bot);
550 /* draw square waves and other discontiguous points clearly */
552 if (tips[i-1].top + 2 < tips[i].top) {
553 wave_context->move_to (i-1, tips[i-1].top);
554 wave_context->line_to (i-1, (tips[i].bot + tips[i-1].top)/2);
555 wave_context->move_to (i, (tips[i].bot + tips[i-1].top)/2);
556 wave_context->line_to (i, tips[i].top);
557 } else if (tips[i-1].bot > tips[i].bot + 2) {
558 wave_context->move_to (i-1, tips[i-1].bot);
559 wave_context->line_to (i-1, (tips[i].top + tips[i-1].bot)/2);
560 wave_context->move_to (i, (tips[i].top + tips[i-1].bot)/2);
561 wave_context->line_to (i, tips[i].bot);
567 if (tips[i].spread >= 5.0 && show_zero_line()) {
568 zero_context->move_to (i, floor(height_2));
569 zero_context->rel_line_to (1.0, 0);
572 if (tips[i].spread > 1.0) {
573 bool clipped = false;
574 /* outline/clip indicators */
575 if (_global_show_waveform_clipping && tips[i].clip_max) {
576 clip_context->move_to (i, tips[i].top);
577 /* clip-indicating upper terminal line */
578 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + 0.5)));
582 if (_global_show_waveform_clipping && tips[i].clip_min) {
583 clip_context->move_to (i, tips[i].bot);
584 /* clip-indicating lower terminal line */
585 clip_context->rel_line_to (0, - min (clip_height, ceil(tips[i].spread + 0.5)));
590 outline_context->move_to (i, tips[i].bot + 1.0);
591 /* normal lower terminal dot */
592 outline_context->rel_line_to (0, -1.0);
594 outline_context->move_to (i, tips[i].top - 1.0);
595 /* normal upper terminal dot */
596 outline_context->rel_line_to (0, 1.0);
599 bool clipped = false;
600 /* outline/clip indicator */
601 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
602 clip_context->move_to (i, tips[i].top);
603 /* clip-indicating upper / lower terminal line */
604 clip_context->rel_line_to (0, 1.0);
609 wave_context->move_to (i, tips[i].top);
610 /* special case where outline only is drawn.
611 * we draw a 1px "line", pretending that the span is 1.0
613 wave_context->rel_line_to (0, 1.0);
618 wave_context->stroke ();
619 outline_context->stroke ();
620 clip_context->stroke ();
621 zero_context->stroke ();
624 if (req->should_stop()) {
628 Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
630 /* Here we set a source colour and use the various components as a mask. */
632 if (gradient_depth() != 0.0) {
634 Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _height));
640 if (_shape == Rectified) {
650 color_to_rgba (_fill_color, r, g, b, a);
651 gradient->add_color_stop_rgba (stops[1], r, g, b, a);
652 /* generate a new color for the middle of the gradient */
654 color_to_hsv (_fill_color, h, s, v);
655 /* change v towards white */
656 v *= 1.0 - gradient_depth();
657 Color center = hsva_to_color (h, s, v, a);
658 color_to_rgba (center, r, g, b, a);
660 gradient->add_color_stop_rgba (stops[0], r, g, b, a);
661 gradient->add_color_stop_rgba (stops[2], r, g, b, a);
663 context->set_source (gradient);
665 set_source_rgba (context, _fill_color);
668 if (req->should_stop()) {
672 context->mask (images.wave, 0, 0);
675 set_source_rgba (context, _outline_color);
676 context->mask (images.outline, 0, 0);
679 set_source_rgba (context, _clip_color);
680 context->mask (images.clip, 0, 0);
683 set_source_rgba (context, _zero_color);
684 context->mask (images.zero, 0, 0);
688 boost::shared_ptr<WaveViewCache::Entry>
689 WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) const
691 boost::shared_ptr<WaveViewCache::Entry> ret (new WaveViewCache::Entry (req->channel,
693 req->region_amplitude,
695 req->samples_per_pixel,
700 images = new WaveViewCache;
703 images->add (_region->audio_source (_channel), ret);
705 /* consolidate cache first (removes fully-contained
709 images->consolidate_image_cache (_region->audio_source (_channel),
710 _channel, _height, _region_amplitude,
711 _fill_color, _samples_per_pixel);
716 boost::shared_ptr<WaveViewCache::Entry>
717 WaveView::get_image (framepos_t start, framepos_t end) const
719 boost::shared_ptr<WaveViewCache::Entry> ret;
721 /* this is called from a ::render() call, when we need an image to
726 Glib::Threads::Mutex::Lock lmq (request_queue_lock);
728 /* if there's a draw request outstanding, check to see if we
729 * have an image there. if so, use it (and put it in the cache
733 if (current_request && !current_request->should_stop() && current_request->image) {
735 /* put the image into the cache so that other
736 * WaveViews can use it if it is useful
739 if (current_request->start <= start && current_request->end >= end) {
741 ret.reset (new WaveViewCache::Entry (current_request->channel,
742 current_request->height,
743 current_request->region_amplitude,
744 current_request->fill_color,
745 current_request->samples_per_pixel,
746 current_request->start,
747 current_request->end,
748 current_request->image));
750 cache_request_result (current_request);
753 /* drop our handle on the current request */
754 current_request.reset ();
760 /* no current image draw request, so look in the cache */
762 ret = get_image_from_cache (start, end);
768 if (get_image_in_thread) {
770 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
772 req->type = WaveViewThreadRequest::Draw;
775 req->samples_per_pixel = _samples_per_pixel;
776 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
777 req->channel = _channel;
778 req->width = _canvas->visible_area().width();
779 req->height = _height;
780 req->fill_color = _fill_color;
781 req->region_amplitude = _region_amplitude;
783 /* draw image in this (the GUI thread) */
785 generate_image (req, false);
787 /* cache the result */
789 ret = cache_request_result (req);
791 /* reset this so that future missing images are
792 * generated in a a worker thread.
795 get_image_in_thread = false;
798 queue_get_image (_region, start, end);
806 boost::shared_ptr<WaveViewCache::Entry>
807 WaveView::get_image_from_cache (framepos_t start, framepos_t end) const
810 return boost::shared_ptr<WaveViewCache::Entry>();
813 return images->lookup_image (_region->audio_source (_channel), start, end, _channel,
814 _height, _region_amplitude, _fill_color, _samples_per_pixel);
818 WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, framepos_t start, framepos_t end) const
820 boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
822 req->type = WaveViewThreadRequest::Draw;
825 req->samples_per_pixel = _samples_per_pixel;
826 req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
827 req->channel = _channel;
828 req->width = _canvas->visible_area().width();
829 req->height = _height;
830 req->fill_color = _fill_color;
831 req->region_amplitude = _region_amplitude;
837 WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_render_thread) const
839 if (!req->should_stop()) {
841 /* sample position is canonical here, and we want to generate
842 * an image that spans about twice the canvas width
845 const framepos_t center = req->start + ((req->end - req->start) / 2);
846 const framecnt_t image_samples = req->width * req->samples_per_pixel; /* one canvas width */
848 /* we can request data from anywhere in the Source, between 0 and its length
851 framepos_t sample_start = max (_region_start, (center - image_samples));
852 framepos_t sample_end = min (center + image_samples, region_end());
853 const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
855 boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
857 /* Note that Region::read_peaks() takes a start position based on an
858 offset into the Region's **SOURCE**, rather than an offset into
862 framecnt_t peaks_read = _region->read_peaks (peaks.get(), n_peaks,
863 sample_start, sample_end - sample_start,
865 req->samples_per_pixel);
867 // apply waveform amplitude zoom multiplier
869 req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
870 /* make sure we record the sample positions that were actually used */
871 req->start = sample_start;
872 req->end = sample_end;
874 if (peaks_read > 0) {
876 for (framecnt_t i = 0; i < peaks_read; ++i) {
877 peaks[i].max *= _amplitude_above_axis;
878 peaks[i].min *= _amplitude_above_axis;
881 draw_image (req->image, peaks.get(), n_peaks, req);
883 draw_absent_image (req->image, peaks.get(), n_peaks);
887 if (in_render_thread && !req->should_stop()) {
888 const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
894 /** Given a waveform that starts at window x-coordinate @param wave_origin
895 * and the first pixel that we will actually draw @param draw_start, return
896 * the offset into an image of the entire waveform that we will need to use.
898 * Note: most of our cached images are NOT of the entire waveform, this is just
899 * computationally useful when determining which the sample range span for
903 window_to_image (double wave_origin, double image_start)
905 return image_start - wave_origin;
909 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
911 assert (_samples_per_pixel != 0);
914 /* first image generation should happen in RENDER thread */
915 get_image_in_thread = false;
916 rendered = true; /* comments in header file */
923 /* a WaveView is intimately connected to an AudioRegion. It will
924 * display the waveform within the region, anywhere from the start of
925 * the region to its end.
927 * the area we've been aked to render may overlap with area covered
928 * by the region in any of the normal ways:
930 * - it may begin and end within the area covered by the region
931 * - it may start before and end after the area covered by region
932 * - it may start before and end within the area covered by the region
933 * - it may start within and end after the area covered by the region
934 * - it may be precisely coincident with the area covered by region.
936 * So let's start by determining the area covered by the region, in
937 * window coordinates. It begins at zero (in item coordinates for this
938 * waveview, and extends to region_length() / _samples_per_pixel.
941 Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
943 /* Now lets get the intersection with the area we've been asked to draw */
945 boost::optional<Rect> d = self.intersection (area);
953 /* "draw" is now a rectangle that defines the rectangle we need to
954 * update/render the waveview into, in window coordinate space.
957 /* window coordinates - pixels where x=0 is the left edge of the canvas
958 * window. We round down in case we were asked to
959 * draw "between" pixels at the start and/or end.
962 double draw_start = floor (draw.x0);
963 const double draw_end = floor (draw.x1);
965 // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
967 /* image coordnates: pixels where x=0 is the start of this waveview,
968 * wherever it may be positioned. thus image_start=N means "an image
969 * that begins N pixels after the start of region that this waveview is
973 const framepos_t image_start = window_to_image (self.x0, draw_start);
974 const framepos_t image_end = window_to_image (self.x0, draw_end);
976 // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
978 /* sample coordinates - note, these are not subject to rounding error
980 * "sample_start = N" means "the first sample we need to represent is N
981 * samples after the first sample of the region"
984 framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
985 framepos_t sample_end = _region_start + (image_end * _samples_per_pixel);
987 // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
989 /* sample_start and sample_end are bounded by the region
990 * limits. sample_start, because of the was just computed, must already
991 * be greater than or equal to the _region_start value.
994 sample_end = min (region_end(), sample_end);
996 // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
1000 if (_current_image) {
1002 /* check it covers the right sample range */
1004 if (_current_image->start > sample_start || _current_image->end < sample_end) {
1005 /* doesn't cover the area we need ... reset */
1006 _current_image.reset ();
1008 /* timestamp our continuing use of this image/cache entry */
1009 images->use (_region->audio_source (_channel), _current_image);
1013 if (!_current_image) {
1017 _current_image = get_image (sample_start, sample_end);
1019 if (!_current_image) {
1020 /* image not currently available. A redraw will be scheduled
1027 /* fix up offset: returned value is the first sample of the returned image */
1029 image_offset = (_current_image->start - _region_start) / _samples_per_pixel;
1031 // cerr << "Offset into image to place at zero: " << image_offset << endl;
1033 if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
1034 /* we are going to draw the first pixel for this region, but
1035 we may not want this to overlap a border around the
1036 waveform. If so, _start_shift will be set.
1038 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
1039 //draw_start += _start_shift;
1040 //image_offset += _start_shift;
1043 context->rectangle (draw_start, draw.y0, draw_end - draw_start, draw.height());
1045 /* round image origin position to an exact pixel in device space to
1049 double x = self.x0 + image_offset;
1051 context->user_to_device (x, y);
1054 context->device_to_user (x, y);
1056 context->set_source (_current_image->image, x, y);
1062 WaveView::compute_bounding_box () const
1065 _bounding_box = Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height);
1067 _bounding_box = boost::optional<Rect> ();
1070 _bounding_box_dirty = false;
1074 WaveView::set_height (Distance height)
1076 if (height != _height) {
1079 invalidate_image_cache ();
1081 get_image_in_thread = true;
1083 _bounding_box_dirty = true;
1089 WaveView::set_channel (int channel)
1091 if (channel != _channel) {
1094 invalidate_image_cache ();
1097 _bounding_box_dirty = true;
1103 WaveView::set_logscaled (bool yn)
1105 if (_logscaled != yn) {
1106 begin_visual_change ();
1107 invalidate_image_cache ();
1109 end_visual_change ();
1114 WaveView::gain_changed ()
1116 begin_visual_change ();
1117 invalidate_image_cache ();
1118 _region_amplitude = _region->scale_amplitude ();
1119 end_visual_change ();
1123 WaveView::set_zero_color (Color c)
1125 if (_zero_color != c) {
1126 begin_visual_change ();
1127 invalidate_image_cache ();
1129 end_visual_change ();
1134 WaveView::set_clip_color (Color c)
1136 if (_clip_color != c) {
1137 begin_visual_change ();
1138 invalidate_image_cache ();
1140 end_visual_change ();
1145 WaveView::set_show_zero_line (bool yn)
1147 if (_show_zero != yn) {
1148 begin_visual_change ();
1149 invalidate_image_cache ();
1151 end_visual_change ();
1156 WaveView::set_shape (Shape s)
1159 begin_visual_change ();
1160 invalidate_image_cache ();
1162 end_visual_change ();
1167 WaveView::set_amplitude_above_axis (double a)
1169 if (fabs (_amplitude_above_axis - a) > 0.01) {
1170 begin_visual_change ();
1171 invalidate_image_cache ();
1172 _amplitude_above_axis = a;
1173 end_visual_change ();
1178 WaveView::set_global_shape (Shape s)
1180 if (_global_shape != s) {
1182 VisualPropertiesChanged (); /* EMIT SIGNAL */
1187 WaveView::set_global_logscaled (bool yn)
1189 if (_global_logscaled != yn) {
1190 _global_logscaled = yn;
1191 VisualPropertiesChanged (); /* EMIT SIGNAL */
1196 WaveView::region_length() const
1198 return _region->length() - (_region_start - _region->start());
1202 WaveView::region_end() const
1204 return _region_start + region_length();
1208 WaveView::set_region_start (frameoffset_t start)
1214 if (_region_start == start) {
1219 _region_start = start;
1220 _bounding_box_dirty = true;
1225 WaveView::region_resized ()
1227 /* Called when the region start or end (thus length) has changed.
1235 _region_start = _region->start();
1236 _bounding_box_dirty = true;
1241 WaveView::set_global_gradient_depth (double depth)
1243 if (_global_gradient_depth != depth) {
1244 _global_gradient_depth = depth;
1245 VisualPropertiesChanged (); /* EMIT SIGNAL */
1250 WaveView::set_global_show_waveform_clipping (bool yn)
1252 if (_global_show_waveform_clipping != yn) {
1253 _global_show_waveform_clipping = yn;
1254 ClipLevelChanged ();
1259 WaveView::set_start_shift (double pixels)
1265 begin_visual_change ();
1266 _start_shift = pixels;
1267 end_visual_change ();
1272 WaveView::cancel_my_render_request () const
1278 /* try to stop any current rendering of the request, or prevent it from
1282 if (current_request) {
1283 current_request->cancel ();
1286 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1288 /* now remove it from the queue and reset our request pointer so that
1289 have no outstanding request (that we know about)
1292 request_queue.erase (this);
1293 current_request.reset ();
1297 WaveView::send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1299 if (req->type == WaveViewThreadRequest::Draw && current_request) {
1300 /* this will stop rendering in progress (which might otherwise
1301 be long lived) for any current request.
1303 current_request->cancel ();
1306 start_drawing_thread ();
1308 Glib::signal_idle().connect (sigc::bind (sigc::mem_fun (this, &WaveView::idle_send_request), req));
1312 WaveView::idle_send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1315 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1316 /* swap requests (protected by lock) */
1317 current_request = req;
1318 request_queue.insert (this);
1321 request_cond.signal (); /* wake thread */
1323 return false; /* do not call from idle again */
1326 /*-------------------------------------------------*/
1329 WaveView::start_drawing_thread ()
1331 if (!_drawing_thread) {
1332 _drawing_thread = Glib::Threads::Thread::create (sigc::ptr_fun (WaveView::drawing_thread));
1337 WaveView::stop_drawing_thread ()
1339 if (_drawing_thread) {
1340 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1341 g_atomic_int_set (&drawing_thread_should_quit, 1);
1342 request_cond.signal ();
1347 WaveView::drawing_thread ()
1349 using namespace Glib::Threads;
1351 WaveView const * requestor;
1352 Mutex::Lock lm (request_queue_lock);
1357 /* remember that we hold the lock at this point, no matter what */
1359 if (g_atomic_int_get (&drawing_thread_should_quit)) {
1363 if (request_queue.empty()) {
1364 request_cond.wait (request_queue_lock);
1367 /* remove the request from the queue (remember: the "request"
1368 * is just a pointer to a WaveView object)
1371 requestor = *(request_queue.begin());
1372 request_queue.erase (request_queue.begin());
1374 boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
1380 /* Generate an image. Unlock the request queue lock
1381 * while we do this, so that other things can happen
1382 * as we do rendering.
1385 request_queue_lock.unlock (); /* some RAII would be good here */
1388 requestor->generate_image (req, true);
1390 req->image.clear(); /* just in case it was set before the exception, whatever it was */
1393 request_queue_lock.lock ();
1395 req.reset (); /* drop/delete request as appropriate */
1398 /* thread is vanishing */
1399 _drawing_thread = 0;
1402 /*-------------------------------------------------*/
1404 WaveViewCache::WaveViewCache ()
1405 : image_cache_size (0)
1406 , _image_cache_threshold (100 * 1048576) /* bytes */
1410 WaveViewCache::~WaveViewCache ()
1415 boost::shared_ptr<WaveViewCache::Entry>
1416 WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
1417 framepos_t start, framepos_t end,
1422 double samples_per_pixel)
1424 ImageCache::iterator x;
1426 if ((x = cache_map.find (src)) == cache_map.end ()) {
1427 /* nothing in the cache for this audio source at all */
1428 return boost::shared_ptr<WaveViewCache::Entry> ();
1431 CacheLine& caches = x->second;
1433 /* Find a suitable ImageSurface, if it exists.
1436 for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
1438 boost::shared_ptr<Entry> e (*c);
1440 if (channel != e->channel
1441 || height != e->height
1442 || amplitude != e->amplitude
1443 || samples_per_pixel != e->samples_per_pixel
1444 || fill_color != e->fill_color) {
1448 if (end <= e->end && start >= e->start) {
1449 /* found an image that covers the range we need */
1455 return boost::shared_ptr<Entry> ();
1459 WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> src,
1464 double samples_per_pixel)
1466 list <uint32_t> deletion_list;
1467 uint32_t other_entries = 0;
1468 ImageCache::iterator x;
1470 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1472 if ((x = cache_map.find (src)) == cache_map.end ()) {
1476 CacheLine& caches = x->second;
1478 for (CacheLine::iterator c1 = caches.begin(); c1 != caches.end(); ) {
1480 CacheLine::iterator nxt = c1;
1483 boost::shared_ptr<Entry> e1 (*c1);
1485 if (channel != e1->channel
1486 || height != e1->height
1487 || amplitude != e1->amplitude
1488 || samples_per_pixel != e1->samples_per_pixel
1489 || fill_color != e1->fill_color) {
1491 /* doesn't match current properties, ignore and move on
1500 /* c1 now points to a cached image entry that matches current
1501 * properties. Check all subsequent cached imaged entries to
1502 * see if there are others that also match but represent
1503 * subsets of the range covered by this one.
1506 for (CacheLine::iterator c2 = c1; c2 != caches.end(); ) {
1508 CacheLine::iterator nxt2 = c2;
1511 boost::shared_ptr<Entry> e2 (*c2);
1513 if (e1 == e2 || channel != e2->channel
1514 || height != e2->height
1515 || amplitude != e2->amplitude
1516 || samples_per_pixel != e2->samples_per_pixel
1517 || fill_color != e2->fill_color) {
1519 /* properties do not match, ignore for the
1520 * purposes of consolidation.
1526 if (e2->start >= e1->start && e2->end <= e1->end) {
1527 /* c2 is fully contained by c1, so delete it */
1528 c2 = caches.erase (c2);
1540 WaveViewCache::use (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1542 ce->timestamp = g_get_monotonic_time ();
1546 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1548 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1550 Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
1552 image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1558 ce->timestamp = g_get_monotonic_time ();
1560 cache_map[src].push_back (ce);
1561 cache_list.push_back (make_pair (src, ce));
1565 WaveViewCache::compute_image_cache_size()
1568 for (ImageCache::iterator s = cache_map.begin(); s != cache_map.end(); ++s) {
1569 CacheLine& per_source_cache (s->second);
1570 for (CacheLine::iterator c = per_source_cache.begin(); c != per_source_cache.end(); ++c) {
1571 Cairo::RefPtr<Cairo::ImageSurface> img ((*c)->image);
1572 total += img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1579 WaveViewCache::cache_full()
1581 return image_cache_size > _image_cache_threshold;
1585 WaveViewCache::cache_flush ()
1587 SortByTimestamp sorter;
1589 /* sort list in LRU order */
1591 sort (cache_list.begin(), cache_list.end(), sorter);
1593 while (image_cache_size > _image_cache_threshold) {
1595 ListEntry& le (cache_list.front());
1597 ImageCache::iterator x;
1599 if ((x = cache_map.find (le.first)) == cache_map.end ()) {
1600 /* wierd ... no entry for this AudioSource */
1604 CacheLine& cl = x->second;
1606 for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
1608 if (*c == le.second) {
1610 /* Remove this entry from this cache line */
1614 /* remove cache line from main cache: no more entries */
1615 cache_map.erase (x);
1622 Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
1623 uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1625 if (image_cache_size > size) {
1626 image_cache_size -= size;
1628 image_cache_size = 0;
1631 /* Remove from the linear list */
1632 cache_list.erase (cache_list.begin());
1637 WaveViewCache::set_image_cache_threshold (uint64_t sz)
1639 _image_cache_threshold = sz;