fix crash when copy'ing latent plugins
[ardour.git] / libs / canvas / wave_view.cc
index e8db7d8c6a3055a8a6056f94d94aa91e5d7a7dcc..17ee8609ff79dc641d084ea5bba29430f8a0514d 100644 (file)
@@ -65,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;
@@ -72,6 +73,14 @@ WaveView::DrawingRequestQueue WaveView::request_queue;
 PBD::Signal0<void> WaveView::VisualPropertiesChanged;
 PBD::Signal0<void> WaveView::ClipLevelChanged;
 
+/* NO_THREAD_WAVEVIEWS is defined by the top level wscript
+ * if --no-threaded-waveviws is provided at the configure step.
+ */
+
+#ifndef NO_THREADED_WAVEVIEWS
+#define ENABLE_THREADED_WAVEFORM_RENDERING
+#endif
+
 WaveView::WaveView (Canvas* c, boost::shared_ptr<ARDOUR::AudioRegion> region)
        : Item (c)
        , _region (region)
@@ -141,6 +150,9 @@ WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
 WaveView::~WaveView ()
 {
        invalidate_image_cache ();
+       if (images ) {
+               images->clear_cache ();
+       }
 }
 
 string
@@ -152,7 +164,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));
+       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 ();
 }
 
@@ -258,8 +270,9 @@ 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));
+       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 ();
 }
 
@@ -268,8 +281,8 @@ WaveView::compute_tips (PeakData const & peak, WaveView::LineTips& tips) const
 {
        const double effective_height  = _height;
 
-       /* remember: canvas (and cairo) coordinate space puts the origin at the upper left. 
-          
+       /* 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
@@ -312,11 +325,11 @@ WaveView::compute_tips (PeakData const & peak, WaveView::LineTips& tips) const
                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
@@ -469,7 +482,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                                } else {
                                        p.min = 0.0;
                                }
-                               
+
                                compute_tips (p, tips[i]);
                                tips[i].spread = tips[i].bot - tips[i].top;
                        }
@@ -493,7 +506,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
        if (req->should_stop()) {
                return;
        }
-       
+
        Color alpha_one = rgba_to_color (0, 0, 0, 1.0);
 
        set_source_rgba (wave_context, alpha_one);
@@ -585,7 +598,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) {
@@ -601,7 +614,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
                                }
                        }
 
-                       /* zero line, show only if there is enough spread 
+                       /* zero line, show only if there is enough spread
                        or the waveform line does not cross zero line */
 
                        if (show_zero_line() && ((tips[i].spread >= 5.0) || (tips[i].top > height_zero ) || (tips[i].bot < height_zero)) ) {
@@ -673,7 +686,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
        if (req->should_stop()) {
                return;
        }
-       
+
        Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);
 
        /* Here we set a source colour and use the various components as a mask. */
@@ -717,7 +730,7 @@ WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peak
        if (req->should_stop()) {
                return;
        }
-       
+
        context->mask (images.wave, 0, 0);
        context->fill ();
 
@@ -737,7 +750,11 @@ 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
 {
-       
+       if (!req->image) {
+               // cerr << "asked to cache null image!!!\n";
+               return boost::shared_ptr<WaveViewCache::Entry> ();
+       }
+
        boost::shared_ptr<WaveViewCache::Entry> ret (new WaveViewCache::Entry (req->channel,
                                                                               req->height,
                                                                               req->amplitude,
@@ -747,11 +764,11 @@ WaveView::cache_request_result (boost::shared_ptr<WaveViewThreadRequest> req) co
                                                                               req->end,
                                                                               req->image));
        images->add (_region->audio_source (_channel), ret);
-       
+
        /* consolidate cache first (removes fully-contained
         * duplicate images)
         */
-       
+
        images->consolidate_image_cache (_region->audio_source (_channel),
                                         req->channel, req->height, req->amplitude,
                                         req->fill_color, req->samples_per_pixel);
@@ -765,14 +782,14 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
        boost::shared_ptr<WaveViewCache::Entry> ret;
 
        full_image = true;
-       
+
        /* this is called from a ::render() call, when we need an image to
           draw with.
        */
 
        DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 needs image from %2 .. %3\n", name, start, end));
-       
-       
+
+
        {
                Glib::Threads::Mutex::Lock lmq (request_queue_lock);
 
@@ -781,10 +798,10 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                 * 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)));
-               
+               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) {
 
                        /* put the image into the cache so that other
@@ -792,7 +809,7 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                         */
 
                        if (current_request->start <= start && current_request->end >= end) {
-                               
+
                                ret.reset (new WaveViewCache::Entry (current_request->channel,
                                                                     current_request->height,
                                                                     current_request->amplitude,
@@ -801,7 +818,7 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                                                                     current_request->start,
                                                                     current_request->end,
                                                                     current_request->image));
-       
+
                                cache_request_result (current_request);
                                DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: got image from completed request, spans %2..%3\n",
                                                                              name, current_request->start, current_request->end));
