a couple of debug output statements to help diagnose a crash
[ardour.git] / libs / canvas / wave_view.cc
index ebcae314aaf02c062f31b0ba4570886f79a2a673..e3377ab1d952115a15b77ee51fb58e72d4a35803 100644 (file)
@@ -37,6 +37,7 @@
 #include "ardour/lmath.h"
 #include "ardour/audioregion.h"
 #include "ardour/audiosource.h"
+#include "ardour/session.h"
 
 #include "canvas/canvas.h"
 #include "canvas/colors.h"
@@ -44,6 +45,8 @@
 #include "canvas/utils.h"
 #include "canvas/wave_view.h"
 
+#include "evoral/Range.hpp"
+
 #include <gdkmm/general.h>
 
 #include "gtkmm2ext/gui_thread.h"
@@ -62,6 +65,7 @@ double WaveView::_clip_level = 0.98853;
 WaveViewCache* WaveView::images = 0;
 gint WaveView::drawing_thread_should_quit = 0;
 Glib::Threads::Mutex WaveView::request_queue_lock;
+Glib::Threads::Mutex WaveView::current_image_lock;
 Glib::Threads::Cond WaveView::request_cond;
 Glib::Threads::Thread* WaveView::_drawing_thread = 0;
 WaveView::DrawingRequestQueue WaveView::request_queue;
@@ -92,10 +96,14 @@ WaveView::WaveView (Canvas* c, boost::shared_ptr<ARDOUR::AudioRegion> region)
        , always_get_image_in_thread (false)
        , rendered (false)
 {
+       if (!images) {
+               images = new WaveViewCache;
+       }
+
        VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
        ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
 
-       ImageReady.connect (image_ready_connection, MISSING_INVALIDATOR, boost::bind (&WaveView::image_ready, this), gui_context());
+       ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
 }
 
 WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
@@ -115,20 +123,28 @@ WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
        , _gradient_depth_independent (false)
        , _amplitude_above_axis (1.0)
        , _region_amplitude (region->scale_amplitude ())
+       , _start_shift (0.0)
        , _region_start (region->start())
        , get_image_in_thread (false)
        , always_get_image_in_thread (false)
        , rendered (false)
 {
+       if (!images) {
+               images = new WaveViewCache;
+       }
+
        VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
        ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
 
-       ImageReady.connect (image_ready_connection, MISSING_INVALIDATOR, boost::bind (&WaveView::image_ready, this), gui_context());
+       ImageReady.connect (image_ready_connection, invalidator (*this), boost::bind (&WaveView::image_ready, this), gui_context());
 }
 
 WaveView::~WaveView ()
 {
        invalidate_image_cache ();
+       if (images ) {
+               images->clear_cache ();
+       }
 }
 
 string
@@ -140,6 +156,7 @@ WaveView::debug_name() const
 void
 WaveView::image_ready ()
 {
+        DEBUG_TRACE (DEBUG::WaveView, string_compose ("queue draw for %1 at %2 (vis = %3 CR %4)\n", this, g_get_monotonic_time(), visible(), current_request));
        redraw ();
 }
 
@@ -245,45 +262,72 @@ WaveView::set_clip_level (double dB)
 void
 WaveView::invalidate_image_cache ()
 {
+        DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 invalidates image cache and cancels current request\n", this));
        cancel_my_render_request ();
+       Glib::Threads::Mutex::Lock lci (current_image_lock);
        _current_image.reset ();
 }
 
