remove debug output and get logic correct to cause first render to always use the...
[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                 
854                 const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
855                 
856                 boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
857
858                 /* Note that Region::read_peaks() takes a start position based on an
859                    offset into the Region's **SOURCE**, rather than an offset into
860                    the Region itself.
861                 */
862                                      
863                 _region->read_peaks (peaks.get(), n_peaks,
864                                      sample_start, sample_end - sample_start,
865                                      req->channel,
866                                      req->samples_per_pixel);
867                 
868     
869                 // apply waveform amplitude zoom multiplier
870
871                 for (int i = 0; i < n_peaks; ++i) {
872                         peaks[i].max *= _amplitude_above_axis;
873                         peaks[i].min *= _amplitude_above_axis;
874                 }
875                 
876                 req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
877                 
878                 /* make sure we record the sample positions that were actually used */
879                 
880                 req->start = sample_start;
881                 req->end = sample_end;
882                 
883                 draw_image (req->image, peaks.get(), n_peaks, req);
884         }
885         
886         if (in_render_thread && !req->should_stop()) {
887                 const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
888         }
889         
890         return;
891 }
892
893 /** Given a waveform that starts at window x-coordinate @param wave_origin
894  * and the first pixel that we will actually draw @param draw_start, return
895  * the offset into an image of the entire waveform that we will need to use.
896  *
897  * Note: most of our cached images are NOT of the entire waveform, this is just
898  * computationally useful when determining which the sample range span for
899  * the image we need.
900  */
901 static inline double
902 window_to_image (double wave_origin, double image_start)
903 {
904         return image_start - wave_origin;
905 }
906
907 void
908 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
909 {
910         assert (_samples_per_pixel != 0);
911
912         if (!rendered) {
913                 /* first image generation should happen in RENDER thread */
914                 get_image_in_thread = false;
915                 rendered = true; /* comments in header file */
916         }
917         
918         if (!_region) {
919                 return;
920         }
921
922         /* a WaveView is intimately connected to an AudioRegion. It will
923          * display the waveform within the region, anywhere from the start of
924          * the region to its end.
925          *
926          * the area we've been aked to render may overlap with area covered
927          * by the region in any of the normal ways:
928          *
929          *  - it may begin and end within the area covered by the region
930          *  - it may start before and end after the area covered by region
931          *  - it may start before and end within the area covered by the region
932          *  - it may start within and end after the area covered by the region
933          *  - it may be precisely coincident with the area covered by region.
934          *
935          * So let's start by determining the area covered by the region, in
936          * window coordinates. It begins at zero (in item coordinates for this
937          * waveview, and extends to region_length() / _samples_per_pixel.
938          */
939         
940         Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
941
942         /* Now lets get the intersection with the area we've been asked to draw */
943
944         boost::optional<Rect> d = self.intersection (area);
945
946         if (!d) {
947                 return;
948         }
949
950         Rect draw = d.get();
951
952         /* "draw" is now a rectangle that defines the rectangle we need to
953          * update/render the waveview into, in window coordinate space.
954          */
955         
956         /* window coordinates - pixels where x=0 is the left edge of the canvas
957          * window. We round down in case we were asked to
958          * draw "between" pixels at the start and/or end.
959          */
960         
961         double draw_start = floor (draw.x0);
962         const double draw_end = floor (draw.x1);
963
964         // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
965         
966         /* image coordnates: pixels where x=0 is the start of this waveview,
967          * wherever it may be positioned. thus image_start=N means "an image
968          * that begins N pixels after the start of region that this waveview is
969          * representing.
970          */
971
972         const framepos_t image_start = window_to_image (self.x0, draw_start);
973         const framepos_t image_end = window_to_image (self.x0, draw_end);
974         
975         // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
976
977         /* sample coordinates - note, these are not subject to rounding error 
978          *
979          * "sample_start = N" means "the first sample we need to represent is N
980          * samples after the first sample of the region"
981          */
982          
983         framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
984         framepos_t sample_end   = _region_start + (image_end * _samples_per_pixel);
985
986         // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
987
988         /* sample_start and sample_end are bounded by the region
989          * limits. sample_start, because of the was just computed, must already
990          * be greater than or equal to the _region_start value.
991          */
992
993         sample_end = min (region_end(), sample_end);
994         
995         // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
996
997         double image_offset;
998
999         if (_current_image) {
1000
1001                 /* check it covers the right sample range */
1002                 
1003                 if (_current_image->start > sample_start || _current_image->end < sample_end) {
1004                         /* doesn't cover the area we need ... reset */
1005                         _current_image.reset ();
1006                 } else {
1007                         /* timestamp our continuing use of this image/cache entry */
1008                         images->use (_region->audio_source (_channel), _current_image);
1009                 }
1010         }
1011
1012         if (!_current_image) {
1013
1014                 /* look it up */
1015                 
1016                 _current_image = get_image (sample_start, sample_end);
1017
1018                 if (!_current_image) {
1019                         /* image not currently available. A redraw will be scheduled
1020                            when it is ready.
1021                         */
1022                         return;
1023                 }
1024         }
1025
1026         /* fix up offset: returned value is the first sample of the returned image */
1027
1028         image_offset = (_current_image->start - _region_start) / _samples_per_pixel;
1029         
1030         // cerr << "Offset into image to place at zero: " << image_offset << endl;
1031
1032         if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
1033                 /* we are going to draw the first pixel for this region, but 
1034                    we may not want this to overlap a border around the
1035                    waveform. If so, _start_shift will be set.
1036                 */
1037                 //cerr << name.substr (23) << " ss = " << sample_start << " rs = " << _region_start << " sf = " << _start_shift << " ds = " << draw_start << " self = " << self << " draw = " << draw << endl;
1038                 //draw_start += _start_shift;
1039                 //image_offset += _start_shift;
1040         }
1041         
1042         context->rectangle (draw_start, draw.y0, draw_end - draw_start, draw.height());
1043
1044         /* round image origin position to an exact pixel in device space to
1045          * avoid blurring
1046          */
1047
1048         double x  = self.x0 + image_offset;
1049         double y  = self.y0;
1050         context->user_to_device (x, y);
1051         x = round (x);
1052         y = round (y);
1053         context->device_to_user (x, y);
1054
1055         context->set_source (_current_image->image, x, y);
1056         context->fill ();
1057
1058 }
1059
1060 void
1061 WaveView::compute_bounding_box () const
1062 {
1063         if (_region) {
1064                 _bounding_box = Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height);
1065         } else {
1066                 _bounding_box = boost::optional<Rect> ();
1067         }
1068
1069         _bounding_box_dirty = false;
1070 }
1071
1072 void
1073 WaveView::set_height (Distance height)
1074 {
1075         if (height != _height) {
1076                 begin_change ();
1077
1078                 invalidate_image_cache ();
1079                 _height = height;
1080                 get_image_in_thread = true;
1081                 
1082                 _bounding_box_dirty = true;
1083                 end_change ();
1084         }
1085 }
1086
1087 void
1088 WaveView::set_channel (int channel)
1089 {
1090         if (channel != _channel) {
1091                 begin_change ();
1092
1093                 invalidate_image_cache ();
1094                 _channel = channel;
1095
1096                 _bounding_box_dirty = true;
1097                 end_change ();
1098         }
1099 }
1100
1101 void
1102 WaveView::set_logscaled (bool yn)
1103 {
1104         if (_logscaled != yn) {
1105                 begin_visual_change ();
1106                 invalidate_image_cache ();
1107                 _logscaled = yn;
1108                 end_visual_change ();
1109         }
1110 }
1111
1112 void
1113 WaveView::gain_changed ()
1114 {
1115         begin_visual_change ();
1116         invalidate_image_cache ();
1117         _region_amplitude = _region->scale_amplitude ();
1118         end_visual_change ();
1119 }
1120
1121 void
1122 WaveView::set_zero_color (Color c)
1123 {
1124         if (_zero_color != c) {
1125                 begin_visual_change ();
1126                 invalidate_image_cache ();
1127                 _zero_color = c;
1128                 end_visual_change ();
1129         }
1130 }
1131
1132 void
1133 WaveView::set_clip_color (Color c)
1134 {
1135         if (_clip_color != c) {
1136                 begin_visual_change ();
1137                 invalidate_image_cache ();
1138                 _clip_color = c;
1139                 end_visual_change ();
1140         }
1141 }
1142
1143 void
1144 WaveView::set_show_zero_line (bool yn)
1145 {
1146         if (_show_zero != yn) {
1147                 begin_visual_change ();
1148                 invalidate_image_cache ();
1149                 _show_zero = yn;
1150                 end_visual_change ();
1151         }
1152 }
1153
1154 void
1155 WaveView::set_shape (Shape s)
1156 {
1157         if (_shape != s) {
1158                 begin_visual_change ();
1159                 invalidate_image_cache ();
1160                 _shape = s;
1161                 end_visual_change ();
1162         }
1163 }
1164
1165 void
1166 WaveView::set_amplitude_above_axis (double a)
1167 {
1168         if (fabs (_amplitude_above_axis - a) > 0.01) {
1169                 begin_visual_change ();
1170                 invalidate_image_cache ();
1171                 _amplitude_above_axis = a;
1172                 end_visual_change ();
1173         }
1174 }
1175
1176 void
1177 WaveView::set_global_shape (Shape s)
1178 {
1179         if (_global_shape != s) {
1180                 _global_shape = s;
1181                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1182         }
1183 }
1184
1185 void
1186 WaveView::set_global_logscaled (bool yn)
1187 {
1188         if (_global_logscaled != yn) {
1189                 _global_logscaled = yn;
1190                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1191         }
1192 }
1193
1194 framecnt_t
1195 WaveView::region_length() const
1196 {
1197         return _region->length() - (_region_start - _region->start());
1198 }
1199
1200 framepos_t
1201 WaveView::region_end() const
1202 {
1203         return _region_start + region_length();
1204 }
1205
1206 void
1207 WaveView::set_region_start (frameoffset_t start)
1208 {
1209         if (!_region) {
1210                 return;
1211         }
1212
1213         if (_region_start == start) {
1214                 return;
1215         }
1216
1217         begin_change ();
1218         _region_start = start;
1219         _bounding_box_dirty = true;
1220         end_change ();
1221 }
1222
1223 void
1224 WaveView::region_resized ()
1225 {
1226         /* Called when the region start or end (thus length) has changed.
1227         */
1228
1229         if (!_region) {
1230                 return;
1231         }
1232
1233         begin_change ();
1234         _region_start = _region->start();
1235         _bounding_box_dirty = true;
1236         end_change ();
1237 }
1238
1239 void
1240 WaveView::set_global_gradient_depth (double depth)
1241 {
1242         if (_global_gradient_depth != depth) {
1243                 _global_gradient_depth = depth;
1244                 VisualPropertiesChanged (); /* EMIT SIGNAL */
1245         }
1246 }
1247
1248 void
1249 WaveView::set_global_show_waveform_clipping (bool yn)
1250 {
1251         if (_global_show_waveform_clipping != yn) {
1252                 _global_show_waveform_clipping = yn;
1253                 ClipLevelChanged ();
1254         }
1255 }
1256
1257 void
1258 WaveView::set_start_shift (double pixels)
1259 {
1260         if (pixels < 0) {
1261                 return;
1262         }
1263
1264         begin_visual_change ();
1265         _start_shift = pixels;
1266         end_visual_change ();
1267 }
1268         
1269
1270 void
1271 WaveView::cancel_my_render_request () const
1272 {
1273         if (!images) {
1274                 return;
1275         }
1276
1277         /* try to stop any current rendering of the request, or prevent it from
1278          * ever starting up.
1279          */
1280         
1281         if (current_request) {
1282                 current_request->cancel ();
1283         }
1284         
1285         Glib::Threads::Mutex::Lock lm (request_queue_lock);
1286
1287         /* now remove it from the queue and reset our request pointer so that
1288            have no outstanding request (that we know about)
1289         */
1290         
1291         request_queue.erase (this);
1292         current_request.reset ();
1293 }
1294
1295 void
1296 WaveView::send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1297 {       
1298         if (req->type == WaveViewThreadRequest::Draw && current_request) {
1299                 /* this will stop rendering in progress (which might otherwise
1300                    be long lived) for any current request.
1301                 */
1302                 current_request->cancel ();
1303         }
1304
1305         start_drawing_thread ();
1306
1307         Glib::signal_idle().connect (sigc::bind (sigc::mem_fun (this, &WaveView::idle_send_request), req));
1308 }
1309
1310 bool
1311 WaveView::idle_send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
1312 {
1313         {
1314                 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1315                 /* swap requests (protected by lock) */
1316                 current_request = req;
1317                 request_queue.insert (this);
1318         }
1319
1320         request_cond.signal (); /* wake thread */
1321         
1322         return false; /* do not call from idle again */
1323 }
1324
1325 /*-------------------------------------------------*/
1326
1327 void
1328 WaveView::start_drawing_thread ()
1329 {
1330         if (!_drawing_thread) {
1331                 _drawing_thread = Glib::Threads::Thread::create (sigc::ptr_fun (WaveView::drawing_thread));
1332         }
1333 }
1334
1335 void
1336 WaveView::stop_drawing_thread ()
1337 {
1338         if (_drawing_thread) {
1339                 Glib::Threads::Mutex::Lock lm (request_queue_lock);
1340                 g_atomic_int_set (&drawing_thread_should_quit, 1);
1341                 request_cond.signal ();
1342         }
1343 }
1344
1345 void
1346 WaveView::drawing_thread ()
1347 {
1348         using namespace Glib::Threads;
1349
1350         WaveView const * requestor;
1351         Mutex::Lock lm (request_queue_lock);
1352         bool run = true;
1353
1354         while (run) {
1355
1356                 /* remember that we hold the lock at this point, no matter what */
1357                 
1358                 if (g_atomic_int_get (&drawing_thread_should_quit)) {
1359                         break;
1360                 }
1361
1362                 if (request_queue.empty()) {
1363                         request_cond.wait (request_queue_lock);
1364                 }
1365
1366                 /* remove the request from the queue (remember: the "request"
1367                  * is just a pointer to a WaveView object)
1368                  */
1369                 
1370                 requestor = *(request_queue.begin());
1371                 request_queue.erase (request_queue.begin());
1372
1373                 boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
1374
1375                 if (!req) {
1376                         continue;
1377                 }
1378
1379                 /* Generate an image. Unlock the request queue lock
1380                  * while we do this, so that other things can happen
1381                  * as we do rendering.
1382                  */
1383
1384                 request_queue_lock.unlock (); /* some RAII would be good here */
1385
1386                 try {
1387                         requestor->generate_image (req, true);
1388                 } catch (...) {
1389                         req->image.clear(); /* just in case it was set before the exception, whatever it was */
1390                 }
1391
1392                 request_queue_lock.lock ();
1393
1394                 req.reset (); /* drop/delete request as appropriate */
1395         }
1396
1397         /* thread is vanishing */
1398         _drawing_thread = 0;
1399 }
1400
1401 /*-------------------------------------------------*/
1402
1403 WaveViewCache::WaveViewCache ()
1404         : image_cache_size (0)
1405         , _image_cache_threshold (100 * 1048576) /* bytes */
1406 {
1407 }
1408
1409 WaveViewCache::~WaveViewCache ()
1410 {
1411 }
1412
1413
1414 boost::shared_ptr<WaveViewCache::Entry>
1415 WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
1416                              framepos_t start, framepos_t end,
1417                              int channel,
1418                              Coord height,
1419                              float amplitude,
1420                              Color fill_color,
1421                              double samples_per_pixel)
1422 {
1423         ImageCache::iterator x;
1424         
1425         if ((x = cache_map.find (src)) == cache_map.end ()) {
1426                 /* nothing in the cache for this audio source at all */
1427                 return boost::shared_ptr<WaveViewCache::Entry> ();
1428         }
1429
1430         CacheLine& caches = x->second;
1431
1432         /* Find a suitable ImageSurface, if it exists.
1433         */
1434
1435         for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
1436
1437                 boost::shared_ptr<Entry> e (*c);
1438                 
1439                 if (channel != e->channel
1440                     || height != e->height
1441                     || amplitude != e->amplitude
1442                     || samples_per_pixel != e->samples_per_pixel
1443                     || fill_color != e->fill_color) {
1444                         continue;
1445                 }
1446
1447                 if (end <= e->end && start >= e->start) {
1448                         /* found an image that covers the range we need */
1449                         use (src, e);
1450                         return e;
1451                 }
1452         }
1453
1454         return boost::shared_ptr<Entry> ();
1455 }
1456
1457 void
1458 WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> src,
1459                                         int channel,
1460                                         Coord height,
1461                                         float amplitude,
1462                                         Color fill_color,
1463                                         double samples_per_pixel)
1464 {
1465         list <uint32_t> deletion_list;
1466         uint32_t other_entries = 0;
1467         ImageCache::iterator x;
1468
1469         /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1470         
1471         if ((x = cache_map.find (src)) == cache_map.end ()) {
1472                 return;
1473         }
1474
1475         CacheLine& caches  = x->second;
1476
1477         for (CacheLine::iterator c1 = caches.begin(); c1 != caches.end(); ) {
1478
1479                 CacheLine::iterator nxt = c1;
1480                 ++nxt;
1481
1482                 boost::shared_ptr<Entry> e1 (*c1);
1483                 
1484                 if (channel != e1->channel
1485                     || height != e1->height
1486                     || amplitude != e1->amplitude
1487                     || samples_per_pixel != e1->samples_per_pixel
1488                     || fill_color != e1->fill_color) {
1489
1490                         /* doesn't match current properties, ignore and move on
1491                          * to the next one.
1492                          */
1493                         
1494                         other_entries++;
1495                         c1 = nxt;
1496                         continue;
1497                 }
1498                 
1499                 /* c1 now points to a cached image entry that matches current
1500                  * properties. Check all subsequent cached imaged entries to
1501                  * see if there are others that also match but represent
1502                  * subsets of the range covered by this one.
1503                  */
1504
1505                 for (CacheLine::iterator c2 = c1; c2 != caches.end(); ) {
1506
1507                         CacheLine::iterator nxt2 = c2;
1508                         ++nxt2;
1509
1510                         boost::shared_ptr<Entry> e2 (*c2);
1511                         
1512                         if (e1 == e2 || channel != e2->channel
1513                             || height != e2->height
1514                             || amplitude != e2->amplitude
1515                             || samples_per_pixel != e2->samples_per_pixel
1516                             || fill_color != e2->fill_color) {
1517
1518                                 /* properties do not match, ignore for the
1519                                  * purposes of consolidation.
1520                                  */
1521                                 c2 = nxt2;
1522                                 continue;
1523                         }
1524                         
1525                         if (e2->start >= e1->start && e2->end <= e1->end) {
1526                                 /* c2 is fully contained by c1, so delete it */
1527                                 c2 = caches.erase (c2);
1528                                 continue;
1529                         }
1530
1531                         c2 = nxt2;
1532                 }
1533
1534                 c1 = nxt;
1535         }
1536 }
1537
1538 void
1539 WaveViewCache::use (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1540 {
1541         ce->timestamp = g_get_monotonic_time ();
1542 }
1543
1544 void
1545 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
1546 {
1547         /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
1548         
1549         Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
1550
1551         image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1552
1553         if (cache_full()) {
1554                 cache_flush ();
1555         }
1556
1557         ce->timestamp = g_get_monotonic_time ();
1558
1559         cache_map[src].push_back (ce);
1560         cache_list.push_back (make_pair (src, ce));
1561 }
1562
1563 uint64_t
1564 WaveViewCache::compute_image_cache_size()
1565 {
1566         uint64_t total = 0;
1567         for (ImageCache::iterator s = cache_map.begin(); s != cache_map.end(); ++s) {
1568                 CacheLine& per_source_cache (s->second);
1569                 for (CacheLine::iterator c = per_source_cache.begin(); c != per_source_cache.end(); ++c) {
1570                         Cairo::RefPtr<Cairo::ImageSurface> img ((*c)->image);
1571                         total += img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1572                 }
1573         }
1574         return total;
1575 }
1576
1577 bool
1578 WaveViewCache::cache_full()
1579 {
1580         return image_cache_size > _image_cache_threshold;
1581 }
1582
1583 void
1584 WaveViewCache::cache_flush ()
1585 {
1586         SortByTimestamp sorter;
1587
1588         /* sort list in LRU order */
1589
1590         sort (cache_list.begin(), cache_list.end(), sorter);
1591
1592         while (image_cache_size > _image_cache_threshold) {
1593
1594                 ListEntry& le (cache_list.front());
1595
1596                 ImageCache::iterator x;
1597                 
1598                 if ((x = cache_map.find (le.first)) == cache_map.end ()) {
1599                         /* wierd ... no entry for this AudioSource */
1600                         continue;
1601                 }
1602                 
1603                 CacheLine& cl  = x->second;
1604
1605                 for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
1606
1607                         if (*c == le.second) {
1608
1609                                 /* Remove this entry from this cache line */
1610                                 cl.erase (c);
1611
1612                                 if (cl.empty()) {
1613                                         /* remove cache line from main cache: no more entries */
1614                                         cache_map.erase (x);
1615                                 }
1616
1617                                 break;
1618                         }
1619                 }
1620                 
1621                 Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
1622                 uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
1623
1624                 if (image_cache_size > size) {
1625                         image_cache_size -= size;
1626                 } else {
1627                         image_cache_size = 0;
1628                 }
1629       
1630                 /* Remove from the linear list */
1631                 cache_list.erase (cache_list.begin());
1632         }
1633 }
1634
1635 void
1636 WaveViewCache::set_image_cache_threshold (uint64_t sz)
1637 {
1638         _image_cache_threshold = sz;
1639         cache_flush ();
1640 }