summaryrefslogtreecommitdiff
path: root/libs/canvas/wave_view.cc
blob: a8e4a3f2861516459308bba9545dc3d17259d1f5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
/*
    Copyright (C) 2011-2013 Paul Davis
    Author: Carl Hetherington <cth@carlh.net>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

*/

#include <cmath>
#include <cairomm/cairomm.h>

#include "gtkmm2ext/utils.h"

#include "pbd/compose.h"
#include "pbd/signals.h"
#include "pbd/stacktrace.h"

#include "ardour/types.h"
#include "ardour/dB.h"
#include "ardour/audioregion.h"

#include "canvas/wave_view.h"
#include "canvas/utils.h"
#include "canvas/canvas.h"
#include "canvas/colors.h"

#include <gdkmm/general.h>

using namespace std;
using namespace ARDOUR;
using namespace ArdourCanvas;

#define CACHE_HIGH_WATER (2)

std::map <boost::shared_ptr<AudioSource>, std::vector<WaveView::CacheEntry> >  WaveView::_image_cache;
double WaveView::_global_gradient_depth = 0.6;
bool WaveView::_global_logscaled = false;
WaveView::Shape WaveView::_global_shape = WaveView::Normal;
bool WaveView::_global_show_waveform_clipping = true;
double WaveView::_clip_level = 0.98853;

PBD::Signal0<void> WaveView::VisualPropertiesChanged;
PBD::Signal0<void> WaveView::ClipLevelChanged;

WaveView::WaveView (Canvas* c, boost::shared_ptr<ARDOUR::AudioRegion> region)
	: Item (c)
	, _region (region)
	, _channel (0)
	, _samples_per_pixel (0)
	, _height (64)
	, _show_zero (false)
	, _zero_color (0xff0000ff)
	, _clip_color (0xff0000ff)
	, _logscaled (_global_logscaled)
	, _shape (_global_shape)
	, _gradient_depth (_global_gradient_depth)
	, _shape_independent (false)
	, _logscaled_independent (false)
	, _gradient_depth_independent (false)
	, _amplitude_above_axis (1.0)
	, _region_amplitude (_region->scale_amplitude ())
	, _region_start (region->start())
{
	VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
	ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
}

WaveView::WaveView (Item* parent, boost::shared_ptr<ARDOUR::AudioRegion> region)
	: Item (parent)
	, _region (region)
	, _channel (0)
	, _samples_per_pixel (0)
	, _height (64)
	, _show_zero (false)
	, _zero_color (0xff0000ff)
	, _clip_color (0xff0000ff)
	, _logscaled (_global_logscaled)
	, _shape (_global_shape)
	, _gradient_depth (_global_gradient_depth)
	, _shape_independent (false)
	, _logscaled_independent (false)
	, _gradient_depth_independent (false)
	, _amplitude_above_axis (1.0)
	, _region_amplitude (_region->scale_amplitude ())
	, _region_start (region->start())
{
	VisualPropertiesChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_visual_property_change, this));
	ClipLevelChanged.connect_same_thread (invalidation_connection, boost::bind (&WaveView::handle_clip_level_change, this));
}

WaveView::~WaveView ()
{
	invalidate_image_cache ();
}

void
WaveView::handle_visual_property_change ()
{
	bool changed = false;

	if (!_shape_independent && (_shape != global_shape())) {
		_shape = global_shape();
		changed = true;
	}

	if (!_logscaled_independent && (_logscaled != global_logscaled())) {
		_logscaled = global_logscaled();
		changed = true;
	}

	if (!_gradient_depth_independent && (_gradient_depth != global_gradient_depth())) {
		_gradient_depth = global_gradient_depth();
		changed = true;
	}

	if (changed) {
		begin_visual_change ();
		invalidate_image_cache ();
		end_visual_change ();
	}
}

void
WaveView::handle_clip_level_change ()
{
	begin_visual_change ();
	invalidate_image_cache ();
	end_visual_change ();
}

void
WaveView::set_fill_color (Color c)
{
	if (c != _fill_color) {
		begin_visual_change ();
		invalidate_image_cache ();
		Fill::set_fill_color (c);
		end_visual_change ();
	}
}

void
WaveView::set_outline_color (Color c)
{
	if (c != _outline_color) {
		begin_visual_change ();
		invalidate_image_cache ();
		Outline::set_outline_color (c);
		end_visual_change ();
	}
}

