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