-Coord
-WaveView::y_extent (double s, bool /*round_to_lower_edge*/) const
+void
+WaveView::compute_tips (PeakData const & peak, WaveView::LineTips& tips) const
 {
-       /* it is important that this returns an integral value, so that we
-        * can ensure correct single pixel behaviour.
-        *
-        * we need (_height - max(wave_line_width))
-        * wave_line_width == 1 IFF top==bottom (1 sample per pixel or flat line)
-        * wave_line_width == 2 otherwise
-        * then round away from the zero line, towards peak
-        */
-       if (_shape == Rectified) {
-               // we only ever have 1 point and align to the bottom (not center)
-               return floor ((1.0 - s) * (_height - 2.0));
-       } else {
-               /* currently canvas rectangle is off-by-one and we
-                * cannot draw a pixel at 0 (-.5 .. +.5) without it being
-                * clipped. A value 1.0 (ideally one point at y=0) ends
-                * up a pixel down. and a value of -1.0 (ideally y = _height-1)
-                * currently is on the bottom separator line :(
-                * So to make the complete waveform appear centered in
-                * a region, we translate by +.5 (instead of -.5)
-                * and waste two pixel of height: -4 (instad of -2)
-                *
-                * This needs fixing in canvas/rectangle the intersect
-                * functions and probably a couple of other places as well...
+       const double effective_height  = _height;
+
+       /* remember: canvas (and cairo) coordinate space puts the origin at the upper left. 
+          
+          So, a sample value of 1.0 (0dbFS) will be computed as:
+
+                (1.0 - 1.0) * 0.5 * effective_height
+
+          which evaluates to 0, or the top of the image.
+
+          A sample value of -1.0 will be computed as
+
+               (1.0 + 1.0) * 0.5 * effective height
+
+           which evaluates to effective height, or the bottom of the image.
+       */
+
+       const double pmax = (1.0 - peak.max) * 0.5 * effective_height;
+       const double pmin = (1.0 - peak.min) * 0.5 * effective_height;
+
+       /* remember that the bottom of the image (pmin) has larger y-coordinates
+          than the top (pmax).
+       */
+
+       double spread = (pmin - pmax) * 0.5;
+
+       /* find the nearest pixel to the nominal center. */
+       const double center = round (pmin - spread);
+
+       if (spread < 1.0) {
+               /* minimum distance between line ends is 1 pixel, and we want it "centered" on a pixel,
+                  as per cairo single-pixel line issues.
+
+                  NOTE: the caller will not draw a line between these two points if the spread is
+                  less than 2 pixels. So only the tips.top value matters, which is where we will
+                  draw a single pixel as part of the outline.
                 */
-               Coord pos;
-               if (s < 0) {
-                       pos = ceil  ((1.0 - s) * .5 * (_height - 4.0));
-               } else {
-                       pos = floor ((1.0 - s) * .5 * (_height - 4.0));
-               }
-               return min (_height - 4.0, (max (0.0, pos)));
+               tips.top = center;
+               tips.bot = center + 1.0;
+       } else {
+               /* round spread above and below center to an integer number of pixels */
+               spread = round (spread);
+               /* top and bottom are located equally either side of the center */
+               tips.top = center - spread;
+               tips.bot = center + spread;
        }
+       
+       tips.top = min (effective_height, max (0.0, tips.top));
+       tips.bot = min (effective_height, max (0.0, tips.bot));
+}
+       
+
+Coord
+WaveView::y_extent (double s) const
+{
+       assert (_shape == Rectified);
+       return floor ((1.0 - s) * _height);
 }
 
 void
@@ -318,16 +362,6 @@ WaveView::draw_absent_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData
        context->fill ();
 }
 