void
WaveView::set_samples_per_pixel (double samples_per_pixel)
{
	if (samples_per_pixel != _samples_per_pixel) {
		begin_change ();

		invalidate_image_cache ();
		_samples_per_pixel = samples_per_pixel;
		_bounding_box_dirty = true;

		end_change ();
	}
}

static inline double
image_to_window (double wave_origin, double image_start)
{
	return wave_origin + image_start;
}

static inline double
window_to_image (double wave_origin, double image_start)
{
	return image_start - wave_origin;
}

static inline float
_log_meter (float power, double lower_db, double upper_db, double non_linearity)
{
	return (power < lower_db ? 0.0 : pow((power-lower_db)/(upper_db-lower_db), non_linearity));
}

static inline float
alt_log_meter (float power)
{
	return _log_meter (power, -192.0, 0.0, 8.0);
}

void
WaveView::set_clip_level (double dB)
{
	const double clip_level = dB_to_coefficient (dB);
	if (clip_level != _clip_level) {
		_clip_level = clip_level;
		ClipLevelChanged ();
	}
}

void
WaveView::invalidate_image_cache ()
{
	vector <uint32_t> deletion_list;
	vector <CacheEntry> caches;

	if (_image_cache.find (_region->audio_source ()) != _image_cache.end ()) {
		caches = _image_cache.find (_region->audio_source ())->second;
	} else {
		return;
	}

	for (uint32_t i = 0; i < caches.size (); ++i) {

		if (_channel != caches[i].channel
		    || _height != caches[i].height
		    || _region_amplitude != caches[i].amplitude
		    || _fill_color != caches[i].fill_color) {

			continue;
		}

		deletion_list.push_back (i);

	}

	while (deletion_list.size() > 0) {
		caches[deletion_list.back ()].image.clear ();
		caches.erase (caches.begin() + deletion_list.back());
		deletion_list.pop_back();
	}

	if (caches.size () == 0) {
		_image_cache.erase(_region->audio_source ());
	} else {
		_image_cache[_region->audio_source ()] = caches;
	}

}

void
WaveView::consolidate_image_cache () const
{
	list <uint32_t> deletion_list;
	vector <CacheEntry> caches;
	uint32_t other_entries = 0;

	if (_image_cache.find (_region->audio_source ()) != _image_cache.end ()) {
		caches  = _image_cache.find (_region->audio_source ())->second;
	}

	for (uint32_t i = 0; i < caches.size (); ++i) {

		if (_channel != caches[i].channel
		    || _height != caches[i].height
		    || _region_amplitude != caches[i].amplitude
		    || _fill_color != caches[i].fill_color) {

			other_entries++;
			continue;
		}

		framepos_t segment_start = caches[i].start;
		framepos_t segment_end = caches[i].end;

		for (uint32_t j = i; j < caches.size (); ++j) {

			if (i == j || _channel != caches[j].channel
			    || _height != caches[i].height
			    || _region_amplitude != caches[i].amplitude
			    || _fill_color != caches[i].fill_color) {

				continue;
			}

			if (caches[j].start >= segment_start && caches[j].end <= segment_end) {

				deletion_list.push_back (j);
			}
		}
	}

	deletion_list.sort ();
	deletion_list.unique ();

	while (deletion_list.size() > 0) {
		caches[deletion_list.back ()].image.clear ();
		caches.erase (caches.begin() + deletion_list.back ());
		deletion_list.pop_back();
	}

	/* We don't care if this channel/height/amplitude has anything in the cache - just drop the Last Added entries
	   until we reach a size where there is a maximum of CACHE_HIGH_WATER + other entries.
	*/

	while (caches.size() > CACHE_HIGH_WATER + other_entries) {
		caches.front ().image.clear ();
		caches.erase(caches.begin ());
	}

	if (caches.size () == 0) {
		_image_cache.erase (_region->audio_source ());
	} else {
		_image_cache[_region->audio_source ()] = caches;
	}
}

