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());
854 const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
856 boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
858 /* Note that Region::read_peaks() takes a start position based on an
859 offset into the Region's **SOURCE**, rather than an offset into
863 _region->read_peaks (peaks.get(), n_peaks,
864 sample_start, sample_end - sample_start,
866 req->samples_per_pixel);
869 // apply waveform amplitude zoom multiplier
871 for (int i = 0; i < n_peaks; ++i) {
872 peaks[i].max *= _amplitude_above_axis;
873 peaks[i].min *= _amplitude_above_axis;
876 req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
878 /* make sure we record the sample positions that were actually used */
880 req->start = sample_start;
881 req->end = sample_end;
883 draw_image (req->image, peaks.get(), n_peaks, req);
886 if (in_render_thread && !req->should_stop()) {
887 const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
893 /** Given a waveform that starts at window x-coordinate @param wave_origin
894 * and the first pixel that we will actually draw @param draw_start, return
895 * the offset into an image of the entire waveform that we will need to use.
897 * Note: most of our cached images are NOT of the entire waveform, this is just
898 * computationally useful when determining which the sample range span for
902 window_to_image (double wave_origin, double image_start)
904 return image_start - wave_origin;
908 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
910 assert (_samples_per_pixel != 0);
913 /* first image generation should happen in RENDER thread */
914 get_image_in_thread = false;
915 rendered = true; /* comments in header file */
922 /* a WaveView is intimately connected to an AudioRegion. It will
923 * display the waveform within the region, anywhere from the start of
924 * the region to its end.
926 * the area we've been aked to render may overlap with area covered
927 * by the region in any of the normal ways:
929 * - it may begin and end within the area covered by the region
930 * - it may start before and end after the area covered by region
931 * - it may start before and end within the area covered by the region
932 * - it may start within and end after the area covered by the region
933 * - it may be precisely coincident with the area covered by region.
935 * So let's start by determining the area covered by the region, in
936 * window coordinates. It begins at zero (in item coordinates for this
937 * waveview, and extends to region_length() / _samples_per_pixel.
940 Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
942 /* Now lets get the intersection with the area we've been asked to draw */
944 boost::optional<Rect> d = self.intersection (area);
952 /* "draw" is now a rectangle that defines the rectangle we need to
953 * update/render the waveview into, in window coordinate space.
956 /* window coordinates - pixels where x=0 is the left edge of the canvas
957 * window. We round down in case we were asked to
958 * draw "between" pixels at the start and/or end.
961 double draw_start = floor (draw.x0);
962 const double draw_end = floor (draw.x1);
964 // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
966 /* image coordnates: pixels where x=0 is the start of this waveview,
967 * wherever it may be positioned. thus image_start=N means "an image
968 * that begins N pixels after the start of region that this waveview is
972 const framepos_t image_start = window_to_image (self.x0, draw_start);
973 const framepos_t image_end = window_to_image (self.x0, draw_end);
975 // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
977 /* sample coordinates - note, these are not subject to rounding error
979 * "sample_start = N" means "the first sample we need to represent is N
980 * samples after the first sample of the region"
983 framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
984 framepos_t sample_end = _region_start + (image_end * _samples_per_pixel);
986 // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
988 /* sample_start and sample_end are bounded by the region
989 * limits. sample_start, because of the was just computed, must already
990 * be greater than or equal to the _region_start value.
993 sample_end = min (region_end(), sample_end);
995 // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
999 if (_current_image) {
1001 /* check it covers the right sample range */
1003 if (_current_image->start > sample_start || _current_image->end < sample_end) {
1004 /* doesn't cover the area we need ... reset */
1005 _current_image.reset ();
1007 /* timestamp our continuing use of this image/cache entry */
1008 images->use (_region->audio_source (_channel), _current_image);
1012 if (!_current_image) {
1016 _current_image = get_image (sample_start, sample_end);
1018 if (!_current_image) {
1019 /* image not currently available. A redraw will be scheduled
1026 /* fix up offset: returned value is the first sample of the returned image */
1028 image_offset = (_current_image->start - _region_start) / _samples_per_pixel;
1030 // cerr << "Offset into image to place at zero: " << image_offset << endl;
1032 if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
1033 /* we are going to draw the first pixel for this region, but
1034 we may not want this to overlap a border around the
1035 waveform. If so, _start_shift will be set.
1037 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
1038 //draw_start += _start_shift;
1039 //image_offset += _start_shift;
1042 context->rectangle (draw_start, draw.y0, draw_end - draw_start, draw.height());
1044 /* round image origin position to an exact pixel in device space to
1048 double x = self.x0 + image_offset;
1050 context->user_to_device (x, y);
1053 context->device_to_user (x, y);
1055 context->set_source (_current_image->image, x, y);
1061 WaveView::compute_bounding_box () const
1064 _bounding_box = Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height);
1066 _bounding_box = boost::optional<Rect> ();
1069 _bounding_box_dirty = false;
1073 WaveView::set_height (Distance height)
1075 if (height != _height) {
1078 invalidate_image_cache ();
1080 get_image_in_thread = true;
1082 _bounding_box_dirty = true;
1088 WaveView::set_channel (int channel)
1090 if (channel != _channel) {
1093 invalidate_image_cache ();
1096 _bounding_box_dirty = true;
1102 WaveView::set_logscaled (bool yn)
1104 if (_logscaled != yn) {
1105 begin_visual_change ();
1106 invalidate_image_cache ();
1108 end_visual_change ();
1113 WaveView::gain_changed ()
1115 begin_visual_change ();
1116 invalidate_image_cache ();
1117 _region_amplitude = _region->scale_amplitude ();
1118 end_visual_change ();
1122 WaveView::set_zero_color (Color c)
1124 if (_zero_color != c) {
1125 begin_visual_change ();
1126 invalidate_image_cache ();
1128 end_visual_change ();
1133 WaveView::set_clip_color (Color c)
1135 if (_clip_color != c) {
1136 begin_visual_change ();
1137 invalidate_image_cache ();
1139 end_visual_change ();
1144 WaveView::set_show_zero_line (bool yn)
1146 if (_show_zero != yn) {
1147 begin_visual_change ();
1148 invalidate_image_cache ();
1150 end_visual_change ();
1155 WaveView::set_shape (Shape s)
1158 begin_visual_change ();
1159 invalidate_image_cache ();
1161 end_visual_change ();
1166 WaveView::set_amplitude_above_axis (double a)
1168 if (fabs (_amplitude_above_axis - a) > 0.01) {
1169 begin_visual_change ();
1170 invalidate_image_cache ();
1171 _amplitude_above_axis = a;
1172 end_visual_change ();
1177 WaveView::set_global_shape (Shape s)
1179 if (_global_shape != s) {
1181 VisualPropertiesChanged (); /* EMIT SIGNAL */
1186 WaveView::set_global_logscaled (bool yn)
1188 if (_global_logscaled != yn) {
1189 _global_logscaled = yn;
1190 VisualPropertiesChanged (); /* EMIT SIGNAL */
1195 WaveView::region_length() const
1197 return _region->length() - (_region_start - _region->start());
1201 WaveView::region_end() const
1203 return _region_start + region_length();
1207 WaveView::set_region_start (frameoffset_t start)
1213 if (_region_start == start) {
1218 _region_start = start;
1219 _bounding_box_dirty = true;
1224 WaveView::region_resized ()
1226 /* Called when the region start or end (thus length) has changed.
1234 _region_start = _region->start();
1235 _bounding_box_dirty = true;
1240 WaveView::set_global_gradient_depth (double depth)
1242 if (_global_gradient_depth != depth) {
1243 _global_gradient_depth = depth;
1244 VisualPropertiesChanged (); /* EMIT SIGNAL */
1249 WaveView::set_global_show_waveform_clipping (bool yn)
1251 if (_global_show_waveform_clipping != yn) {
1252 _global_show_waveform_clipping = yn;
1253 ClipLevelChanged ();
1258 WaveView::set_start_shift (double pixels)
1264 begin_visual_change ();
1265 _start_shift = pixels;
1266 end_visual_change ();
1271 WaveView::cancel_my_render_request () const
1277 /* try to stop any current rendering of the request, or prevent it from
1281 if (current_request) {
1282 current_request->cancel ();
1285 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1287 /* now remove it from the queue and reset our request pointer so that
1288 have no outstanding request (that we know about)
1291 request_queue.erase (this);
1292 current_request.reset ();
1296 WaveView::send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1298 if (req->type == WaveViewThreadRequest::Draw && current_request) {
1299 /* this will stop rendering in progress (which might otherwise
1300 be long lived) for any current request.
1302 current_request->cancel ();
1305 start_drawing_thread ();
1307 Glib::signal_idle().connect (sigc::bind (sigc::mem_fun (this, &WaveView::idle_send_request), req));
1311 WaveView::idle_send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1314 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1315 /* swap requests (protected by lock) */
1316 current_request = req;
1317 request_queue.insert (this);
1320 request_cond.signal (); /* wake thread */
1322 return false; /* do not call from idle again */
1325 /*-------------------------------------------------*/
1328 WaveView::start_drawing_thread ()
1330 if (!_drawing_thread) {
1331 _drawing_thread = Glib::Threads::Thread::create (sigc::ptr_fun (WaveView::drawing_thread));
1336 WaveView::stop_drawing_thread ()
1338 if (_drawing_thread) {
1339 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1340 g_atomic_int_set (&drawing_thread_should_quit, 1);
1341 request_cond.signal ();
1346 WaveView::drawing_thread ()
1348 using namespace Glib::Threads;
1350 WaveView const * requestor;
1351 Mutex::Lock lm (request_queue_lock);
1356 /* remember that we hold the lock at this point, no matter what */
1358 if (g_atomic_int_get (&drawing_thread_should_quit)) {
1362 if (request_queue.empty()) {
1363 request_cond.wait (request_queue_lock);
1366 /* remove the request from the queue (remember: the "request"
1367 * is just a pointer to a WaveView object)
1370 requestor = *(request_queue.begin());
1371 request_queue.erase (request_queue.begin());
1373 boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
1379 /* Generate an image. Unlock the request queue lock
1380 * while we do this, so that other things can happen
1381 * as we do rendering.
1384 request_queue_lock.unlock (); /* some RAII would be good here */
1387 requestor->generate_image (req, true);
1389 req->image.clear(); /* just in case it was set before the exception, whatever it was */
1392 request_queue_lock.lock ();
1394 req.reset (); /* drop/delete request as appropriate */
1397 /* thread is vanishing */
1398 _drawing_thread = 0;
1401 /*-------------------------------------------------*/
1403 WaveViewCache::WaveViewCache ()
1404 : image_cache_size (0)
1405 , _image_cache_threshold (100 * 1048576) /* bytes */
1409 WaveViewCache::~WaveViewCache ()
1414 boost::shared_ptr<WaveViewCache::Entry>
1415 WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
1416 framepos_t start, framepos_t end,
1421 double samples_per_pixel)
1423 ImageCache::iterator x;
1425 if ((x = cache_map.find (src)) == cache_map.end ()) {
1426 /* nothing in the cache for this audio source at all */
1427 return boost::shared_ptr<WaveViewCache::Entry> ();
1430 CacheLine& caches = x->second;
1432 /* Find a suitable ImageSurface, if it exists.
1435 for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
1437 boost::shared_ptr<Entry> e (*c);
1439 if (channel != e->channel
1440 || height != e->height
1441 || amplitude != e->amplitude
1442 || samples_per_pixel != e->samples_per_pixel
1443 || fill_color != e->fill_color) {
1447 if (end <= e->end && start >= e->start) {
1448 /* found an image that covers the range we need */
1454 return boost::shared_ptr<Entry> ();
1458 WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> src,
1463 double samples_per_pixel)
1465 list <uint32_t> deletion_list;
1466 uint32_t other_entries = 0;
1467 ImageCache::iterator x;
1469 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1471 if ((x = cache_map.find (src)) == cache_map.end ()) {
1475 CacheLine& caches = x->second;
1477 for (CacheLine::iterator c1 = caches.begin(); c1 != caches.end(); ) {
1479 CacheLine::iterator nxt = c1;
1482 boost::shared_ptr<Entry> e1 (*c1);
1484 if (channel != e1->channel
1485 || height != e1->height
1486 || amplitude != e1->amplitude
1487 || samples_per_pixel != e1->samples_per_pixel
1488 || fill_color != e1->fill_color) {
1490 /* doesn't match current properties, ignore and move on
1499 /* c1 now points to a cached image entry that matches current
1500 * properties. Check all subsequent cached imaged entries to
1501 * see if there are others that also match but represent
1502 * subsets of the range covered by this one.
1505 for (CacheLine::iterator c2 = c1; c2 != caches.end(); ) {
1507 CacheLine::iterator nxt2 = c2;
1510 boost::shared_ptr<Entry> e2 (*c2);
1512 if (e1 == e2 || channel != e2->channel
1513 || height != e2->height
1514 || amplitude != e2->amplitude
1515 || samples_per_pixel != e2->samples_per_pixel
1516 || fill_color != e2->fill_color) {
1518 /* properties do not match, ignore for the
1519 * purposes of consolidation.
1525 if (e2->start >= e1->start && e2->end <= e1->end) {
1526 /* c2 is fully contained by c1, so delete it */
1527 c2 = caches.erase (c2);
1539 WaveViewCache::use (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1541 ce->timestamp = g_get_monotonic_time ();
1545 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1547 /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1549 Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
1551 image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1557 ce->timestamp = g_get_monotonic_time ();
1559 cache_map[src].push_back (ce);
1560 cache_list.push_back (make_pair (src, ce));
1564 WaveViewCache::compute_image_cache_size()
1567 for (ImageCache::iterator s = cache_map.begin(); s != cache_map.end(); ++s) {
1568 CacheLine& per_source_cache (s->second);
1569 for (CacheLine::iterator c = per_source_cache.begin(); c != per_source_cache.end(); ++c) {
1570 Cairo::RefPtr<Cairo::ImageSurface> img ((*c)->image);
1571 total += img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1578 WaveViewCache::cache_full()
1580 return image_cache_size > _image_cache_threshold;
1584 WaveViewCache::cache_flush ()
1586 SortByTimestamp sorter;
1588 /* sort list in LRU order */
1590 sort (cache_list.begin(), cache_list.end(), sorter);
1592 while (image_cache_size > _image_cache_threshold) {
1594 ListEntry& le (cache_list.front());
1596 ImageCache::iterator x;
1598 if ((x = cache_map.find (le.first)) == cache_map.end ()) {
1599 /* wierd ... no entry for this AudioSource */
1603 CacheLine& cl = x->second;
1605 for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
1607 if (*c == le.second) {
1609 /* Remove this entry from this cache line */
1613 /* remove cache line from main cache: no more entries */
1614 cache_map.erase (x);
1621 Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
1622 uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1624 if (image_cache_size > size) {
1625 image_cache_size -= size;
1627 image_cache_size = 0;
1630 /* Remove from the linear list */
1631 cache_list.erase (cache_list.begin());
1636 WaveViewCache::set_image_cache_threshold (uint64_t sz)
1638 _image_cache_threshold = sz;