@@ -815,21 +832,26 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
        if (!ret) {
 
                /* no current image draw request, so look in the cache */
-               
+
                ret = get_image_from_cache (start, end, full_image);
                DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: lookup from cache gave %2 (full %3)\n",
                                                              name, ret, full_image));
 
        }
 
-       
-       
+
+
        if (!ret || !full_image) {
 
-               if ((rendered && get_image_in_thread) || always_get_image_in_thread) {
-                        
+#ifndef ENABLE_THREADED_WAVEFORM_RENDERING
+               if (1)
+#else
+               if ((rendered && get_image_in_thread) || always_get_image_in_thread)
+#endif
+               {
+
                        DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1: generating image in caller thread\n", name));
-                       
+
                        boost::shared_ptr<WaveViewThreadRequest> req (new WaveViewThreadRequest);
 
                        req->type = WaveViewThreadRequest::Draw;
@@ -841,10 +863,10 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                        req->height = _height;
                        req->fill_color = _fill_color;
                        req->amplitude = _region_amplitude * _amplitude_above_axis;
-                        req->width = desired_image_width ();
+                       req->width = desired_image_width ();
 
                        /* draw image in this (the GUI thread) */
-                       
+
                        generate_image (req, false);
 
                        /* cache the result */
@@ -854,7 +876,7 @@ WaveView::get_image (framepos_t start, framepos_t end, bool& full_image) const
                        /* reset this so that future missing images are
                         * generated in a a worker thread.
                         */
-                       
+
                        get_image_in_thread = false;
 
                } else {
@@ -885,21 +907,21 @@ WaveView::get_image_from_cache (framepos_t start, framepos_t end, bool& full) co
 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;
+       /* 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
@@ -916,13 +938,16 @@ WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, frame
        req->height = _height;
        req->fill_color = _fill_color;
        req->amplitude = _region_amplitude * _amplitude_above_axis;
-        req->width = desired_image_width ();
+       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 ();
+               Glib::Threads::Mutex::Lock lm (request_queue_lock);
+               if (current_request) {
+                       current_request->cancel ();
+               }
        }
 
        start_drawing_thread ();
@@ -933,14 +958,14 @@ WaveView::queue_get_image (boost::shared_ptr<const ARDOUR::Region> region, frame
                Glib::Threads::Mutex::Lock lm (request_queue_lock);
                current_request = req;
 
-                DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 now has current request %2\n", this, 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 ();
-                }
+               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 ();
+               }
        }
 }
 
@@ -950,38 +975,52 @@ 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 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.
+                * 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;
-               
+
                /* we can request data from anywhere in the Source, between 0 and its length
                 */
-               
+
                framepos_t sample_start = max (_region_start, (center - image_samples));
                framepos_t sample_end = min (center + image_samples, region_end());
-               const int n_peaks = llrintf ((sample_end - sample_start)/ (req->samples_per_pixel));
-               
+               const int n_peaks = std::max (1LL, llrint (ceil ((sample_end - sample_start) / (req->samples_per_pixel))));
+
+               assert (n_peaks > 0 && n_peaks < 32767);
+
                boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);
 
                /* Note that Region::read_peaks() takes a start position based on an
                   offset into the Region's **SOURCE**, rather than an offset into
                   the Region itself.
                */
-                                    
+
                framecnt_t peaks_read = _region->read_peaks (peaks.get(), n_peaks,
                                                             sample_start, sample_end - sample_start,
                                                             req->channel,
                                                             req->samples_per_pixel);
-               
+
+               if (req->should_stop()) {
+                       // cerr << "Request stopped after reading peaks\n";
+                       return;
+               }
+
                req->image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, req->height);
+
+               // http://cairographics.org/manual/cairo-Image-Surfaces.html#cairo-image-surface-create
+               // This function always returns a valid pointer, but it will return a pointer to a "nil" surface..
+               // but there's some evidence that req->image can be NULL.
+               // http://tracker.ardour.org/view.php?id=6478
+               assert (req->image);
+
                /* make sure we record the sample positions that were actually used */
                req->start = sample_start;
                req->end = sample_end;
-               
+
                if (peaks_read > 0) {
 
                        /* region amplitude will have been used to generate the
@@ -989,7 +1028,7 @@ WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_
                         * 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;
@@ -1001,13 +1040,15 @@ WaveView::generate_image (boost::shared_ptr<WaveViewThreadRequest> req, bool in_
                } 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));
+               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 */
        }
-       
+
        return;
 }
 