-struct LineTips {
-       double top;
-       double bot;
-       double spread;
-       bool clip_max;
-       bool clip_min;
-
-       LineTips() : top (0.0), bot (0.0), clip_max (false), clip_min (false) {}
-};
-
 struct ImageSet {
        Cairo::RefPtr<Cairo::ImageSurface> wave;
        Cairo::RefPtr<Cairo::ImageSurface> outline;
@@ -384,8 +418,8 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
 
                                tips[i].bot = height() - 1.0;
                                const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
-                               tips[i].top = y_extent (p, false);
-                               tips[i].spread = p * (_height - 1.0);
+                               tips[i].top = y_extent (p);
+                               tips[i].spread = p * _height;
 
                                if (_peaks[i].max >= clip_level) {
                                        tips[i].clip_max = true;
@@ -401,8 +435,8 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
 
                                tips[i].bot = height() - 1.0;
                                const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
-                               tips[i].top = y_extent (p, false);
-                               tips[i].spread = p * (_height - 2.0);
+                               tips[i].top = y_extent (p);
+                               tips[i].spread = p * _height;
                                if (p >= clip_level) {
                                        tips[i].clip_max = true;
                                }
@@ -414,34 +448,34 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
 
                if (_logscaled) {
                        for (int i = 0; i < n_peaks; ++i) {
-                               double top = _peaks[i].max;
-                               double bot = _peaks[i].min;
+                               PeakData p;
+                               p.max = _peaks[i].max;
+                               p.min = _peaks[i].min;
 
                                if (_peaks[i].max >= clip_level) {
-                                               tips[i].clip_max = true;
+                                       tips[i].clip_max = true;
                                }
                                if (-(_peaks[i].min) >= clip_level) {
                                        tips[i].clip_min = true;
                                }
 
-                               if (top > 0.0) {
-                                       top = alt_log_meter (fast_coefficient_to_dB (top));
-                               } else if (top < 0.0) {
-                                       top =-alt_log_meter (fast_coefficient_to_dB (-top));
+                               if (p.max > 0.0) {
+                                       p.max = alt_log_meter (fast_coefficient_to_dB (p.max));
+                               } else if (p.max < 0.0) {
+                                       p.max =-alt_log_meter (fast_coefficient_to_dB (-p.max));
                                } else {
-                                       top = 0.0;
+                                       p.max = 0.0;
                                }
 
-                               if (bot > 0.0) {
-                                       bot = alt_log_meter (fast_coefficient_to_dB (bot));
-                               } else if (bot < 0.0) {
-                                       bot = -alt_log_meter (fast_coefficient_to_dB (-bot));
+                               if (p.min > 0.0) {
+                                       p.min = alt_log_meter (fast_coefficient_to_dB (p.min));
+                               } else if (p.min < 0.0) {
+                                       p.min = -alt_log_meter (fast_coefficient_to_dB (-p.min));
                                } else {
-                                       bot = 0.0;
+                                       p.min = 0.0;
                                }
-
-                               tips[i].top = y_extent (top, false);
-                               tips[i].bot = y_extent (bot, true);
+                               
+                               compute_tips (p, tips[i]);
                                tips[i].spread = tips[i].bot - tips[i].top;
                        }
 
@@ -454,8 +488,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                                        tips[i].clip_min = true;
                                }
 
-                               tips[i].top = y_extent (_peaks[i].max, false);
-                               tips[i].bot = y_extent (_peaks[i].min, true);
+                               compute_tips (_peaks[i], tips[i]);
                                tips[i].spread = tips[i].bot - tips[i].top;
                        }
 
@@ -476,16 +509,16 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
        /* ensure single-pixel lines */
 
        wave_context->set_line_width (1.0);
-       wave_context->translate (0.5, +1.5);
+       wave_context->translate (0.5, 0.5);
 
        outline_context->set_line_width (1.0);
-       outline_context->translate (0.5, +1.5);
+       outline_context->translate (0.5, 0.5);
 
        clip_context->set_line_width (1.0);
-       clip_context->translate (0.5, +1.5);
+       clip_context->translate (0.5, 0.5);
 
        zero_context->set_line_width (1.0);
-       zero_context->translate (0.5, +1.5);
+       zero_context->translate (0.5, 0.5);
 
        /* the height of the clip-indicator should be at most 7 pixels,
         * or 5% of the height of the waveview item.
@@ -547,7 +580,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                outline_context->stroke ();
 
        } else {
-               const double height_2 = (_height - 2.5) * .5;
+               const int height_zero = floor( _height * .5);
 
                for (int i = 0; i < n_peaks; ++i) {
 
@@ -557,6 +590,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                                wave_context->move_to (i, tips[i].top);
                                wave_context->line_to (i, tips[i].bot);
                        }
+                       
                        /* draw square waves and other discontiguous points clearly */
                        if (i > 0) {
                                if (tips[i-1].top + 2 < tips[i].top) {
@@ -572,10 +606,11 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                                }
                        }
 
-                       /* zero line */
+                       /* zero line, show only if there is enough spread 
+                       or the waveform line does not cross zero line */
 
-                       if (tips[i].spread >= 5.0 && show_zero_line()) {
-                               zero_context->move_to (i, floor(height_2));
+                       if (show_zero_line() && ((tips[i].spread >= 5.0) || (tips[i].top > height_zero ) || (tips[i].bot < height_zero)) ) {
+                               zero_context->move_to (i, height_zero);
                                zero_context->rel_line_to (1.0, 0);
                        }
 
@@ -596,13 +631,17 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                                        clipped = true;
                                }
 
-                               if (!clipped) {
-                                       outline_context->move_to (i, tips[i].bot + 1.0);
-                                       /* normal lower terminal dot */
+                               if (!clipped && tips[i].spread > 2.0) {
+                                       /* only draw the outline if the spread
+                                          implies 3 or more pixels (so that we see 1
+                                          white pixel in the middle).
+                                       */
+                                       outline_context->move_to (i, tips[i].bot);
+                                       /* normal lower terminal dot; line moves up */
                                        outline_context->rel_line_to (0, -1.0);
 
-                                       outline_context->move_to (i, tips[i].top - 1.0);
-                                       /* normal upper terminal dot */
+                                       outline_context->move_to (i, tips[i].top);
+                                       /* normal upper terminal dot, line moves down */
                                        outline_context->rel_line_to (0, 1.0);
                                }
                        } else {
@@ -616,10 +655,15 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                                }
 
                                if (!clipped) {
+                                       /* special case where only 1 pixel of
+                                        * the waveform line is drawn (and
+                                        * nothing else).
+                                        *
+                                        * we draw a 1px "line", pretending
+                                        * that the span is 1.0 (whether it is
+                                        * zero or 1.0)
+                                        */
                                        wave_context->move_to (i, tips[i].top);
-                                       /* special case where outline only is drawn.
-                                        * we draw a 1px "line", pretending that the span is 1.0
-                                       */
                                        wave_context->rel_line_to (0, 1.0);
                                }
                        }
@@ -698,18 +742,15 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
 boost::shared_ptr<WaveViewCache::Entry>
 WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) const
 {
+       
        boost::shared_ptr<WaveViewCache::Entry> ret (new WaveViewCache::Entry (req->channel,
                                                                               req->height,
-                                                                              req->region_amplitude,
+                                                                              req->amplitude,
                                                                               req->fill_color,
                                                                               req->samples_per_pixel,
                                                                               req->start,
                                                                               req->end,
                                                                               req->image));
-       if (!images) {
-               images = new WaveViewCache;
-       }
-
        images->add (_region->audio_source (_channel), ret);
        
        /* consolidate cache first (removes fully-contained
@@ -717,8 +758,8 @@ WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) co
         */
        
        images->consolidate_image_cache (_region->audio_source (_channel),
-                                        _channel, _height, _region_amplitude,
-                                        _fill_color, _samples_per_pixel);
+                                        req->channel, req->height, req->amplitude,
+                                        req->fill_color, req->samples_per_pixel);
 
        return ret;
 }
