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