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