@@ -744,6 +785,10 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                 * have an image there. if so, use it (and put it in the cache
                 * while we're here.
                 */
+
+                DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 CR %2 stop? %3 image %4\n", this, current_request, 
+                                                              (current_request ? current_request->should_stop() : false), 
+                                                              (current_request ? current_request->image : 0)));
                
                if (current_request && !current_request->should_stop() && current_request->image) {
 
@@ -755,7 +800,7 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                                
                                ret.reset (new WaveViewCache::Entry (current_request->channel,
                                                                     current_request->height,
-                                                                    current_request->region_amplitude,
+                                                                    current_request->amplitude,
                                                                     current_request->fill_color,
                                                                     current_request->samples_per_pixel,
                                                                     current_request->start,
@@ -787,7 +832,7 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
        if (!ret || !full_image) {
 
                if ((rendered && get_image_in_thread) || always_get_image_in_thread) {
-
+                        
                        DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: generating image in caller thread\n", name));
                        
                        boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
@@ -798,10 +843,10 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                        req->samples_per_pixel = _samples_per_pixel;
                        req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
                        req->channel = _channel;
-                       req->width = _canvas->visible_area().width();
                        req->height = _height;
                        req->fill_color = _fill_color;
-                       req->region_amplitude = _region_amplitude;
+                       req->amplitude = _region_amplitude * _amplitude_above_axis;
+                        req->width = desired_image_width ();
 
                        /* draw image in this (the GUI thread) */
                        
@@ -839,7 +884,27 @@ WaveView::get_image_from_cache (framepos_t start, framepos_t end, bool& full) co
        }
 
        return images->lookup_image (_region->audio_source (_channel), start, end, _channel,
-                                    _height, _region_amplitude, _fill_color, _samples_per_pixel, full);
+                                    _height, _region_amplitude * _amplitude_above_axis, _fill_color, _samples_per_pixel, full);
+}
+
+framecnt_t
+WaveView::desired_image_width () const
+{
+        /* compute how wide the image should be, in samples. 
+         *
+         * We want at least 1 canvas width's worth, but if that 
+         * represents less than 1/10th of a second, use 1/10th of
+         * a second instead.
+         */
+        
+        framecnt_t canvas_width_samples = _canvas->visible_area().width() * _samples_per_pixel;
+        const framecnt_t one_tenth_of_second = _region->session().frame_rate() / 10;
+
+        if (canvas_width_samples > one_tenth_of_second) {
+                return  canvas_width_samples;
+        } 
+
+        return one_tenth_of_second;
 }
 
 void
@@ -853,12 +918,35 @@ WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, frame
        req->samples_per_pixel = _samples_per_pixel;
        req->region = _region; /* weak ptr, to avoid storing a reference in the request queue */
        req->channel = _channel;
-       req->width = _canvas->visible_area().width();
        req->height = _height;
        req->fill_color = _fill_color;
-       req->region_amplitude = _region_amplitude;
+       req->amplitude = _region_amplitude * _amplitude_above_axis;
+        req->width = desired_image_width ();
+
+       if (current_request) {
+               /* this will stop rendering in progress (which might otherwise
+                  be long lived) for any current request.
+               */
+               current_request->cancel ();
+       }
+
+       start_drawing_thread ();
+
+       /* swap requests (protected by lock) */
+
+       {
+               Glib::Threads::Mutex::Lock lm (request_queue_lock);
+               current_request = req;
 
-       send_request (req);
+                DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 now has current request %2\n", this, req));
+
+                if (request_queue.insert (this).second) {
+                        /* this waveview was not already in the request queue, make sure we wake
+                           the rendering thread in case it is asleep.
+                        */
+                        request_cond.signal ();
+                }
+       }
 }
 
 void
@@ -867,11 +955,13 @@ WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_
        if (!req->should_stop()) {
 
                /* sample position is canonical here, and we want to generate
-                * an image that spans about twice the canvas width
+                * an image that spans about 3x the canvas width. We get to that 
+                 * width by using an image sample count of the screen width added
+                 * on each side of the desired image center.
                 */
                
                const framepos_t center = req->start + ((req->end - req->start) / 2);
-               const framecnt_t image_samples = req->width * req->samples_per_pixel; /* one canvas width */
+               const framecnt_t image_samples = req->width;
                
                /* we can request data from anywhere in the Source, between 0 and its length
                 */
@@ -892,8 +982,6 @@ WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_
                                                             req->channel,
                                                             req->samples_per_pixel);
                
-               // apply waveform amplitude zoom multiplier
-
                req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
                /* make sure we record the sample positions that were actually used */
                req->start = sample_start;
@@ -901,20 +989,33 @@ WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_
                
                if (peaks_read > 0) {
 
-                       for (framecnt_t i = 0; i < n_peaks; ++i) {
-                               peaks[i].max *= _amplitude_above_axis;
-                               peaks[i].min *= _amplitude_above_axis;
+                       /* region amplitude will have been used to generate the
+                        * peak values already, but not the visual-only
+                        * amplitude_above_axis. So apply that here before
+                        * rendering.
+                        */
+                       
+                       if (_amplitude_above_axis != 1.0) {
+                               for (framecnt_t i = 0; i < n_peaks; ++i) {
+                                       peaks[i].max *= _amplitude_above_axis;
+                                       peaks[i].min *= _amplitude_above_axis;
+                               }
                        }
 
                        draw_image (req->image, peaks.get(), n_peaks, req);
                } else {
                        draw_absent_image (req->image, peaks.get(), n_peaks);
                }
+       } else {
+               cerr << "Request stopped before image generation\n";
        }
        
        if (in_render_thread && !req->should_stop()) {
+                DEBUG_TRACE (DEBUG::WaveView, string_compose ("done with request for %1 at %2 CR %3 req %4 range %5 .. %6\n", this, g_get_monotonic_time(), current_request, req, req->start, req->end));
                const_cast<WaveView*>(this)->ImageReady (); /* emit signal */
        }
+
+       cerr << "Generate image done, image = " << req->image << endl;
        
        return;
 }