Coord
WaveView::y_extent (double s, bool /*round_to_lower_edge*/) const
{
	/* it is important that this returns an integral value, so that we
	 * can ensure correct single pixel behaviour.
	 *
	 * we need (_height - max(wave_line_width))
	 * wave_line_width == 1 IFF top==bottom (1 sample per pixel or flat line)
	 * wave_line_width == 2 otherwise
	 * then round away from the zero line, towards peak
	 */
	if (_shape == Rectified) {
		// we only ever have 1 point and align to the bottom (not center)
		return floor ((1.0 - s) * (_height - 2.0));
	} else {
		/* currently canvas rectangle is off-by-one and we
		 * cannot draw a pixel at 0 (-.5 .. +.5) without it being
		 * clipped. A value 1.0 (ideally one point at y=0) ends
		 * up a pixel down. and a value of -1.0 (ideally y = _height-1)
		 * currently is on the bottom separator line :(
		 * So to make the complete waveform appear centered in
		 * a region, we translate by +.5 (instead of -.5)
		 * and waste two pixel of height: -4 (instad of -2)
		 *
		 * This needs fixing in canvas/rectangle the intersect
		 * functions and probably a couple of other places as well...
		 */
		Coord pos;
		if (s < 0) {
			pos = ceil  ((1.0 - s) * .5 * (_height - 4.0));
		} else {
			pos = floor ((1.0 - s) * .5 * (_height - 4.0));
		}
		return min (_height - 4.0, (max (0.0, pos)));
	}
}

struct LineTips {
	double top;
	double bot;
	double spread;
	bool clip_max;
	bool clip_min;

	LineTips() : top (0.0), bot (0.0), clip_max (false), clip_min (false) {}
};

struct ImageSet {
	Cairo::RefPtr<Cairo::ImageSurface> wave;
	Cairo::RefPtr<Cairo::ImageSurface> outline;
	Cairo::RefPtr<Cairo::ImageSurface> clip;
	Cairo::RefPtr<Cairo::ImageSurface> zero;

	ImageSet() :
		wave (0), outline (0), clip (0), zero (0) {}
};