@@ -1029,12 +1070,12 @@ void
 WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
 {
        assert (_samples_per_pixel != 0);
-       
+
        if (!_region) {
                return;
        }
 
-        DEBUG_TRACE (DEBUG::WaveView, string_compose ("render %1 at %2\n", this, g_get_monotonic_time()));
+       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
@@ -1053,11 +1094,11 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
         * window coordinates. It begins at zero (in item coordinates for this
         * waveview, and extends to region_length() / _samples_per_pixel.
         */
-       
+
        Rect self = item_to_window (Rect (0.0, 0.0, region_length() / _samples_per_pixel, _height));
 
        // cerr << name << " RENDER " << area << " self = " << self << endl;
-       
+
        /* Now lets get the intersection with the area we've been asked to draw */
 
        boost::optional<Rect> d = self.intersection (area);
@@ -1071,17 +1112,17 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
        /* "draw" is now a rectangle that defines the rectangle we need to
         * update/render the waveview into, in window coordinate space.
         */
-       
+
        /* window coordinates - pixels where x=0 is the left edge of the canvas
         * window. We round down in case we were asked to
         * draw "between" pixels at the start and/or end.
         */
-       
+
        double draw_start = floor (draw.x0);
        const double draw_end = floor (draw.x1);
 
        // cerr << "Need to draw " << draw_start << " .. " << draw_end << " vs. " << area << " and self = " << self << endl;
-       
+
        /* image coordnates: pixels where x=0 is the start of this waveview,
         * wherever it may be positioned. thus image_start=N means "an image
         * that begins N pixels after the start of region that this waveview is
@@ -1090,18 +1131,18 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
 
        const framepos_t image_start = window_to_image (self.x0, draw_start);
        const framepos_t image_end = window_to_image (self.x0, draw_end);
-       
+
        // cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;
-       
-       /* sample coordinates - note, these are not subject to rounding error 
+
+       /* sample coordinates - note, these are not subject to rounding error
         *
         * "sample_start = N" means "the first sample we need to represent is N
         * samples after the first sample of the region"
         */
-        
+
        framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
        framepos_t sample_end   = _region_start + (image_end * _samples_per_pixel);
-       
+
        // cerr << "Sample space: " << sample_start << " .. " << sample_end << " @ " << _samples_per_pixel << " rs = " << _region_start << endl;
 
        /* sample_start and sample_end are bounded by the region
@@ -1110,16 +1151,17 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
         */
 
        sample_end = min (region_end(), sample_end);
-       
+
        // cerr << debug_name() << " will need image spanning " << sample_start << " .. " << sample_end << " region spans " << _region_start << " .. " << region_end() << endl;
 
        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 */
-               
+
                if (_current_image->start > sample_start || _current_image->end < sample_end) {
                        /* doesn't cover the area we need ... reset */
                        _current_image.reset ();
@@ -1138,7 +1180,7 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
                image_to_draw = get_image (sample_start, sample_end, full_image);
 
                DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 image to draw = %2 (full? %3)\n", name, image_to_draw, full_image));
-               
+
                if (!image_to_draw) {
                        /* image not currently available. A redraw will be scheduled
                           when it is ready.
@@ -1155,13 +1197,13 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
        }
 
        /* compute the first pixel of the image that should be used when we
-        * render the specified range. 
+        * render the specified range.
         */
 
        image_origin_in_self_coordinates = (image_to_draw->start - _region_start) / _samples_per_pixel;
-       
+
        if (_start_shift && (sample_start == _region_start) && (self.x0 == draw.x0)) {
-               /* we are going to draw the first pixel for this region, but 
+               /* we are going to draw the first pixel for this region, but
                   we may not want this to overlap a border around the
                   waveform. If so, _start_shift will be set.
                */
@@ -1169,15 +1211,16 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
                //draw_start += _start_shift;
                //image_origin_in_self_coordinates += _start_shift;
        }
-       
+
        /* the image may only be a best-effort ... it may not span the entire
         * range requested, though it is guaranteed to cover the start. So
         * determine how many pixels we can actually draw.
         */
 
        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
@@ -1187,13 +1230,12 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
                 * draw or the available width of the image.
                 */
 
-               draw_width = min ((double) image_to_draw->image->get_width() - (draw_start - image_to_draw->start),
-                                 (draw_end - draw_start));
+               draw_width = min ((double) image_to_draw->image->get_width(), (draw_end - draw_start));
 
 
-               DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 draw just %2 of %3 (iwidth %4 off %5 img @ %6 rs @ %7)\n", name, draw_width, (draw_end - draw_start),
+               DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 draw just %2 of %3 @ %8 (iwidth %4 off %5 img @ %6 rs @ %7)\n", name, draw_width, (draw_end - draw_start),
                                                              image_to_draw->image->get_width(), image_origin_in_self_coordinates,
-                                                             image_to_draw->start, _region_start));
+                                                             image_to_draw->start, _region_start, draw_start));
        } else {
                draw_width = draw_end - draw_start;
                DEBUG_TRACE (DEBUG::WaveView, string_compose ("use current image, span entire render width %1..%2\n", draw_start, draw_end));
@@ -1217,7 +1259,7 @@ WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) cons
         * will appear. So specifying (10,10) will put the upper left corner of
         * the image at (10,10) in user space.
         */