@@ -942,6 +1043,8 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
                return;
        }
 
+        DEBUG_TRACE (DEBUG::WaveView, string_compose ("render %1 at %2\n", this, g_get_monotonic_time()));
+
        /* a WaveView is intimately connected to an AudioRegion. It will
         * display the waveform within the region, anywhere from the start of
         * the region to its end.
@@ -1022,6 +1125,7 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
        double image_origin_in_self_coordinates;
        boost::shared_ptr<WaveViewCache::Entry> image_to_draw;
        
+       Glib::Threads::Mutex::Lock lci (current_image_lock);
        if (_current_image) {
 
                /* check it covers the right sample range */
@@ -1084,6 +1188,7 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
        double draw_width;
        
        if (image_to_draw != _current_image) {
+               lci.release ();
 
                /* the image is guaranteed to start at or before
                 * draw_start. But if it starts before draw_start, that reduces
@@ -1192,6 +1297,7 @@ WaveView::gain_changed ()
        begin_visual_change ();
        invalidate_image_cache ();
        _region_amplitude = _region->scale_amplitude ();
+       get_image_in_thread = true;
        end_visual_change ();
 }
 
@@ -1246,6 +1352,7 @@ WaveView::set_amplitude_above_axis (double a)
                begin_visual_change ();
                invalidate_image_cache ();
                _amplitude_above_axis = a;
+               get_image_in_thread = true;
                end_visual_change ();
        }
 }
@@ -1255,6 +1362,9 @@ WaveView::set_global_shape (Shape s)
 {
        if (_global_shape != s) {
                _global_shape = s;
+               if (images) {
+                       images->clear_cache ();
+               }
                VisualPropertiesChanged (); /* EMIT SIGNAL */
        }
 }