void
WaveView::draw_image (Cairo::RefPtr<Cairo::ImageSurface>& image, PeakData* _peaks, int n_peaks) const
{

	ImageSet images;

	images.wave = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
	images.outline = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
	images.clip = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);
	images.zero = Cairo::ImageSurface::create (Cairo::FORMAT_A8, n_peaks, _height);

	Cairo::RefPtr<Cairo::Context> wave_context = Cairo::Context::create (images.wave);
	Cairo::RefPtr<Cairo::Context> outline_context = Cairo::Context::create (images.outline);
	Cairo::RefPtr<Cairo::Context> clip_context = Cairo::Context::create (images.clip);
	Cairo::RefPtr<Cairo::Context> zero_context = Cairo::Context::create (images.zero);

	boost::scoped_array<LineTips> tips (new LineTips[n_peaks]);

	/* Clip level nominally set to -0.9dBFS to account for inter-sample
	   interpolation possibly clipping (value may be too low).

	   We adjust by the region's own gain (but note: not by any gain
	   automation or its gain envelope) so that clip indicators are closer
	   to providing data about on-disk data. This multiplication is
	   needed because the data we get from AudioRegion::read_peaks()
	   has been scaled by scale_amplitude() already.
	*/

	const double clip_level = _clip_level * _region_amplitude;

	if (_shape == WaveView::Rectified) {

		/* each peak is a line from the bottom of the waveview
		 * to a point determined by max (_peaks[i].max,
		 * _peaks[i].min)
		 */

		if (_logscaled) {
			for (int i = 0; i < n_peaks; ++i) {

				tips[i].bot = height() - 1.0;
				const double p = alt_log_meter (fast_coefficient_to_dB (max (fabs (_peaks[i].max), fabs (_peaks[i].min))));
				tips[i].top = y_extent (p, false);
				tips[i].spread = p * (_height - 1.0);

				if (fabs (_peaks[i].max) >= clip_level) {
					tips[i].clip_max = true;
				}

				if (fabs (_peaks[i].min) >= clip_level) {
					tips[i].clip_max = true;
				}
			}

		} else {for (int i = 0; i < n_peaks; ++i) {

				tips[i].bot = height() - 1.0;
				const double p = max(fabs (_peaks[i].max), fabs (_peaks[i].min));
				tips[i].top = y_extent (p, false);
				tips[i].spread = p * (_height - 2.0);
				if (p >= clip_level) {
					tips[i].clip_max = true;
				}
			}

		}

	} else {

		if (_logscaled) {
			for (int i = 0; i < n_peaks; ++i) {
				double top = _peaks[i].max;
				double bot = _peaks[i].min;

				if (_peaks[i].max > 0 && _peaks[i].min > 0) {
					if (fabs (_peaks[i].max) >= clip_level) {
						tips[i].clip_max = true;
					}
				}
				else if (_peaks[i].max < 0 && _peaks[i].min < 0) {
					if (fabs (_peaks[i].min) >= clip_level) {
						tips[i].clip_min = true;
					}
				} else {
					if (fabs (_peaks[i].max) >= clip_level) {
						tips[i].clip_max = true;
					}
					if (fabs (_peaks[i].min) >= clip_level) {
						tips[i].clip_min = true;
					}
				}

				if (top > 0.0) {
					top = alt_log_meter (fast_coefficient_to_dB (top));
				} else if (top < 0.0) {
					top =-alt_log_meter (fast_coefficient_to_dB (-top));
				} else {
					top = 0.0;
				}

				if (bot > 0.0) {
					bot = alt_log_meter (fast_coefficient_to_dB (bot));
				} else if (bot < 0.0) {
					bot = -alt_log_meter (fast_coefficient_to_dB (-bot));
				} else {
					bot = 0.0;
				}

				tips[i].top = y_extent (top, false);
				tips[i].bot = y_extent (bot, true);
				tips[i].spread = fabs (tips[i].top - tips[i].bot);
			}

		} else {
			for (int i = 0; i < n_peaks; ++i) {
				if (_peaks[i].max > 0 && _peaks[i].min > 0) {
					if (fabs (_peaks[i].max) >= clip_level) {
						tips[i].clip_max = true;
					}
				}
				else if (_peaks[i].max < 0 && _peaks[i].min < 0) {
					if (fabs (_peaks[i].min) >= clip_level) {
						tips[i].clip_min = true;
					}
				} else {
					if (fabs (_peaks[i].max) >= clip_level) {
						tips[i].clip_max = true;
					}
					if (fabs (_peaks[i].min) >= clip_level) {
						tips[i].clip_min = true;
					}
				}

				tips[i].top = y_extent (_peaks[i].max, false);
				tips[i].bot = y_extent (_peaks[i].min, true);
				tips[i].spread = fabs (tips[i].top - tips[i].bot);
			}

		}
	}
	Color alpha_one = rgba_to_color (0, 0, 0, 1.0);

	set_source_rgba (wave_context, alpha_one);
	set_source_rgba (outline_context, alpha_one);
	set_source_rgba (clip_context, alpha_one);
	set_source_rgba (zero_context, alpha_one);

	/* ensure single-pixel lines */

	wave_context->set_line_width (1.0);
	wave_context->translate (0.5, +0.5);

	outline_context->set_line_cap (Cairo::LINE_CAP_ROUND);
	outline_context->set_line_width (1.0);
	outline_context->translate (0.5, +0.5);

	clip_context->set_line_width (1.0);
	clip_context->translate (0.5, +0.5);

	zero_context->set_line_width (1.0);
	zero_context->translate (0.5, +0.5);

	/* the height of the clip-indicator should be at most 7 pixels,
	 * or 5% of the height of the waveview item.
	 */

	const double clip_height = min (7.0, ceil (_height * 0.05));

	/* There are 3 possible components to draw at each x-axis position: the
	   waveform "line", the zero line and an outline/clip indicator.  We
	   have to decide which of the 3 to draw at each position, pixel by
	   pixel. This makes the rendering less efficient but it is the only
	   way I can see to do this correctly.

	   To avoid constant source swapping and stroking, we draw the components separately
	   onto four alpha only image surfaces for use as a mask.

	   With only 1 pixel of spread between the top and bottom of the line,
	   we just draw the upper outline/clip indicator.

	   With 2 pixels of spread, we draw the upper and lower outline clip
	   indicators.

	   With 3 pixels of spread we draw the upper and lower outline/clip
	   indicators and at least 1 pixel of the waveform line.

	   With 5 pixels of spread, we draw all components.

	   We can do rectified as two separate passes because we have a much
	   easier decision regarding whether to draw the waveform line. We
	   always draw the clip/outline indicators.
	*/

	if (_shape == WaveView::Rectified) {

		for (int i = 0; i < n_peaks; ++i) {

			/* waveform line */

			if (tips[i].spread >= 1.0) {
				wave_context->move_to (i, tips[i].top);
				wave_context->line_to (i, tips[i].bot);
			}

			if (_global_show_waveform_clipping && (tips[i].clip_max)) {
				clip_context->move_to (i, tips[i].top);
				/* clip-indicating upper terminal line */
				clip_context->rel_line_to (0, min (clip_height, ceil(tips[i].spread + .5)));
			} else {
				outline_context->move_to (i, tips[i].top);
				/* normal upper terminal dot */
				outline_context->close_path ();
			}
		}

		wave_context->stroke ();
		clip_context->stroke ();
		outline_context->stroke ();

	} else {
		const double height_2 = (_height - 4.0) * .5;

		for (int i = 0; i < n_peaks; ++i) {

			/* waveform line */

			if (tips[i].spread >= 2.0) {
				wave_context->move_to (i, tips[i].top);
				wave_context->line_to (i, tips[i].bot);
			}
			if (i > 0) {
				if (tips[i-1].top + 2 < tips[i].bot) {
					wave_context->move_to (i-1, tips[i-1].top);
					wave_context->line_to (i, tips[i].bot);
				}
				else if (tips[i-1].bot > tips[i].top + 2) {
					wave_context->move_to (i-1, tips[i-1].bot);
					wave_context->line_to (i, tips[i].top);
				}
			}

			/* zero line */

			if (tips[i].spread >= 5.0 && show_zero_line()) {
				zero_context->move_to (i, floor(height_2));
				zero_context->rel_line_to (1.0, 0);
			}

			if (tips[i].spread > 1.0) {
				/* lower outline/clip indicator */
				if (_global_show_waveform_clipping && tips[i].clip_min) {
					clip_context->move_to (i, tips[i].bot);
					/* clip-indicating lower terminal line */
					const double sign = tips[i].bot > height_2 ? -1 : 1;
					clip_context->rel_line_to (0, sign * min (clip_height, ceil (tips[i].spread + .5)));
				} else {
					outline_context->move_to (i, tips[i].bot);
					/* normal lower terminal dot */
					outline_context->close_path ();
				}
			} else {
				if (tips[i].clip_min) {
					// make sure we draw the clip
					tips[i].clip_max = true;
				}
			}

			/* upper outline/clip indicator */
			if (_global_show_waveform_clipping && tips[i].clip_max) {
				clip_context->move_to (i, tips[i].top);
				/* clip-indicating upper terminal line */
				const double sign = tips[i].top > height_2 ? -1 : 1;
				clip_context->rel_line_to (0, sign * min(clip_height, ceil(tips[i].spread + .5)));
			} else {
				outline_context->move_to (i, tips[i].top);
				/* normal upper terminal dot */
				outline_context->close_path ();
			}
		}

		wave_context->stroke ();
		outline_context->stroke ();
		clip_context->stroke ();
		zero_context->stroke ();
	}

	Cairo::RefPtr<Cairo::Context> context = Cairo::Context::create (image);

	/* Here we set a source colour and use the various components as a mask. */

	if (gradient_depth() != 0.0) {

		Cairo::RefPtr<Cairo::LinearGradient> gradient (Cairo::LinearGradient::create (0, 0, 0, _height));

		double stops[3];

		double r, g, b, a;

		if (_shape == Rectified) {
			stops[0] = 0.1;
			stops[1] = 0.3;
			stops[2] = 0.9;
		} else {
			stops[0] = 0.1;
			stops[1] = 0.5;
			stops[2] = 0.9;
		}

		color_to_rgba (_fill_color, r, g, b, a);
		gradient->add_color_stop_rgba (stops[1], r, g, b, a);
		/* generate a new color for the middle of the gradient */
		double h, s, v;
		color_to_hsv (_fill_color, h, s, v);
		/* change v towards white */
		v *= 1.0 - gradient_depth();
		Color center = hsv_to_color (h, s, v, a);
		color_to_rgba (center, r, g, b, a);

		gradient->add_color_stop_rgba (stops[0], r, g, b, a);
		gradient->add_color_stop_rgba (stops[2], r, g, b, a);

		context->set_source (gradient);
	} else {
		set_source_rgba (context, _fill_color);
	}

	context->mask (images.wave, 0, 0);
	context->fill ();

	set_source_rgba (context, _outline_color);
	context->mask (images.outline, 0, 0);
	context->fill ();

	set_source_rgba (context, _clip_color);
	context->mask (images.clip, 0, 0);
	context->fill ();

	set_source_rgba (context, _zero_color);
	context->mask (images.zero, 0, 0);
	context->fill ();

}

