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