@@ -1264,6 +1374,9 @@ WaveView::set_global_logscaled (bool yn)
 {
        if (_global_logscaled != yn) {
                _global_logscaled = yn;
+               if (images) {
+                       images->clear_cache ();
+               }
                VisualPropertiesChanged (); /* EMIT SIGNAL */
        }
 }
@@ -1342,7 +1455,6 @@ WaveView::set_start_shift (double pixels)
        _start_shift = pixels;
        end_visual_change ();
 }
-       
 
 void
 WaveView::cancel_my_render_request () const
@@ -1367,36 +1479,18 @@ WaveView::cancel_my_render_request () const
        
        request_queue.erase (this);
        current_request.reset ();
-}
+        DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 now has no request %2\n", this));
 
-void
-WaveView::send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
-{      
-       if (req->type == WaveViewThreadRequest::Draw && current_request) {
-               /* this will stop rendering in progress (which might otherwise
-                  be long lived) for any current request.
-               */
-               current_request->cancel ();
-       }
-
-       start_drawing_thread ();
-
-       Glib::signal_idle().connect (sigc::bind (sigc::mem_fun (*this, &WaveView::idle_send_request), req));
 }
 
-bool
-WaveView::idle_send_request (boost::shared_ptr<WaveViewThreadRequest> req) const
+void
+WaveView::set_image_cache_size (uint64_t sz)
 {
-       {
-               Glib::Threads::Mutex::Lock lm (request_queue_lock);
-               /* swap requests (protected by lock) */
-               current_request = req;
-               request_queue.insert (this);
+       if (!images) {
+               images = new WaveViewCache;
        }
 
-       request_cond.signal (); /* wake thread */
-       
-       return false; /* do not call from idle again */
+       images->set_image_cache_threshold (sz);
 }
 
 /*-------------------------------------------------*/
@@ -1440,6 +1534,11 @@ WaveView::drawing_thread ()
                        request_cond.wait (request_queue_lock);
                }
 