void
WaveView::get_image (Cairo::RefPtr<Cairo::ImageSurface>& image, framepos_t start, framepos_t end, double& image_offset) const
{
	vector <CacheEntry> caches;

	if (_image_cache.find (_region->audio_source ()) != _image_cache.end ()) {

		caches = _image_cache.find (_region->audio_source ())->second;
	}

	/* Find a suitable ImageSurface.
	*/
	for (uint32_t i = 0; i < caches.size (); ++i) {

		if (_channel != caches[i].channel
		    || _height != caches[i].height
		    || _region_amplitude != caches[i].amplitude
		    || _fill_color != caches[i].fill_color) {

			continue;
		}

		framepos_t segment_start = caches[i].start;
		framepos_t segment_end = caches[i].end;

		if (end <= segment_end && start >= segment_start) {
			image_offset = (segment_start - _region_start) / _samples_per_pixel;
			image = caches[i].image;

			return;
		}
	}

	consolidate_image_cache ();

	/* sample position is canonical here, and we want to generate
	 * an image that spans about twice the canvas width
	 */

	const framepos_t center = start + ((end - start) / 2);
	const framecnt_t canvas_samples = _canvas->visible_area().width() * _samples_per_pixel; /* one canvas width */

	/* we can request data from anywhere in the Source, between 0 and its length
	 */

	framepos_t sample_start = max ((framepos_t) 0, (center - canvas_samples));
	framepos_t sample_end = min (center + canvas_samples, _region->source_length (0));

	const int n_peaks = llrintf ((sample_end - sample_start)/ (double) _samples_per_pixel);

	boost::scoped_array<ARDOUR::PeakData> peaks (new PeakData[n_peaks]);

	_region->read_peaks (peaks.get(), n_peaks,
			     sample_start, sample_end - sample_start,
			     _channel,
			     _samples_per_pixel);

	image = Cairo::ImageSurface::create (Cairo::FORMAT_ARGB32, n_peaks, _height);

	draw_image (image, peaks.get(), n_peaks);

	_image_cache[_region->audio_source ()].push_back (CacheEntry (_channel, _height, _region_amplitude, _fill_color, sample_start,  sample_end, image));

	image_offset = (sample_start - _region->start()) / _samples_per_pixel;

	//cerr << "_image_cache size is : " << _image_cache.size() << " entries for this audiosource : " << _image_cache.find (_region->audio_source ())->second.size() << endl;

	return;
}