-       
+
        context->set_source (image_to_draw->image, x, y);
        context->fill ();
 
@@ -1249,7 +1291,7 @@ WaveView::set_height (Distance height)
                invalidate_image_cache ();
                _height = height;
                get_image_in_thread = true;
-               
+
                _bounding_box_dirty = true;
                end_change ();
        }
@@ -1351,6 +1393,9 @@ WaveView::set_global_shape (Shape s)
 {
        if (_global_shape != s) {
                _global_shape = s;
+               if (images) {
+                       images->clear_cache ();
+               }
                VisualPropertiesChanged (); /* EMIT SIGNAL */
        }
 }
@@ -1360,6 +1405,9 @@ WaveView::set_global_logscaled (bool yn)
 {
        if (_global_logscaled != yn) {
                _global_logscaled = yn;
+               if (images) {
+                       images->clear_cache ();
+               }
                VisualPropertiesChanged (); /* EMIT SIGNAL */
        }
 }
@@ -1449,20 +1497,20 @@ WaveView::cancel_my_render_request () const
        /* try to stop any current rendering of the request, or prevent it from
         * ever starting up.
         */
-       
+
+       Glib::Threads::Mutex::Lock lm (request_queue_lock);
+
        if (current_request) {
                current_request->cancel ();
        }
-       
-       Glib::Threads::Mutex::Lock lm (request_queue_lock);
 
        /* now remove it from the queue and reset our request pointer so that
           have no outstanding request (that we know about)
        */
-       
+
        request_queue.erase (this);
        current_request.reset ();
-        DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 now has no request %2\n", this));
+       DEBUG_TRACE (DEBUG::WaveView, string_compose ("%1 now has no request %2\n", this));
 
 }
 
@@ -1489,7 +1537,7 @@ WaveView::start_drawing_thread ()
 void
 WaveView::stop_drawing_thread ()
 {
-       if (_drawing_thread) {
+       while (_drawing_thread) {
                Glib::Threads::Mutex::Lock lm (request_queue_lock);
                g_atomic_int_set (&drawing_thread_should_quit, 1);
                request_cond.signal ();
@@ -1508,7 +1556,7 @@ WaveView::drawing_thread ()
        while (run) {
 
                /* remember that we hold the lock at this point, no matter what */
-               
+
                if (g_atomic_int_get (&drawing_thread_should_quit)) {
                        break;
                }
@@ -1517,14 +1565,18 @@ WaveView::drawing_thread ()
                        request_cond.wait (request_queue_lock);
                }
 
+               if (request_queue.empty()) {
+                       continue;
+               }
+
                /* remove the request from the queue (remember: the "request"
                 * is just a pointer to a WaveView object)
                 */
-               
+
                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()));
+               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;
 
@@ -1537,7 +1589,7 @@ WaveView::drawing_thread ()
                 * as we do rendering.
                 */
 
-               request_queue_lock.unlock (); /* some RAII would be good here */
+               lm.release (); /* some RAII would be good here */
 
                try {
                        requestor->generate_image (req, true);
@@ -1545,7 +1597,7 @@ WaveView::drawing_thread ()
                        req->image.clear(); /* just in case it was set before the exception, whatever it was */
                }
 
-               request_queue_lock.lock ();
+               lm.acquire ();
 
                req.reset (); /* drop/delete request as appropriate */
        }