+               if (request_queue.empty()) {
+                       assert (g_atomic_int_get (&drawing_thread_should_quit));
+                       continue; // or break;
+               }
+
                /* remove the request from the queue (remember: the "request"
                 * is just a pointer to a WaveView object)
                 */
@@ -1447,6 +1546,8 @@ WaveView::drawing_thread ()
                requestor = *(request_queue.begin());
                request_queue.erase (request_queue.begin());
 
+                DEBUG_TRACE (DEBUG::WaveView, string_compose ("start request for %1 at %2\n", requestor, g_get_monotonic_time()));
+
                boost::shared_ptr<WaveViewThreadRequest> req = requestor->current_request;
 
                if (!req) {
@@ -1524,25 +1625,25 @@ WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
                        continue;
                }
 
-               if (end <= e->end && start >= e->start) {
-                       /* found an image that covers the range we need */
+                switch (Evoral::coverage (start, end, e->start, e->end)) {
+                case Evoral::OverlapExternal:  /* required range is inside image range */
                        DEBUG_TRACE (DEBUG::WaveView, string_compose ("found image spanning %1..%2 covers %3..%4\n",
                                                                      e->start, e->end, start, end));
                        use (src, e);
-                       full_coverage = true;
-                       return e;
-               }
-
-               if (start >= e->start) {
-                       /* found an image that covers the start, but not the
-                        * end. See if it is longer than any other similar
-                        * partial image that we've found so far.
-                        */
-
-                       if ((e->end - e->start) > max_coverage) {
-                               best_partial = e;
-                               max_coverage = e->end - e->start;
-                       }
+                        full_coverage = true;
+                        return e;
+
+                case Evoral::OverlapStart: /* required range start is covered by image range */
+                        if ((e->end - start) > max_coverage) {
+                                best_partial = e;
+                                max_coverage = e->end - start;
+                        }
+                        break;
+
+                case Evoral::OverlapNone:
+                case Evoral::OverlapEnd:
+                case Evoral::OverlapInternal:
+                        break;
                }
        }
 
@@ -1627,8 +1728,11 @@ WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> s
                        
                        if (e2->start >= e1->start && e2->end <= e1->end) {
                                /* c2 is fully contained by c1, so delete it */
-                               c2 = caches.erase (c2);
-                               continue;
+                               caches.erase (c2);
+
+                               /* and re-start the whole iteration */
+                               nxt = caches.begin ();
+                               break;
                        }
 
                        c2 = nxt2;