void
WaveView::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
{
	assert (_samples_per_pixel != 0);

	if (!_region) {
		return;
	}

	Rect self = item_to_window (Rect (0.0, 0.0, _region->length() / _samples_per_pixel, _height));
	boost::optional<Rect> d = self.intersection (area);

	if (!d) {
		return;
	}

	Rect draw = d.get();

	/* window coordinates - pixels where x=0 is the left edge of the canvas
	 * window. We round down in case we were asked to
	 * draw "between" pixels at the start and/or end.
	 */

	const double draw_start = floor (draw.x0);
	const double draw_end = floor (draw.x1);

	// cerr << "Need to draw " << draw_start << " .. " << draw_end << endl;

	/* image coordnates: pixels where x=0 is the start of this waveview,
	 * wherever it may be positioned. thus image_start=N means "an image
	 * that beings N pixels after the start of region that this waveview is
	 * representing.
	 */

	const framepos_t image_start = window_to_image (self.x0, draw_start);
	const framepos_t image_end = window_to_image (self.x0, draw_end);

	// cerr << "Image/WV space: " << image_start << " .. " << image_end << endl;

	/* sample coordinates - note, these are not subject to rounding error */
	framepos_t sample_start = _region_start + (image_start * _samples_per_pixel);
	framepos_t sample_end   = _region_start + (image_end * _samples_per_pixel);

	// cerr << "Sample space: " << sample_start << " .. " << sample_end << endl;

	Cairo::RefPtr<Cairo::ImageSurface> image;
	double image_offset = 0;

	get_image (image, sample_start, sample_end, image_offset);

	// cerr << "Offset into image to place at zero: " << image_offset << endl;

	context->rectangle (draw_start, draw.y0, draw_end - draw_start, draw.height());

	/* round image origin position to an exact pixel in device space to
	 * avoid blurring
	 */

	double x  = self.x0 + image_offset;
	double y  = self.y0;
	context->user_to_device (x, y);
	x = round (x);
	y = round (y);
	context->device_to_user (x, y);

	context->set_source (image, x, y);
	context->fill ();

}

