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