@@ -1578,7 +1630,7 @@ WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
                              bool& full_coverage)
 {
        ImageCache::iterator x;
-       
+
        if ((x = cache_map.find (src)) == cache_map.end ()) {
                /* nothing in the cache for this audio source at all */
                return boost::shared_ptr<WaveViewCache::Entry> ();
@@ -1587,14 +1639,14 @@ WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
        CacheLine& caches = x->second;
        boost::shared_ptr<Entry> best_partial;
        framecnt_t max_coverage = 0;
-       
+
        /* Find a suitable ImageSurface, if it exists.
        */
 
        for (CacheLine::iterator c = caches.begin(); c != caches.end(); ++c) {
 
                boost::shared_ptr<Entry> e (*c);
-               
+
                if (channel != e->channel
                    || height != e->height
                    || amplitude != e->amplitude
@@ -1603,25 +1655,25 @@ WaveViewCache::lookup_image (boost::shared_ptr<ARDOUR::AudioSource> src,
                        continue;
                }
 
-                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;
-
-                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;
+               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;
+
+                       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;
                }
        }
 
@@ -1649,7 +1701,7 @@ WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> s
        ImageCache::iterator x;
 
        /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
-       
+
        if ((x = cache_map.find (src)) == cache_map.end ()) {
                return;
        }
@@ -1662,7 +1714,7 @@ WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> s
                ++nxt;
 
                boost::shared_ptr<Entry> e1 (*c1);
-               
+
                if (channel != e1->channel
                    || height != e1->height
                    || amplitude != e1->amplitude
@@ -1672,12 +1724,12 @@ WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> s
                        /* doesn't match current properties, ignore and move on
                         * to the next one.
                         */
-                       
+
                        other_entries++;
                        c1 = nxt;
                        continue;
                }
-               
+
                /* c1 now points to a cached image entry that matches current
                 * properties. Check all subsequent cached imaged entries to
                 * see if there are others that also match but represent
@@ -1690,7 +1742,7 @@ WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> s
                        ++nxt2;
 
                        boost::shared_ptr<Entry> e2 (*c2);
-                       
+
                        if (e1 == e2 || channel != e2->channel
                            || height != e2->height
                            || amplitude != e2->amplitude
@@ -1703,7 +1755,7 @@ WaveViewCache::consolidate_image_cache (boost::shared_ptr<ARDOUR::AudioSource> s
                                c2 = nxt2;
                                continue;
                        }
-                       
+
                        if (e2->start >= e1->start && e2->end <= e1->end) {
                                /* c2 is fully contained by c1, so delete it */
                                caches.erase (c2);
@@ -1730,7 +1782,7 @@ void
 WaveViewCache::add (boost::shared_ptr<ARDOUR::AudioSource> src, boost::shared_ptr<Entry> ce)
 {
        /* MUST BE CALLED FROM (SINGLE) GUI THREAD */
-       
+
        Cairo::RefPtr<Cairo::ImageSurface> img (ce->image);
 
        image_cache_size += img->get_height() * img->get_width () * 4; /* 4 = bytes per FORMAT_ARGB32 pixel */
@@ -1768,7 +1820,7 @@ void
 WaveViewCache::cache_flush ()
 {
        /* Build a sortable list of all cache entries */
-       
+
        CacheList cache_list;
 
        for (ImageCache::const_iterator cm = cache_map.begin(); cm != cache_map.end(); ++cm) {
@@ -1776,7 +1828,7 @@ WaveViewCache::cache_flush ()
                        cache_list.push_back (make_pair (cm->first, *cl));
                }
        }
-       
+
        /* sort list in LRU order */
        SortByTimestamp sorter;
        sort (cache_list.begin(), cache_list.end(), sorter);
@@ -1786,32 +1838,32 @@ WaveViewCache::cache_flush ()
                ListEntry& le (cache_list.front());
 
                ImageCache::iterator x;
-               
+
                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) {
 
                                        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;
                                }
                        }
-                       
+
                        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 {
@@ -1819,7 +1871,7 @@ WaveViewCache::cache_flush ()
                        }
                        DEBUG_TRACE (DEBUG::WaveView, string_compose ("cache shrunk to %1\n", image_cache_size));
                }
-      
+
                /* Remove from the linear list, even if we didn't find it in
                 * the actual cache_mao
                 */
@@ -1827,10 +1879,20 @@ WaveViewCache::cache_flush ()
        }
 }
 
+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 \n", sz));
+       DEBUG_TRACE (DEBUG::WaveView, string_compose ("new image cache size %1\n", sz));
        _image_cache_threshold = sz;
        cache_flush ();
 }