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