@@ -1660,7 +1764,6 @@ WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_pt
        ce->timestamp = g_get_monotonic_time ();
 
        cache_map[src].push_back (ce);
-       cache_list.push_back (make_pair (src, ce));
 }
 
 uint64_t
@@ -1686,58 +1789,80 @@ WaveViewCache::cache_full()
 void
 WaveViewCache::cache_flush ()
 {
-       SortByTimestamp sorter;
+       /* Build a sortable list of all cache entries */
+       
+       CacheList cache_list;
 
+       for (ImageCache::const_iterator cm = cache_map.begin(); cm != cache_map.end(); ++cm) {
+               for (CacheLine::const_iterator cl = cm->second.begin(); cl != cm->second.end(); ++cl) {
+                       cache_list.push_back (make_pair (cm->first, *cl));
+               }
+       }
+       
        /* sort list in LRU order */
-
+       SortByTimestamp sorter;
        sort (cache_list.begin(), cache_list.end(), sorter);
 
-       while (image_cache_size > _image_cache_threshold) {
+       while (image_cache_size > _image_cache_threshold && !cache_map.empty() && !cache_list.empty()) {
 
                ListEntry& le (cache_list.front());
 
                ImageCache::iterator x;
                
-               if ((x = cache_map.find (le.first)) == cache_map.end ()) {
-                       /* wierd ... no entry for this AudioSource */
-                       continue;
-               }
+               if ((x = cache_map.find (le.first)) != cache_map.end ()) {
                
-               CacheLine& cl  = x->second;
-
-               for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
-
-                       if (*c == le.second) {
-
-                               /* Remove this entry from this cache line */
-                               cl.erase (c);
-
-                               if (cl.empty()) {
-                                       /* remove cache line from main cache: no more entries */
-                                       cache_map.erase (x);
+                       CacheLine& cl  = x->second;
+                       
+                       for (CacheLine::iterator c = cl.begin(); c != cl.end(); ++c) {
+                               
+                               if (*c == le.second) {
+
+                                       DEBUG_TRACE (DEBUG::WaveView, string_compose ("Removing cache line entry for %1\n", x->first->name()));
+                                       
+                                       /* Remove this entry from this cache line */
+                                       cl.erase (c);
+                                       
+                                       if (cl.empty()) {
+                                               /* remove cache line from main cache: no more entries */
+                                               cache_map.erase (x);
+                                       }
+                                       
+                                       break;
                                }
-
-                               break;
                        }
-               }
-               
-               Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
-               uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
-
-               if (image_cache_size > size) {
-                       image_cache_size -= size;
-               } else {
-                       image_cache_size = 0;
+                       
+                       Cairo::RefPtr<Cairo::ImageSurface> img (le.second->image);
+                       uint64_t size = img->get_height() * img->get_width() * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
+                       
+                       if (image_cache_size > size) {
+                               image_cache_size -= size;
+                       } else {
+                               image_cache_size = 0;
+                       }
+                       DEBUG_TRACE (DEBUG::WaveView, string_compose ("cache shrunk to %1\n", image_cache_size));
                }
       
-               /* Remove from the linear list */
+               /* Remove from the linear list, even if we didn't find it in
+                * the actual cache_mao
+                */
                cache_list.erase (cache_list.begin());
        }
 }
 
+void
+WaveViewCache::clear_cache ()
+{
+       DEBUG_TRACE (DEBUG::WaveView, "clear cache\n");
+       const uint64_t image_cache_threshold = _image_cache_threshold;
+       _image_cache_threshold = 0;
+       cache_flush ();
+       _image_cache_threshold = image_cache_threshold;
+}
+
 void
 WaveViewCache::set_image_cache_threshold (uint64_t sz)
 {
+       DEBUG_TRACE (DEBUG::WaveView, string_compose ("new image cache size %1\n", sz));
        _image_cache_threshold = sz;
        cache_flush ();
 }