3d70527120eea7a90b173db804e487a9826a7f3e
[ardour.git] / libs / canvas / wave_view.cc
1 /*
2     Copyright (C) 2011-2013 Paul Davis
3     Author: Carl Hetherington <cth@carlh.net>
4
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.
9
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.
14
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.
18
19 */
20
21 #include <cmath>
22 #include <cairomm/cairomm.h>
23
24 #include <glibmm/threads.h>
25
26 #include "gtkmm2ext/utils.h"
27 #include "gtkmm2ext/gui_thread.h"
28
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"
34
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"
40 #include "ardour/session.h"
41
42 #include "canvas/canvas.h"
43 #include "canvas/colors.h"
44 #include "canvas/debug.h"
45 #include "canvas/utils.h"
46 #include "canvas/wave_view.h"
47
48 #include "evoral/Range.hpp"
49
50 #include <gdkmm/general.h>
51
52 #include "gtkmm2ext/gui_thread.h"
53
54 using namespace std;
55 using namespace ARDOUR;
56 using namespace PBD;
57 using namespace ArdourCanvas;
58
59 double WaveView::_global_gradient_depth = 0.6;
60 bool WaveView::_global_logscaled = false;
61 WaveView::Shape WaveView::_global_shape = WaveView::Normal;
62 bool WaveView::_global_show_waveform_clipping = true;
63 double WaveView::_clip_level = 0.98853;
64
65 WaveViewCache* WaveView::images = 0;
66 gint WaveView::drawing_thread_should_quit = 0;
67 Glib::Threads::Mutex WaveView::request_queue_lock;
68 Glib::Threads::Mutex WaveView::current_image_lock;
69 Glib::Threads::Cond WaveView::request_cond;
70 Glib::Threads::Thread* WaveView::_drawing_thread = 0;
71 WaveView::DrawingRequestQueue WaveView::request_queue;
72
73 PBD::Signal0<void> WaveView::VisualPropertiesChanged;
74 PBD::Signal0<void> WaveView::ClipLevelChanged;
75
76 #undef ENABLE_THREADED_WAVEFORM_RENDERING
77
78 WaveView::WaveView (Canvas* c, boost::shared_ptr<ARDOUR::AudioRegion> region)
79         : Item (c)
80         , _region (region)
81         , _channel (0)
82         , _samples_per_pixel (0)
83         , _height (64)
84         , _show_zero (false)
85         , _zero_color (0xff0000ff)
86         , _clip_color (0xff0000ff)
87         , _logscaled (_global_logscaled)
88         , _shape (_global_shape)
89         , _gradient_depth (_global_gradient_depth)
90         , _shape_independent (false)
91         , _logscaled_independent (false)
92         , _gradient_depth_independent (false)
93         , _amplitude_above_axis (1.0)
94         , _region_amplitude (region->scale_amplitude ())
95         , _start_shift (0.0)
96         , _region_start (region->start())
97         , get_image_in_thread (false)
98         , always_get_image_in_thread (false)
99         , rendered (false)
100 {
101         if (!images) {
102                 images = new WaveViewCache;
103         }
104
105         VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
106         ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
107
108         ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
109 }
110
111 WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
112         : Item (parent)
113         , _region (region)
114         , _channel (0)
115         , _samples_per_pixel (0)
116         , _height (64)
117         , _show_zero (false)
118         , _zero_color (0xff0000ff)
119         , _clip_color (0xff0000ff)
120         , _logscaled (_global_logscaled)
121         , _shape (_global_shape)
122         , _gradient_depth (_global_gradient_depth)
123         , _shape_independent (false)
124         , _logscaled_independent (false)
125         , _gradient_depth_independent (false)
126         , _amplitude_above_axis (1.0)
127         , _region_amplitude (region->scale_amplitude ())
128         , _start_shift (0.0)
129         , _region_start (region->start())
130         , get_image_in_thread (false)
131         , always_get_image_in_thread (false)
132         , rendered (false)
133 {
134         if (!images) {
135                 images = new WaveViewCache;
136         }
137
138         VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
139         ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
140
141         ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
142 }
143
144 WaveView::~WaveView ()
145 {
146         invalidate_image_cache ();
147         if (images ) {
148                 images->clear_cache ();
149         }
150 }
151
152 string
153 WaveView::debug_name() const
154 {
155         return _region->name() + string (":") + PBD::to_string (_channel+1, std::dec);
156 }
157
158 void
159 WaveView::image_ready ()
160 {
161         DEBUG_TRACE (DEBUG::WaveView, string_compose ("queue draw for %1 at %2 (vis = %3 CR %4)\n", this, g_get_monotonic_time(), visible(), current_request));
162         redraw ();
163 }
164
165 void
166 WaveView::set_always_get_image_in_thread (bool yn)
167 {
168         always_get_image_in_thread = yn;
169 }
170
171 void
172 WaveView::handle_visual_property_change ()
173 {
174         bool changed = false;
175
176         if (!_shape_independent && (_shape != global_shape())) {
177                 _shape = global_shape();
178                 changed = true;
179         }
180
181         if (!_logscaled_independent && (_logscaled != global_logscaled())) {
182                 _logscaled = global_logscaled();
183                 changed = true;
184         }
185
186         if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
187                 _gradient_depth = global_gradient_depth();
188                 changed = true;
189         }
190
191         if (changed) {
192                 begin_visual_change ();
193                 invalidate_image_cache ();
194                 end_visual_change ();
195         }
196 }
197
198 void
199 WaveView::handle_clip_level_change ()
200 {
201         begin_visual_change ();
202         invalidate_image_cache ();
203         end_visual_change ();
204 }
205
206 void
207 WaveView::set_fill_color (Color c)
208 {
209         if (c != _fill_color) {
210                 begin_visual_change ();
211                 invalidate_image_cache ();
212                 Fill::set_fill_color (c);
213                 end_visual_change ();
214         }
215 }
216
217 void
218 WaveView::set_outline_color (Color c)
219 {
220         if (c != _outline_color) {
221                 begin_visual_change ();
222                 invalidate_image_cache ();
223                 Outline::set_outline_color (c);
224                 end_visual_change ();
225         }
226 }
227
228 void
229 WaveView::set_samples_per_pixel (double samples_per_pixel)
230 {
231         if (samples_per_pixel != _samples_per_pixel) {
232                 begin_change ();
233
234                 invalidate_image_cache ();
235                 _samples_per_pixel = samples_per_pixel;
236                 _bounding_box_dirty = true;
237
238                 end_change ();
239         }
240 }
241
242 static inline float
243 _log_meter (float power, double lower_db, double upper_db, double non_linearity)
244 {
245         return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
246 }
247
248 static inline float
249 alt_log_meter (float power)
250 {
251         return _log_meter (power, -192.0, 0.0, 8.0);
252 }
253
254 void
255 WaveView::set_clip_level (double dB)
256 {
257         const double clip_level = dB_to_coefficient (dB);
258         if (clip_level != _clip_level) {
259                 _clip_level = clip_level;
260                 ClipLevelChanged ();
261         }
262 }
263
264 void
265 WaveView::invalidate_image_cache ()
266 {
267         DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 invalidates image cache and cancels current request\n", this));
268         cancel_my_render_request ();
269         Glib::Threads::Mutex::Lock lci (current_image_lock);
270         _current_image.reset ();
271 }
272
273 void
274 WaveView::compute_tips (PeakData const & peak, WaveView::LineTips& tips) const
275 {
276         const double effective_height  = _height;
277
278         /* remember: canvas (and cairo) coordinate space puts the origin at the upper left.
279
280            So, a sample value of 1.0 (0dbFS) will be computed as:
281
282                  (1.0 - 1.0) * 0.5 * effective_height
283
284            which evaluates to 0, or the top of the image.
285
286            A sample value of -1.0 will be computed as
287
288                 (1.0 + 1.0) * 0.5 * effective height
289
290            which evaluates to effective height, or the bottom of the image.
291         */
292
293         const double pmax = (1.0 - peak.max) * 0.5 * effective_height;
294         const double pmin = (1.0 - peak.min) * 0.5 * effective_height;
295
296         /* remember that the bottom of the image (pmin) has larger y-coordinates
297            than the top (pmax).
298         */
299
300         double spread = (pmin - pmax) * 0.5;
301
302         /* find the nearest pixel to the nominal center. */
303         const double center = round (pmin - spread);
304
305         if (spread < 1.0) {
306                 /* minimum distance between line ends is 1 pixel, and we want it "centered" on a pixel,
307                    as per cairo single-pixel line issues.
308
309                    NOTE: the caller will not draw a line between these two points if the spread is
310                    less than 2 pixels. So only the tips.top value matters, which is where we will
311                    draw a single pixel as part of the outline.
312                  */
313                 tips.top = center;
314                 tips.bot = center + 1.0;
315         } else {
316                 /* round spread above and below center to an integer number of pixels */
317                 spread = round (spread);
318                 /* top and bottom are located equally either side of the center */
319                 tips.top = center - spread;
320                 tips.bot = center + spread;
321         }
322
323         tips.top = min (effective_height, max (0.0, tips.top));
324         tips.bot = min (effective_height, max (0.0, tips.bot));
325 }
326
327
328 Coord
329 WaveView::y_extent (double s) const
330 {
331         assert (_shape == Rectified);
332         return floor ((1.0 - s) * _height);
333 }
334
335 void
336 WaveView::draw_absent_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
337 {
338         Cairo::RefPtr<Cairo::ImageSurface> stripe = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
339
340         Cairo::RefPtr<Cairo::Context> stripe_context = Cairo::Context::create (stripe);
341         stripe_context->set_antialias (Cairo::ANTIALIAS_NONE);
342
343         uint32_t stripe_separation = 150;
344         double start = - floor (_height / stripe_separation) * stripe_separation;
345         int stripe_x = 0;
346
347         while (start < n_peaks) {
348
349                 stripe_context->move_to (start, 0);
350                 stripe_x = start + _height;
351                 stripe_context->line_to (stripe_x, _height);
352                 start += stripe_separation;
353         }
354
355         stripe_context->set_source_rgba (1.0, 1.0, 1.0, 1.0);
356         stripe_context->set_line_cap (Cairo::LINE_CAP_SQUARE);
357         stripe_context->set_line_width(50);
358         stripe_context->stroke();
359
360         Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
361
362         context->set_source_rgba (1.0, 1.0, 0.0, 0.3);
363         context->mask (stripe, 0, 0);
364         context->fill ();
365 }
366
367 struct ImageSet {
368         Cairo::RefPtr<Cairo::ImageSurface> wave;
369         Cairo::RefPtr<Cairo::ImageSurface> outline;
370         Cairo::RefPtr<Cairo::ImageSurface> clip;
371         Cairo::RefPtr<Cairo::ImageSurface> zero;
372
373         ImageSet() :
374                 wave (0), outline (0), clip (0), zero (0) {}
375 };
376
377 void
378 WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks, boost::shared_ptr<WaveViewThreadRequest> req) const
379 {
380
381         ImageSet images;
382
383         images.wave = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
384         images.outline = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
385         images.clip = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
386         images.zero = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
387
388         Cairo::RefPtr<Cairo::Context> wave_context = Cairo::Context::create (images.wave);
389         Cairo::RefPtr<Cairo::Context> outline_context = Cairo::Context::create (images.outline);
390         Cairo::RefPtr<Cairo::Context> clip_context = Cairo::Context::create (images.clip);
391         Cairo::RefPtr<Cairo::Context> zero_context = Cairo::Context::create (images.zero);
392         wave_context->set_antialias (Cairo::ANTIALIAS_NONE);
393         outline_context->set_antialias (Cairo::ANTIALIAS_NONE);
394         clip_context->set_antialias (Cairo::ANTIALIAS_NONE);
395         zero_context->set_antialias (Cairo::ANTIALIAS_NONE);
396
397         boost::scoped_array<LineTips> tips (new LineTips[n_peaks]);
398
399         /* Clip level nominally set to -0.9dBFS to account for inter-sample
400            interpolation possibly clipping (value may be too low).
401
402            We adjust by the region's own gain (but note: not by any gain
403            automation or its gain envelope) so that clip indicators are closer
404            to providing data about on-disk data. This multiplication is
405            needed because the data we get from AudioRegion::read_peaks()
406            has been scaled by scale_amplitude() already.
407         */
408
409         const double clip_level = _clip_level * _region_amplitude;
410
411         if (_shape == WaveView::Rectified) {
412
413                 /* each peak is a line from the bottom of the waveview
414                  * to a point determined by max (_peaks[i].max,
415                  * _peaks[i].min)
416                  */
417
418                 if (_logscaled) {
419                         for (int i = 0; i < n_peaks; ++i) {
420
421                                 tips[i].bot = height() - 1.0;
422                                 const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
423                                 tips[i].top = y_extent (p);
424                                 tips[i].spread = p * _height;
425
426                                 if (_peaks[i].max >= clip_level) {
427                                         tips[i].clip_max = true;
428                                 }
429
430                                 if (-(_peaks[i].min) >= clip_level) {
431                                         tips[i].clip_min = true;
432                                 }
433                         }
434
435                 } else {
436                         for (int i = 0; i < n_peaks; ++i) {
437
438                                 tips[i].bot = height() - 1.0;
439                                 const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
440                                 tips[i].top = y_extent (p);
441                                 tips[i].spread = p * _height;
442                                 if (p >= clip_level) {
443                                         tips[i].clip_max = true;
444                                 }
445                         }
446
447                 }
448
449         } else {
450
451                 if (_logscaled) {
452                         for (int i = 0; i < n_peaks; ++i) {
453                                 PeakData p;
454                                 p.max = _peaks[i].max;
455                                 p.min = _peaks[i].min;
456
457                                 if (_peaks[i].max >= clip_level) {
458                                         tips[i].clip_max = true;
459                                 }
460                                 if (-(_peaks[i].min) >= clip_level) {
461                                         tips[i].clip_min = true;
462                                 }
463
464                                 if (p.max > 0.0) {
465                                         p.max = alt_log_meter (fast_coefficient_to_dB (p.max));
466                                 } else if (p.max < 0.0) {
467                                         p.max =-alt_log_meter (fast_coefficient_to_dB (-p.max));
468                                 } else {
469                                         p.max = 0.0;
470                                 }
471
472                                 if (p.min > 0.0) {
473                                         p.min = alt_log_meter (fast_coefficient_to_dB (p.min));
474                                 } else if (p.min < 0.0) {
475                                         p.min = -alt_log_meter (fast_coefficient_to_dB (-p.min));
476                                 } else {
477                                         p.min = 0.0;
478                                 }
479
480                                 compute_tips (p, tips[i]);
481                                 tips[i].spread = tips[i].bot - tips[i].top;
482                         }
483
484                 } else {
485                         for (int i = 0; i < n_peaks; ++i) {
486                                 if (_peaks[i].max >= clip_level) {
487                                         tips[i].clip_max = true;
488                                 }
489                                 if (-(_peaks[i].min) >= clip_level) {
490                                         tips[i].clip_min = true;
491                                 }
492
493                                 compute_tips (_peaks[i], tips[i]);
494                                 tips[i].spread = tips[i].bot - tips[i].top;
495                         }
496
497                 }
498         }
499
500         if (req->should_stop()) {
501                 return;
502         }
503
504         Color alpha_one = rgba_to_color (0, 0, 0, 1.0);
505
506         set_source_rgba (wave_context, alpha_one);
507         set_source_rgba (outline_context, alpha_one);
508         set_source_rgba (clip_context, alpha_one);
509         set_source_rgba (zero_context, alpha_one);
510
511         /* ensure single-pixel lines */
512
513         wave_context->set_line_width (1.0);
514         wave_context->translate (0.5, 0.5);
515
516         outline_context->set_line_width (1.0);
517         outline_context->translate (0.5, 0.5);
518
519         clip_context->set_line_width (1.0);
520         clip_context->translate (0.5, 0.5);
521
522         zero_context->set_line_width (1.0);
523         zero_context->translate (0.5, 0.5);
524
525         /* the height of the clip-indicator should be at most 7 pixels,
526          * or 5% of the height of the waveview item.
527          */
528
529         const double clip_height = min (7.0, ceil (_height * 0.05));
530
531         /* There are 3 possible components to draw at each x-axis position: the
532            waveform "line", the zero line and an outline/clip indicator.  We
533            have to decide which of the 3 to draw at each position, pixel by
534            pixel. This makes the rendering less efficient but it is the only
535            way I can see to do this correctly.
536
537            To avoid constant source swapping and stroking, we draw the components separately
538            onto four alpha only image surfaces for use as a mask.
539
540            With only 1 pixel of spread between the top and bottom of the line,
541            we just draw the upper outline/clip indicator.
542
543            With 2 pixels of spread, we draw the upper and lower outline clip
544            indicators.
545
546            With 3 pixels of spread we draw the upper and lower outline/clip
547            indicators and at least 1 pixel of the waveform line.
548
549            With 5 pixels of spread, we draw all components.
550
551            We can do rectified as two separate passes because we have a much
552            easier decision regarding whether to draw the waveform line. We
553            always draw the clip/outline indicators.
554         */
555
556         if (_shape == WaveView::Rectified) {
557
558                 for (int i = 0; i < n_peaks; ++i) {
559
560                         /* waveform line */
561
562                         if (tips[i].spread >= 1.0) {
563                                 wave_context->move_to (i, tips[i].top);
564                                 wave_context->line_to (i, tips[i].bot);
565                         }
566
567                         /* clip indicator */
568
569                         if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
570                                 clip_context->move_to (i, tips[i].top);
571                                 /* clip-indicating upper terminal line */
572                                 clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + .5)));
573                         } else {
574                                 outline_context->move_to (i, tips[i].top);
575                                 /* normal upper terminal dot */
576                                 outline_context->rel_line_to (0, -1.0);
577                         }
578                 }
579
580                 wave_context->stroke ();
581                 clip_context->stroke ();
582                 outline_context->stroke ();
583
584         } else {
585                 const int height_zero = floor( _height * .5);
586
587                 for (int i = 0; i < n_peaks; ++i) {
588
589                         /* waveform line */
590
591                         if (tips[i].spread >= 2.0) {
592                                 wave_context->move_to (i, tips[i].top);
593                                 wave_context->line_to (i, tips[i].bot);
594                         }
595
596                         /* draw square waves and other discontiguous points clearly */
597                         if (i > 0) {
598                                 if (tips[i-1].top + 2 < tips[i].top) {
599                                         wave_context->move_to (i-1, tips[i-1].top);
600                                         wave_context->line_to (i-1, (tips[i].bot + tips[i-1].top)/2);
601                                         wave_context->move_to (i, (tips[i].bot + tips[i-1].top)/2);
602                                         wave_context->line_to (i, tips[i].top);
603                                 } else if (tips[i-1].bot > tips[i].bot + 2) {
604                                         wave_context->move_to (i-1, tips[i-1].bot);
605                                         wave_context->line_to (i-1, (tips[i].top + tips[i-1].bot)/2);
606                                         wave_context->move_to (i, (tips[i].top + tips[i-1].bot)/2);
607                                         wave_context->line_to (i, tips[i].bot);
608                                 }
609                         }
610
611                         /* zero line, show only if there is enough spread
612                         or the waveform line does not cross zero line */
613
614                         if (show_zero_line() && ((tips[i].spread >= 5.0) || (tips[i].top > height_zero ) || (tips[i].bot < height_zero)) ) {
615                                 zero_context->move_to (i, height_zero);
616                                 zero_context->rel_line_to (1.0, 0);
617                         }
618
619                         if (tips[i].spread > 1.0) {
620                                 bool clipped = false;
621                                 /* outline/clip indicators */
622                                 if (_global_show_waveform_clipping && tips[i].clip_max) {
623                                         clip_context->move_to (i, tips[i].top);
624                                         /* clip-indicating upper terminal line */
625                                         clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + 0.5)));
626                                         clipped = true;
627                                 }
628
629                                 if (_global_show_waveform_clipping && tips[i].clip_min) {
630                                         clip_context->move_to (i, tips[i].bot);
631                                         /* clip-indicating lower terminal line */
632                                         clip_context->rel_line_to (0, - min (clip_height, ceil(tips[i].spread + 0.5)));
633                                         clipped = true;
634                                 }
635
636                                 if (!clipped && tips[i].spread > 2.0) {
637                                         /* only draw the outline if the spread
638                                            implies 3 or more pixels (so that we see 1
639                                            white pixel in the middle).
640                                         */
641                                         outline_context->move_to (i, tips[i].bot);
642                                         /* normal lower terminal dot; line moves up */
643                                         outline_context->rel_line_to (0, -1.0);
644
645                                         outline_context->move_to (i, tips[i].top);
646                                         /* normal upper terminal dot, line moves down */
647                                         outline_context->rel_line_to (0, 1.0);
648                                 }
649                         } else {
650                                 bool clipped = false;
651                                 /* outline/clip indicator */
652                                 if (_global_show_waveform_clipping && (tips[i].clip_max || tips[i].clip_min)) {
653                                         clip_context->move_to (i, tips[i].top);
654                                         /* clip-indicating upper / lower terminal line */
655                                         clip_context->rel_line_to (0, 1.0);
656                                         clipped = true;
657                                 }
658
659                                 if (!clipped) {
660                                         /* special case where only 1 pixel of
661                                          * the waveform line is drawn (and
662                                          * nothing else).
663                                          *
664                                          * we draw a 1px "line", pretending
665                                          * that the span is 1.0 (whether it is
666                                          * zero or 1.0)
667                                          */
668                                         wave_context->move_to (i, tips[i].top);
669                                         wave_context->rel_line_to (0, 1.0);
670                                 }
671                         }
672                 }
673
674                 wave_context->stroke ();
675                 outline_context->stroke ();
676                 clip_context->stroke ();
677                 zero_context->stroke ();
678         }
679
680         if (req->should_stop()) {
681                 return;
682         }
683
684         Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
685
686         /* Here we set a source colour and use the various components as a mask. */
687
688         if (gradient_depth() != 0.0) {
689
690                 Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _height));
691
692                 double stops[3];
693
694                 double r, g, b, a;
695
696                 if (_shape == Rectified) {
697                         stops[0] = 0.1;
698                         stops[1] = 0.3;
699                         stops[2] = 0.9;
700                 } else {
701                         stops[0] = 0.1;
702                         stops[1] = 0.5;
703                         stops[2] = 0.9;
704                 }
705
706                 color_to_rgba (_fill_color, r, g, b, a);
707                 gradient->add_color_stop_rgba (stops[1], r, g, b, a);
708                 /* generate a new color for the middle of the gradient */
709                 double h, s, v;
710                 color_to_hsv (_fill_color, h, s, v);
711                 /* change v towards white */
712                 v *= 1.0 - gradient_depth();
713                 Color center = hsva_to_color (h, s, v, a);
714                 color_to_rgba (center, r, g, b, a);
715
716                 gradient->add_color_stop_rgba (stops[0], r, g, b, a);
717                 gradient->add_color_stop_rgba (stops[2], r, g, b, a);
718
719                 context->set_source (gradient);
720         } else {
721                 set_source_rgba (context, _fill_color);
722         }
723
724         if (req->should_stop()) {
725                 return;
726         }
727
728         context->mask (images.wave, 0, 0);
729         context->fill ();
730
731         set_source_rgba (context, _outline_color);
732         context->mask (images.outline, 0, 0);
733         context->fill ();
734
735         set_source_rgba (context, _clip_color);
736         context->mask (images.clip, 0, 0);
737         context->fill ();
738
739         set_source_rgba (context, _zero_color);
740         context->mask (images.zero, 0, 0);
741         context->fill ();
742 }
743
744 boost::shared_ptr<WaveViewCache::Entry>
745 WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) const
746 {
747         if (!req->image) {
748                 cerr << "asked to cache null image!!!\n";
749                 return boost::shared_ptr<WaveViewCache::Entry> ();
750         }
751
752         boost::shared_ptr<WaveViewCache::Entry> ret (new WaveViewCache::Entry (req->channel,
753                                                                                req->height,
754                                                                                req->amplitude,
755                                                                                req->fill_color,
756                                                                                req->samples_per_pixel,
757                                                                                req->start,
758                                                                                req->end,
759                                                                                req->image));
760         images->add (_region->audio_source (_channel), ret);
761
762         /* consolidate cache first (removes fully-contained
763          * duplicate images)
764          */
765
766         images->consolidate_image_cache (_region->audio_source (_channel),
767                                          req->channel, req->height, req->amplitude,
768                                          req->fill_color, req->samples_per_pixel);
769
770         return ret;
771 }
772
773 boost::shared_ptr<WaveViewCache::Entry>
774 WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
775 {
776         boost::shared_ptr<WaveViewCache::Entry> ret;
777
778         full_image = true;
779
780         /* this is called from a ::render() call, when we need an image to
781            draw with.
782         */
783
784         DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 needs image from %2 .. %3\n", name, start, end));
785
786
787         {
788                 Glib::Threads::Mutex::Lock lmq (request_queue_lock);
789
790                 /* if there's a draw request outstanding, check to see if we
791                  * have an image there. if so, use it (and put it in the cache
792                  * while we're here.
793                  */
794
795                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 CR %2 stop? %3 image %4\n", this, current_request,
796                                                               (current_request ? current_request->should_stop() : false),
797                                                               (current_request ? current_request->image : 0)));
798
799                 if (current_request && !current_request->should_stop() && current_request->image) {
800
801                         /* put the image into the cache so that other
802                          * WaveViews can use it if it is useful
803                          */
804
805                         if (current_request->start <= start && current_request->end >= end) {
806
807                                 ret.reset (new WaveViewCache::Entry (current_request->channel,
808                                                                      current_request->height,
809                                                                      current_request->amplitude,
810                                                                      current_request->fill_color,
811                                                                      current_request->samples_per_pixel,
812                                                                      current_request->start,
813                                                                      current_request->end,
814                                                                      current_request->image));
815
816                                 cache_request_result (current_request);
817                                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: got image from completed request, spans %2..%3\n",
818                                                                               name, current_request->start, current_request->end));
819                         }
820
821                         /* drop our handle on the current request */
822                         current_request.reset ();
823                 }
824         }
825
826         if (!ret) {
827
828                 /* no current image draw request, so look in the cache */
829
830                 ret = get_image_from_cache (start, end, full_image);
831                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: lookup from cache gave %2 (full %3)\n",
832                                                               name, ret, full_image));
833
834         }
835
836
837
838         if (!ret || !full_image) {
839
840 #ifndef ENABLE_THREADED_WAVEFORM_RENDERING
841                 if (1)
842 #else
843                 if ((rendered && get_image_in_thread) || always_get_image_in_thread)
844 #endif
845                 {
846
847                         DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: generating image in caller thread\n", name));
848
849                         boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
850
851                         req->type = WaveViewThreadRequest::Draw;
852                         req->start = start;
853                         req->end = end;
854                         req->samples_per_pixel = _samples_per_pixel;
855                         req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
856                         req->channel = _channel;
857                         req->height = _height;
858                         req->fill_color = _fill_color;
859                         req->amplitude = _region_amplitude * _amplitude_above_axis;
860                         req->width = desired_image_width ();
861
862                         /* draw image in this (the GUI thread) */
863
864                         generate_image (req, false);
865
866                         /* cache the result */
867
868                         ret = cache_request_result (req);
869
870                         /* reset this so that future missing images are
871                          * generated in a a worker thread.
872                          */
873
874                         get_image_in_thread = false;
875
876                 } else {
877                         queue_get_image (_region, start, end);
878                 }
879         }
880
881         if (ret) {
882                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 got an image from %2 .. %3 (full ? %4)\n", name, ret->start, ret->end, full_image));
883         } else {
884                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 no useful image available\n", name));
885         }
886
887         return ret;
888 }
889
890 boost::shared_ptr<WaveViewCache::Entry>
891 WaveView::get_image_from_cache (framepos_t start, framepos_t end, bool& full) const
892 {
893         if (!images) {
894                 return boost::shared_ptr<WaveViewCache::Entry>();
895         }
896
897         return images->lookup_image (_region->audio_source (_channel), start, end, _channel,
898                                      _height, _region_amplitude * _amplitude_above_axis, _fill_color, _samples_per_pixel, full);
899 }
900
901 framecnt_t
902 WaveView::desired_image_width () const
903 {
904         /* compute how wide the image should be, in samples.
905          *
906          * We want at least 1 canvas width's worth, but if that
907          * represents less than 1/10th of a second, use 1/10th of
908          * a second instead.
909          */
910
911         framecnt_t canvas_width_samples = _canvas->visible_area().width() * _samples_per_pixel;
912         const framecnt_t one_tenth_of_second = _region->session().frame_rate() / 10;
913
914         if (canvas_width_samples > one_tenth_of_second) {
915                 return  canvas_width_samples;
916         }
917
918         return one_tenth_of_second;
919 }
920
921 void
922 WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, framepos_t start, framepos_t end) const
923 {
924         boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
925
926         req->type = WaveViewThreadRequest::Draw;
927         req->start = start;
928         req->end = end;
929         req->samples_per_pixel = _samples_per_pixel;
930         req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
931         req->channel = _channel;
932         req->height = _height;
933         req->fill_color = _fill_color;
934         req->amplitude = _region_amplitude * _amplitude_above_axis;
935         req->width = desired_image_width ();
936
937         if (current_request) {
938                 /* this will stop rendering in progress (which might otherwise
939                    be long lived) for any current request.
940                 */
941                 current_request->cancel ();
942         }
943
944         start_drawing_thread ();
945
946         /* swap requests (protected by lock) */
947
948         {
949                 Glib::Threads::Mutex::Lock lm (request_queue_lock);
950                 current_request = req;
951
952                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 now has current request %2\n", this, req));
953
954                 if (request_queue.insert (this).second) {
955                         /* this waveview was not already in the request queue, make sure we wake
956                            the rendering thread in case it is asleep.
957                         */
958                         request_cond.signal ();
959                 }
960         }
961 }
962
963 void
964 WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_render_thread) const
965 {
966         if (!req->should_stop()) {
967
968                 /* sample position is canonical here, and we want to generate
969                  * an image that spans about 3x the canvas width. We get to that
970                  * width by using an image sample count of the screen width added
971                  * on each side of the desired image center.
972                  */
973
974                 const framepos_t center = req->start + ((req->end - req->start) / 2);
975                 const framecnt_t image_samples = req->width;
976
977                 /* we can request data from anywhere in the Source, between 0 and its length
978                  */
979
980                 framepos_t sample_start = max (_region_start, (center - image_samples));
981                 framepos_t sample_end = min (center + image_samples, region_end());
982                 const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
983
984                 boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
985
986                 /* Note that Region::read_peaks() takes a start position based on an
987                    offset into the Region's **SOURCE**, rather than an offset into
988                    the Region itself.
989                 */
990
991                 framecnt_t peaks_read = _region->read_peaks (peaks.get(), n_peaks,
992                                                              sample_start, sample_end - sample_start,
993                                                              req->channel,
994                                                              req->samples_per_pixel);
995
996                 req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
997                 /* make sure we record the sample positions that were actually used */
998                 req->start = sample_start;
999                 req->end = sample_end;
1000
1001                 if (peaks_read > 0) {
1002
1003                         /* region amplitude will have been used to generate the
1004                          * peak values already, but not the visual-only
1005                          * amplitude_above_axis. So apply that here before
1006                          * rendering.
1007                          */
1008
1009                         if (_amplitude_above_axis != 1.0) {
1010                                 for (framecnt_t i = 0; i < n_peaks; ++i) {
1011                                         peaks[i].max *= _amplitude_above_axis;
1012                                         peaks[i].min *= _amplitude_above_axis;
1013                                 }
1014                         }
1015
1016                         draw_image (req->image, peaks.get(), n_peaks, req);
1017                 } else {
1018                         draw_absent_image (req->image, peaks.get(), n_peaks);
1019                 }
1020         } else {
1021                 cerr << "Request stopped before image generation\n";
1022         }
1023
1024         if (in_render_thread && !req->should_stop()) {
1025                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("done with request for %1 at %2 CR %3 req %4 range %5 .. %6\n", this, g_get_monotonic_time(), current_request, req, req->start, req->end));
1026                 const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
1027         }
1028
1029         return;
1030 }
1031
1032 /** Given a waveform that starts at window x-coordinate @param wave_origin
1033  * and the first pixel that we will actually draw @param draw_start, return
1034  * the offset into an image of the entire waveform that we will need to use.
1035  *
1036  * Note: most of our cached images are NOT of the entire waveform, this is just
1037  * computationally useful when determining which the sample range span for
1038  * the image we need.
1039  */
1040 static inline double
1041 window_to_image (double wave_origin, double image_start)
1042 {
1043         return image_start - wave_origin;
1044 }
1045
1046 void
1047 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
1048 {
1049         assert (_samples_per_pixel != 0);
1050
1051         if (!_region) {
1052                 return;
1053         }
1054
1055         DEBUG_TRACE (DEBUG::WaveView, string_compose ("render %1 at %2\n", this, g_get_monotonic_time()));
1056
1057         /* a WaveView is intimately connected to an AudioRegion. It will
1058          * display the waveform within the region, anywhere from the start of
1059          * the region to its end.
1060          *
1061          * the area we've been aked to render may overlap with area covered
1062          * by the region in any of the normal ways:
1063          *
1064          *  - it may begin and end within the area covered by the region
1065          *  - it may start before and end after the area covered by region
1066          *  - it may start before and end within the area covered by the region
1067          *  - it may start within and end after the area covered by the region
1068          *  - it may be precisely coincident with the area covered by region.
1069          *
1070          * So let's start by determining the area covered by the region, in
1071          * window coordinates. It begins at zero (in item coordinates for this
1072          * waveview, and extends to region_length() / _samples_per_pixel.
1073          */
1074
1075         Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
1076
1077         // cerr << name << " RENDER " << area << " self = " << self << endl;
1078
1079         /* Now lets get the intersection with the area we've been asked to draw */
1080
1081         boost::optional<Rect> d = self.intersection (area);
1082
1083         if (!d) {
1084                 return;
1085         }
1086
1087         Rect draw = d.get();
1088
1089         /* "draw" is now a rectangle that defines the rectangle we need to
1090          * update/render the waveview into, in window coordinate space.
1091          */
1092
1093         /* window coordinates - pixels where x=0 is the left edge of the canvas
1094          * window. We round down in case we were asked to
1095          * draw "between" pixels at the start and/or end.
1096          */
1097
1098         double draw_start = floor (draw.x0);
1099         const double draw_end = floor (draw.x1);
1100
1101         // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
1102
1103         /* image coordnates: pixels where x=0 is the start of this waveview,
1104          * wherever it may be positioned. thus image_start=N means "an image
1105          * that begins N pixels after the start of region that this waveview is
1106          * representing.
1107          */
1108
1109         const framepos_t image_start = window_to_image (self.x0, draw_start);
1110         const framepos_t image_end = window_to_image (self.x0, draw_end);
1111
1112         // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
1113
1114         /* sample coordinates - note, these are not subject to rounding error
1115          *
1116          * "sample_start = N" means "the first sample we need to represent is N
1117          * samples after the first sample of the region"
1118          */
1119
1120         framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
1121         framepos_t sample_end   = _region_start + (image_end * _samples_per_pixel);
1122
1123         // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
1124
1125         /* sample_start and sample_end are bounded by the region
1126          * limits. sample_start, because of the was just computed, must already
1127          * be greater than or equal to the _region_start value.
1128          */
1129
1130         sample_end = min (region_end(), sample_end);
1131
1132         // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
1133
1134         double image_origin_in_self_coordinates;
1135         boost::shared_ptr<WaveViewCache::Entry> image_to_draw;
1136
1137         Glib::Threads::Mutex::Lock lci (current_image_lock);
1138         if (_current_image) {
1139
1140                 /* check it covers the right sample range */
1141
1142                 if (_current_image->start > sample_start || _current_image->end < sample_end) {
1143                         /* doesn't cover the area we need ... reset */
1144                         _current_image.reset ();
1145                 } else {
1146                         /* timestamp our continuing use of this image/cache entry */
1147                         images->use (_region->audio_source (_channel), _current_image);
1148                         image_to_draw = _current_image;
1149                 }
1150         }
1151
1152         if (!image_to_draw) {
1153
1154                 /* look it up */
1155
1156                 bool full_image;
1157                 image_to_draw = get_image (sample_start, sample_end, full_image);
1158
1159                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 image to draw = %2 (full? %3)\n", name, image_to_draw, full_image));
1160
1161                 if (!image_to_draw) {
1162                         /* image not currently available. A redraw will be scheduled
1163                            when it is ready.
1164                         */
1165                         return;
1166                 }
1167
1168                 if (full_image) {
1169                         /* found an image that covers our entire sample range,
1170                          * so keep a reference to it.
1171                          */
1172                         _current_image = image_to_draw;
1173                 }
1174         }
1175
1176         /* compute the first pixel of the image that should be used when we
1177          * render the specified range.
1178          */
1179
1180         image_origin_in_self_coordinates = (image_to_draw->start - _region_start) / _samples_per_pixel;
1181
1182         if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
1183                 /* we are going to draw the first pixel for this region, but
1184                    we may not want this to overlap a border around the
1185                    waveform. If so, _start_shift will be set.
1186                 */
1187                 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
1188                 //draw_start += _start_shift;
1189                 //image_origin_in_self_coordinates += _start_shift;
1190         }
1191
1192         /* the image may only be a best-effort ... it may not span the entire
1193          * range requested, though it is guaranteed to cover the start. So
1194          * determine how many pixels we can actually draw.
1195          */
1196
1197         double draw_width;
1198
1199         if (image_to_draw != _current_image) {
1200                 lci.release ();
1201
1202                 /* the image is guaranteed to start at or before
1203                  * draw_start. But if it starts before draw_start, that reduces
1204                  * the maximum available width we can render with.
1205                  *
1206                  * so .. clamp the draw width to the smaller of what we need to
1207                  * draw or the available width of the image.
1208                  */
1209
1210                 draw_width = min ((double) image_to_draw->image->get_width() - (draw_start - image_to_draw->start),
1211                                   (draw_end - draw_start));
1212
1213
1214                 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),
1215                                                               image_to_draw->image->get_width(), image_origin_in_self_coordinates,
1216                                                               image_to_draw->start, _region_start));
1217         } else {
1218                 draw_width = draw_end - draw_start;
1219                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("use current image, span entire render width %1..%2\n", draw_start, draw_end));
1220         }
1221
1222         context->rectangle (draw_start, draw.y0, draw_width, draw.height());
1223
1224         /* round image origin position to an exact pixel in device space to
1225          * avoid blurring
1226          */
1227
1228         double x  = self.x0 + image_origin_in_self_coordinates;
1229         double y  = self.y0;
1230         context->user_to_device (x, y);
1231         x = round (x);
1232         y = round (y);
1233         context->device_to_user (x, y);
1234
1235         /* the coordinates specify where in "user coordinates" (i.e. what we
1236          * generally call "canvas coordinates" in this code) the image origin
1237          * will appear. So specifying (10,10) will put the upper left corner of
1238          * the image at (10,10) in user space.
1239          */
1240
1241         context->set_source (image_to_draw->image, x, y);
1242         context->fill ();
1243
1244         /* image obtained, some of it painted to display: we are rendered.
1245            Future calls to get_image_in_thread are now meaningful.
1246         */
1247
1248         rendered = true;
1249 }
1250
1251 void
1252 WaveView::compute_bounding_box () const
1253 {
1254         if (_region) {
1255                 _bounding_box = Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height);
1256         } else {
1257                 _bounding_box = boost::optional<Rect> ();
1258         }
1259
1260         _bounding_box_dirty = false;
1261 }
1262
1263 void
1264 WaveView::set_height (Distance height)
1265 {
1266         if (height != _height) {
1267                 begin_change ();
1268
1269                 invalidate_image_cache ();
1270                 _height = height;
1271                 get_image_in_thread = true;
1272
1273                 _bounding_box_dirty = true;
1274                 end_change ();
1275         }
1276 }
1277
1278 void
1279 WaveView::set_channel (int channel)
1280 {
1281         if (channel != _channel) {
1282                 begin_change ();
1283
1284                 invalidate_image_cache ();
1285                 _channel = channel;
1286
1287                 _bounding_box_dirty = true;
1288                 end_change ();
1289         }
1290 }
1291
1292 void
1293 WaveView::set_logscaled (bool yn)
1294 {
1295         if (_logscaled != yn) {
1296                 begin_visual_change ();
1297                 invalidate_image_cache ();
1298                 _logscaled = yn;
1299                 end_visual_change ();
1300         }
1301 }
1302
1303 void
1304 WaveView::gain_changed ()
1305 {
1306         begin_visual_change ();
1307         invalidate_image_cache ();
1308         _region_amplitude = _region->scale_amplitude ();
1309         get_image_in_thread = true;
1310         end_visual_change ();
1311 }
1312
1313 void
1314 WaveView::set_zero_color (Color c)
1315 {
1316         if (_zero_color != c) {
1317                 begin_visual_change ();
1318                 invalidate_image_cache ();
1319                 _zero_color = c;
1320                 end_visual_change ();
1321         }
1322 }
1323
1324 void
1325 WaveView::set_clip_color (Color c)
1326 {
1327         if (_clip_color != c) {
1328                 begin_visual_change ();
1329                 invalidate_image_cache ();
1330                 _clip_color = c;
1331                 end_visual_change ();
1332         }
1333 }
1334
1335 void
1336 WaveView::set_show_zero_line (bool yn)
1337 {
1338         if (_show_zero != yn) {
1339                 begin_visual_change ();
1340                 invalidate_image_cache ();
1341                 _show_zero = yn;
1342                 end_visual_change ();
1343         }
1344 }
1345
1346 void
1347 WaveView::set_shape (Shape s)
1348 {
1349         if (_shape != s) {
1350                 begin_visual_change ();
1351                 invalidate_image_cache ();
1352                 _shape = s;
1353                 end_visual_change ();
1354         }
1355 }
1356
1357 void
1358 WaveView::set_amplitude_above_axis (double a)
1359 {
1360         if (fabs (_amplitude_above_axis - a) > 0.01) {
1361                 begin_visual_change ();
1362                 invalidate_image_cache ();
1363                 _amplitude_above_axis = a;
1364                 get_image_in_thread = true;
1365                 end_visual_change ();
1366         }
1367 }
1368
1369 void
1370 WaveView::set_global_shape (Shape s)
1371 {
1372         if (_global_shape != s) {
1373                 _global_shape = s;
1374                 if (images) {
1375                         images->clear_cache ();
1376                 }
1377                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1378         }
1379 }
1380
1381 void
1382 WaveView::set_global_logscaled (bool yn)
1383 {
1384         if (_global_logscaled != yn) {
1385                 _global_logscaled = yn;
1386                 if (images) {
1387                         images->clear_cache ();
1388                 }
1389                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1390         }
1391 }
1392
1393 framecnt_t
1394 WaveView::region_length() const
1395 {
1396         return _region->length() - (_region_start - _region->start());
1397 }
1398
1399 framepos_t
1400 WaveView::region_end() const
1401 {
1402         return _region_start + region_length();
1403 }
1404
1405 void
1406 WaveView::set_region_start (frameoffset_t start)
1407 {
1408         if (!_region) {
1409                 return;
1410         }
1411
1412         if (_region_start == start) {
1413                 return;
1414         }
1415
1416         begin_change ();
1417         _region_start = start;
1418         _bounding_box_dirty = true;
1419         end_change ();
1420 }
1421
1422 void
1423 WaveView::region_resized ()
1424 {
1425         /* Called when the region start or end (thus length) has changed.
1426         */
1427
1428         if (!_region) {
1429                 return;
1430         }
1431
1432         begin_change ();
1433         _region_start = _region->start();
1434         _bounding_box_dirty = true;
1435         end_change ();
1436 }
1437
1438 void
1439 WaveView::set_global_gradient_depth (double depth)
1440 {
1441         if (_global_gradient_depth != depth) {
1442                 _global_gradient_depth = depth;
1443                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1444         }
1445 }
1446
1447 void
1448 WaveView::set_global_show_waveform_clipping (bool yn)
1449 {
1450         if (_global_show_waveform_clipping != yn) {
1451                 _global_show_waveform_clipping = yn;
1452                 ClipLevelChanged ();
1453         }
1454 }
1455
1456 void
1457 WaveView::set_start_shift (double pixels)
1458 {
1459         if (pixels < 0) {
1460                 return;
1461         }
1462
1463         begin_visual_change ();
1464         _start_shift = pixels;
1465         end_visual_change ();
1466 }
1467
1468 void
1469 WaveView::cancel_my_render_request () const
1470 {
1471         if (!images) {
1472                 return;
1473         }
1474
1475         /* try to stop any current rendering of the request, or prevent it from
1476          * ever starting up.
1477          */
1478
1479         if (current_request) {
1480                 current_request->cancel ();
1481         }
1482
1483         Glib::Threads::Mutex::Lock lm (request_queue_lock);
1484
1485         /* now remove it from the queue and reset our request pointer so that
1486            have no outstanding request (that we know about)
1487         */
1488
1489         request_queue.erase (this);
1490         current_request.reset ();
1491         DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 now has no request %2\n", this));
1492
1493 }
1494
1495 void
1496 WaveView::set_image_cache_size (uint64_t sz)
1497 {
1498         if (!images) {
1499                 images = new WaveViewCache;
1500         }
1501
1502         images->set_image_cache_threshold (sz);
1503 }
1504
1505 /*-------------------------------------------------*/
1506
1507 void
1508 WaveView::start_drawing_thread ()
1509 {
1510         if (!_drawing_thread) {
1511                 _drawing_thread = Glib::Threads::Thread::create (sigc::ptr_fun (WaveView::drawing_thread));
1512         }
1513 }
1514
1515 void
1516 WaveView::stop_drawing_thread ()
1517 {
1518         while (_drawing_thread) {
1519                 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1520                 g_atomic_int_set (&drawing_thread_should_quit, 1);
1521                 request_cond.signal ();
1522         }
1523 }
1524
1525 void
1526 WaveView::drawing_thread ()
1527 {
1528         using namespace Glib::Threads;
1529
1530         WaveView const * requestor;
1531         Mutex::Lock lm (request_queue_lock);
1532         bool run = true;
1533
1534         while (run) {
1535
1536                 /* remember that we hold the lock at this point, no matter what */
1537
1538                 if (g_atomic_int_get (&drawing_thread_should_quit)) {
1539                         break;
1540                 }
1541
1542                 if (request_queue.empty()) {
1543                         request_cond.wait (request_queue_lock);
1544                 }
1545
1546                 if (request_queue.empty()) {
1547                         continue;
1548                 }
1549
1550                 /* remove the request from the queue (remember: the "request"
1551                  * is just a pointer to a WaveView object)
1552                  */
1553
1554                 requestor = *(request_queue.begin());
1555                 request_queue.erase (request_queue.begin());
1556
1557                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("start request for %1 at %2\n", requestor, g_get_monotonic_time()));
1558
1559                 boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
1560
1561                 if (!req) {
1562                         continue;
1563                 }
1564
1565                 /* Generate an image. Unlock the request queue lock
1566                  * while we do this, so that other things can happen
1567                  * as we do rendering.
1568                  */
1569
1570                 request_queue_lock.unlock (); /* some RAII would be good here */
1571
1572                 try {
1573                         requestor->generate_image (req, true);
1574                 } catch (...) {
1575                         req->image.clear(); /* just in case it was set before the exception, whatever it was */
1576                 }
1577
1578                 request_queue_lock.lock ();
1579
1580                 req.reset (); /* drop/delete request as appropriate */
1581         }
1582
1583         /* thread is vanishing */
1584         _drawing_thread = 0;
1585 }
1586
1587 /*-------------------------------------------------*/
1588
1589 WaveViewCache::WaveViewCache ()
1590         : image_cache_size (0)
1591         , _image_cache_threshold (100 * 1048576) /* bytes */
1592 {
1593 }
1594
1595 WaveViewCache::~WaveViewCache ()
1596 {
1597 }
1598
1599
1600 boost::shared_ptr<WaveViewCache::Entry>
1601 WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
1602                              framepos_t start, framepos_t end,
1603                              int channel,
1604                              Coord height,
1605                              float amplitude,
1606                              Color fill_color,
1607                              double samples_per_pixel,
1608                              bool& full_coverage)
1609 {
1610         ImageCache::iterator x;
1611
1612         if ((x = cache_map.find (src)) == cache_map.end ()) {
1613                 /* nothing in the cache for this audio source at all */
1614                 return boost::shared_ptr<WaveViewCache::Entry> ();
1615         }
1616
1617         CacheLine& caches = x->second;
1618         boost::shared_ptr<Entry> best_partial;
1619         framecnt_t max_coverage = 0;
1620
1621         /* Find a suitable ImageSurface, if it exists.
1622         */
1623
1624         for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
1625
1626                 boost::shared_ptr<Entry> e (*c);
1627
1628                 if (channel != e->channel
1629                     || height != e->height
1630                     || amplitude != e->amplitude
1631                     || samples_per_pixel != e->samples_per_pixel
1632                     || fill_color != e->fill_color) {
1633                         continue;
1634                 }
1635
1636                 switch (Evoral::coverage (start, end, e->start, e->end)) {
1637                 case Evoral::OverlapExternal:  /* required range is inside image range */
1638                         DEBUG_TRACE (DEBUG::WaveView, string_compose ("found image spanning %1..%2 covers %3..%4\n",
1639                                                                       e->start, e->end, start, end));
1640                         use (src, e);
1641                         full_coverage = true;
1642                         return e;
1643
1644                 case Evoral::OverlapStart: /* required range start is covered by image range */
1645                         if ((e->end - start) > max_coverage) {
1646                                 best_partial = e;
1647                                 max_coverage = e->end - start;
1648                         }
1649                         break;
1650
1651                 case Evoral::OverlapNone:
1652                 case Evoral::OverlapEnd:
1653                 case Evoral::OverlapInternal:
1654                         break;
1655                 }
1656         }
1657
1658         if (best_partial) {
1659                 DEBUG_TRACE (DEBUG::WaveView, string_compose ("found PARTIAL image spanning %1..%2 partially covers %3..%4\n",
1660                                                               best_partial->start, best_partial->end, start, end));
1661                 use (src, best_partial);
1662                 full_coverage = false;
1663                 return best_partial;
1664         }
1665
1666         return boost::shared_ptr<Entry> ();
1667 }
1668
1669 void
1670 WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> src,
1671                                         int channel,
1672                                         Coord height,
1673                                         float amplitude,
1674                                         Color fill_color,
1675                                         double samples_per_pixel)
1676 {
1677         list <uint32_t> deletion_list;
1678         uint32_t other_entries = 0;
1679         ImageCache::iterator x;
1680
1681         /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1682
1683         if ((x = cache_map.find (src)) == cache_map.end ()) {
1684                 return;
1685         }
1686
1687         CacheLine& caches  = x->second;
1688
1689         for (CacheLine::iterator c1 = caches.begin(); c1 != caches.end(); ) {
1690
1691                 CacheLine::iterator nxt = c1;
1692                 ++nxt;
1693
1694                 boost::shared_ptr<Entry> e1 (*c1);
1695
1696                 if (channel != e1->channel
1697                     || height != e1->height
1698                     || amplitude != e1->amplitude
1699                     || samples_per_pixel != e1->samples_per_pixel
1700                     || fill_color != e1->fill_color) {
1701
1702                         /* doesn't match current properties, ignore and move on
1703                          * to the next one.
1704                          */
1705
1706                         other_entries++;
1707                         c1 = nxt;
1708                         continue;
1709                 }
1710
1711                 /* c1 now points to a cached image entry that matches current
1712                  * properties. Check all subsequent cached imaged entries to
1713                  * see if there are others that also match but represent
1714                  * subsets of the range covered by this one.
1715                  */
1716
1717                 for (CacheLine::iterator c2 = c1; c2 != caches.end(); ) {
1718
1719                         CacheLine::iterator nxt2 = c2;
1720                         ++nxt2;
1721
1722                         boost::shared_ptr<Entry> e2 (*c2);
1723
1724                         if (e1 == e2 || channel != e2->channel
1725                             || height != e2->height
1726                             || amplitude != e2->amplitude
1727                             || samples_per_pixel != e2->samples_per_pixel
1728                             || fill_color != e2->fill_color) {
1729
1730                                 /* properties do not match, ignore for the
1731                                  * purposes of consolidation.
1732                                  */
1733                                 c2 = nxt2;
1734                                 continue;
1735                         }
1736
1737                         if (e2->start >= e1->start && e2->end <= e1->end) {
1738                                 /* c2 is fully contained by c1, so delete it */
1739                                 caches.erase (c2);
1740
1741                                 /* and re-start the whole iteration */
1742                                 nxt = caches.begin ();
1743                                 break;
1744                         }
1745
1746                         c2 = nxt2;
1747                 }
1748
1749                 c1 = nxt;
1750         }
1751 }
1752
1753 void
1754 WaveViewCache::use (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1755 {
1756         ce->timestamp = g_get_monotonic_time ();
1757 }
1758
1759 void
1760 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1761 {
1762         /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1763
1764         Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
1765
1766         image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1767
1768         if (cache_full()) {
1769                 cache_flush ();
1770         }
1771
1772         ce->timestamp = g_get_monotonic_time ();
1773
1774         cache_map[src].push_back (ce);
1775 }
1776
1777 uint64_t
1778 WaveViewCache::compute_image_cache_size()
1779 {
1780         uint64_t total = 0;
1781         for (ImageCache::iterator s = cache_map.begin(); s != cache_map.end(); ++s) {
1782                 CacheLine& per_source_cache (s->second);
1783                 for (CacheLine::iterator c = per_source_cache.begin(); c != per_source_cache.end(); ++c) {
1784                         Cairo::RefPtr<Cairo::ImageSurface> img ((*c)->image);
1785                         total += img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1786                 }
1787         }
1788         return total;
1789 }
1790
1791 bool
1792 WaveViewCache::cache_full()
1793 {
1794         return image_cache_size > _image_cache_threshold;
1795 }
1796
1797 void
1798 WaveViewCache::cache_flush ()
1799 {
1800         /* Build a sortable list of all cache entries */
1801
1802         CacheList cache_list;
1803
1804         for (ImageCache::const_iterator cm = cache_map.begin(); cm != cache_map.end(); ++cm) {
1805                 for (CacheLine::const_iterator cl = cm->second.begin(); cl != cm->second.end(); ++cl) {
1806                         cache_list.push_back (make_pair (cm->first, *cl));
1807                 }
1808         }
1809
1810         /* sort list in LRU order */
1811         SortByTimestamp sorter;
1812         sort (cache_list.begin(), cache_list.end(), sorter);
1813
1814         while (image_cache_size > _image_cache_threshold && !cache_map.empty() && !cache_list.empty()) {
1815
1816                 ListEntry& le (cache_list.front());
1817
1818                 ImageCache::iterator x;
1819
1820                 if ((x = cache_map.find (le.first)) != cache_map.end ()) {
1821
1822                         CacheLine& cl  = x->second;
1823
1824                         for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
1825
1826                                 if (*c == le.second) {
1827
1828                                         DEBUG_TRACE (DEBUG::WaveView, string_compose ("Removing cache line entry for %1\n", x->first->name()));
1829
1830                                         /* Remove this entry from this cache line */
1831                                         cl.erase (c);
1832
1833                                         if (cl.empty()) {
1834                                                 /* remove cache line from main cache: no more entries */
1835                                                 cache_map.erase (x);
1836                                         }
1837
1838                                         break;
1839                                 }
1840                         }
1841
1842                         Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
1843                         uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1844
1845                         if (image_cache_size > size) {
1846                                 image_cache_size -= size;
1847                         } else {
1848                                 image_cache_size = 0;
1849                         }
1850                         DEBUG_TRACE (DEBUG::WaveView, string_compose ("cache shrunk to %1\n", image_cache_size));
1851                 }
1852
1853                 /* Remove from the linear list, even if we didn't find it in
1854                  * the actual cache_mao
1855                  */
1856                 cache_list.erase (cache_list.begin());
1857         }
1858 }
1859
1860 void
1861 WaveViewCache::clear_cache ()
1862 {
1863         DEBUG_TRACE (DEBUG::WaveView, "clear cache\n");
1864         const uint64_t image_cache_threshold = _image_cache_threshold;
1865         _image_cache_threshold = 0;
1866         cache_flush ();
1867         _image_cache_threshold = image_cache_threshold;
1868 }
1869
1870 void
1871 WaveViewCache::set_image_cache_threshold (uint64_t sz)
1872 {
1873         DEBUG_TRACE (DEBUG::WaveView, string_compose ("new image cache size %1\n", sz));
1874         _image_cache_threshold = sz;
1875         cache_flush ();
1876 }