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