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