void
WaveView::compute_bounding_box () const
{
	if (_region) {
		_bounding_box = Rect (0.0, 0.0, _region->length() / _samples_per_pixel, _height);
	} else {
		_bounding_box = boost::optional<Rect> ();
	}

	_bounding_box_dirty = false;
}

void
WaveView::set_height (Distance height)
{
	if (height != _height) {
		begin_change ();

		invalidate_image_cache ();
		_height = height;

		_bounding_box_dirty = true;
		end_change ();
	}
}

void
WaveView::set_channel (int channel)
{
	if (channel != _channel) {
		begin_change ();

		invalidate_image_cache ();
		_channel = channel;

		_bounding_box_dirty = true;
		end_change ();
	}
}

void
WaveView::set_logscaled (bool yn)
{
	if (_logscaled != yn) {
		begin_visual_change ();
		invalidate_image_cache ();
		_logscaled = yn;
		end_visual_change ();
	}
}

void
WaveView::gain_changed ()
{
	begin_visual_change ();
	invalidate_image_cache ();
	_region_amplitude = _region->scale_amplitude ();
	end_visual_change ();
}

void
WaveView::set_zero_color (Color c)
{
	if (_zero_color != c) {
		begin_visual_change ();
		invalidate_image_cache ();
		_zero_color = c;
		end_visual_change ();
	}
}

void
WaveView::set_clip_color (Color c)
{
	if (_clip_color != c) {
		begin_visual_change ();
		invalidate_image_cache ();
		_clip_color = c;
		end_visual_change ();
	}
}

void
WaveView::set_show_zero_line (bool yn)
{
	if (_show_zero != yn) {
		begin_visual_change ();
		invalidate_image_cache ();
		_show_zero = yn;
		end_visual_change ();
	}
}

void
WaveView::set_shape (Shape s)
{
	if (_shape != s) {
		begin_visual_change ();
		invalidate_image_cache ();
		_shape = s;
		end_visual_change ();
	}
}

void
WaveView::set_amplitude_above_axis (double a)
{
	if (_amplitude_above_axis != a) {
		begin_visual_change ();
		invalidate_image_cache ();
		_amplitude_above_axis = a;
		end_visual_change ();
	}
}

void
WaveView::set_global_shape (Shape s)
{
	if (_global_shape != s) {
		_global_shape = s;
		VisualPropertiesChanged (); /* EMIT SIGNAL */
	}
}

void
WaveView::set_global_logscaled (bool yn)
{
	if (_global_logscaled != yn) {
		_global_logscaled = yn;
		VisualPropertiesChanged (); /* EMIT SIGNAL */
	}
}

void
WaveView::set_region_start (frameoffset_t start)
{
	if (!_region) {
		return;
	}

	if (_region_start == start) {
		return;
	}

	begin_change ();
	_region_start = start;
	_bounding_box_dirty = true;
	end_change ();
}

void
WaveView::region_resized ()
{
	/* Called when the region start or end (thus length) has changed.
	*/

	if (!_region) {
		return;
	}

	begin_change ();
	_region_start = _region->start();
	_bounding_box_dirty = true;
	end_change ();
}

void
WaveView::set_global_gradient_depth (double depth)
{
	if (_global_gradient_depth != depth) {
		_global_gradient_depth = depth;
		VisualPropertiesChanged (); /* EMIT SIGNAL */
	}
}

void
WaveView::set_global_show_waveform_clipping (bool yn)
{
	if (_global_show_waveform_clipping != yn) {
		_global_show_waveform_clipping = yn;
		VisualPropertiesChanged (); /* EMIT SIGNAL */
	}
}