-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeliner_run.cpp
1836 lines (1644 loc) · 53.4 KB
/
timeliner_run.cpp
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
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS // for strcpy, getenv, _snprintf, fopen, fscanf
#endif
#undef DEBUG
#include "timeliner_diagnostics.h"
#include "timeliner_cache.h"
#include "timeliner_util.h" // #includes <windows.h>
#include "timeliner_util_threads.h"
// Linux: apt-get install libsndfile1-dev
// Windows: www.mega-nerd.com/libsndfile/ libsndfile-1.0.25-w64-setup.exe
#include <sndfile.h>
#include <vector>
// Linux: apt-get install libglew-dev
// Windows: http://glew.sourceforge.net/install.html
#include <GL/glew.h> // before gl.h
#include <GL/freeglut.h> // Instead of glut.h, to get glutLeaveMainLoop().
// Linux: apt-get install libpng12-dev
// Windows: http://gnuwin32.sourceforge.net/packages/libpng.htm and http://zlib.net/
#include <png.h>
#include <algorithm>
#include <cerrno>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <fstream>
#ifdef _MSC_VER
#include <time.h>
#include <iostream>
#include <sstream>
#include <functional>
#else
#include <pthread.h>
#include <sys/ioctl.h>
#include <sys/stat.h> // mkdir
#include <sys/time.h>
#include <sys/types.h>
#include <linux/soundcard.h>
#include <unistd.h>
#endif
#if !defined(GLUT_WHEEL_UP)
#define GLUT_WHEEL_UP (3)
#define GLUT_WHEEL_DOWN (4)
#endif
#undef making_movie
#ifdef making_movie
double sMovieRecordingStart = -1.0;
bool fMovieRecording = false;
bool fMoviePlaying = false;
const int izPlaybackMaxMax = 30 * 60; // 30 FPS, max 60 seconds
double rgzPlayback[izPlaybackMaxMax][5];
int izPlaybackMax = 0; // last frame
int izPlayback = 0; // current frame, at 30 FPS
FILE* fpMovie = NULL;
#define yscroll_disable
#endif
void snooze(const double sec)
#ifdef _MSC_VER
{ Sleep(DWORD(sec * 1e3)); }
#else
{ (void)usleep(sec * 1e6); }
#endif
#ifdef _MSC_VER
#include <time.h>
#include <iostream>
// Difference between Unix epoch Jan 1 1970 and Windows epoch Jan 1 1601.
#if defined(_MSC_VER) || defined(_MSC_EXTENSIONS)
#define DELTA_EPOCH_IN_MICROSECS (11644473600000000Ui64)
#else
#define DELTA_EPOCH_IN_MICROSECS (11644473600000000ULL)
#endif
struct timezone
{
int tz_minuteswest; // minutes W of Greenwich
int tz_dsttime; // type of dst correction
};
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
if (NULL != tv)
{
FILETIME ft;
GetSystemTimeAsFileTime(&ft);
const unsigned __int64 usecNow =
(((unsigned __int64)(ft.dwHighDateTime) << 32) | ft.dwLowDateTime) / 10 - DELTA_EPOCH_IN_MICROSECS;
tv->tv_sec = (long)(usecNow / 1000000UL);
tv->tv_usec = (long)(usecNow % 1000000UL);
}
#ifdef unused_by_timeliner
if (NULL != tz)
{
static bool fFirst = true;
if (fFirst)
{
fFirst = false;
_tzset();
}
long tmp;
_get_timezone(&tmp);
tz->tz_minuteswest = tmp / 60;
_get_daylight(&tz->tz_dsttime);
}
#endif
return 0;
}
#endif
// seconds since app started
double appnow()
{
static bool fFirst = true;
static struct timeval t0;
if (fFirst) {
fFirst = false;
if (gettimeofday(&t0, NULL) < 0) {
perror("appnow() first time");
return -1;
}
}
struct timeval t;
if (gettimeofday(&t, NULL) < 0) {
perror("appnow()");
return -1;
}
return (t.tv_sec - t0.tv_sec) + (t.tv_usec - t0.tv_usec) / 1e6;
}
double tFPSPrev = appnow();
double secsPerFrame = 1/60.0;
const double yShowBound[2] = { 0.0, 1.0 };
double yShowPrev[2] = {-2.0, -1.0}; // deliberately bogus
double yZoom = 1.0;
double yShow[2] = {yShowBound[0], yShowBound[1]}; // displayed interval of y, updated each frame
double yAim[2] = {yShow[0], yShow[1]}; // setpoint for yShow, updated more slowly
double tShowBound[2] = {0.0, 90000.0};
double tShowPrev[2] = {-2.0, -1.0}; // deliberately bogus
double tShow[2] = {tShowBound[0], tShowBound[1]}; // displayed interval of time, updated each frame
double tAim[2] = {tShow[0], tShow[1]}; // setpoint for tShow, updated more slowly
inline double dsecondFromGL(const double dx) { return dx * (tShow[1] - tShow[0]); }
inline double secondFromGL(const double x) { return dsecondFromGL(x) + tShow[0]; }
inline double glFromSecond(const double s) { return (s - tShow[0]) / (tShow[1] - tShow[0]); }
// Like dsecondFromGL().
inline double dyFromGL(const double dy) { return dy * (yShow[1] - yShow[0]); }
// Like dyFromGL, but considering pan as well as zoom. yFromGL : dyFromGL :: secondFromGL : dsecondFromGL.
// Inverse of drawAll's scale and translate.
inline double yFromGL(const double y) {
return dyFromGL(y) + yShow[0];
}
// Ignores yTimeline translate-and-scale.
inline double glFromY(const double y) { return (y - yShow[0]) / (yShow[1] - yShow[0]); }
void testConverters()
{
for (double i = -30.0; i < 50.0; ++i) {
assert(abs(i - glFromSecond(secondFromGL(i))) < 1e-10);
assert(abs(i - secondFromGL(glFromSecond(i))) < 1e-10);
assert(abs(i - glFromY(yFromGL(i))) < 1e-10);
assert(abs(i - yFromGL(glFromY(i))) < 1e-10);
}
}
long wavcsamp = -1L; // int wraps around too soon
short* wavS16 = NULL;
bool onscreen(const double sec) { return sec >= tShow[0] && sec <= tShow[1]; }
int SR = -1;
arLock vlockAudio; // guards next three
int vnumSamples = 0; // high-low-water-mark between samplewriter() and samplereader()
const short* vpsSamples = NULL; // vpsSamples and visSamples are set by samplewriter() via emit(), and cleared by samplereader().
int visSamples = 0;
class S2Splay {
public:
S2Splay() : _sPlay(-1.0), _sPlayPrev(-1.0), _tPlay(appnow()), _fPlaying(false), _sampBgn(10000) {}
bool playing() const { arGuard _(_lock); return _fPlaying; }
void soundpause() { arGuard _(_lock); _fPlaying = false; }
// Stuff dst with positions of playback cursors, in seconds or opengl offsets.
bool sPlayCursors(double* dst) const {
arGuard _(_lock);
if (!_fPlaying)
return false;
dst[0] = _sPlay;
dst[1] = sPlayCursor1Nolock();
return true;
}
bool xPlayCursors(double* dst) const {
arGuard _(_lock);
if (!_fPlaying
#ifdef making_movie
&& !fMoviePlaying
#endif
)
return false;
dst[0] = glFromSecond(_sPlay);
dst[1] = glFromSecond(sPlayCursor1Nolock());
// sPlayCursors(), with glFromSecond *inside* the lock.
return true;
}
// Report position of the next numSamples of audio,
// starting implicitly at _sampBgn,
// by setting vpsSamples and visSamples,
// and updating _sampBgn for the next emit().
//
// Called from inside vlockAudio.lock();
void emit(int numSamples /* actually is vnumSamples */) {
assert(vnumSamples > 0); // true but not helpful
arGuard _(_lock);
long sampEnd = _sampBgn + numSamples;
const bool fPastEnd = sampEnd > wavcsamp;
if (fPastEnd) {
// truncate, and cease playing thereafter
sampEnd = wavcsamp;
numSamples = sampEnd - _sampBgn;
}
const short* psStart = wavS16 + _sampBgn;
vpsSamples = psStart;
visSamples += numSamples;
_sampBgn += numSamples;
//not true when hit space to stop playing. assert(_fPlaying);
if (fPastEnd)
_fPlaying = false;
// Stop playing if cursor moves offscreen, or screen moves off cursor.
_fPlaying &= onscreen(sPlayCursor1Nolock());
}
void spacebar(double s) {
bool f;
{
arGuard _(_lock);
f = _fPlaying;
// If s no longer equals _sPlayPrev,
// either user moved purple cursor during playback
// which means he wants to keep listening from the new position;
// or user panned purple cursor left-offscreen
// in which case resuming playback from left edge is a bug,
// to be fixed by defining yet another flag to catch either that case,
// or the user's explicit repositioning of purple cursor (that's better).
if (f && s==_sPlayPrev) {
_fPlaying = false;
#ifdef making_movie
if (fMovieRecording)
fprintf(fpMovie, "# audio playback stop at offset = %f s\n", sPlayCursor1Nolock());
#endif
} else {
_sPlayPrev = s;
soundplayNolock(s);
#ifdef making_movie
if (fMovieRecording)
fprintf(fpMovie, "# audio playback start from wavfile offset = %f s, at screenshot-recording offset = %f s\n", s, appnow() - sMovieRecordingStart);
#endif
}
}
}
#ifdef making_movie
void moviePlayback(const double s, const double t) {
_sPlay = s;
_tPlay = s + appnow() - t; // inverse of sPlayCursor1Nolock()
}
#endif
private:
// Start playing at offset of t seconds,
// primarily by setting _sampBgn so emit() knows where to look for samples.
void soundplayNolock(const double t) {
const long sampBgn = long(double(SR) * t);
if (sampBgn<0 || sampBgn > wavcsamp) {
warn("play out of range");
return;
}
// arGuard _(_lock); *would* go here.
_sampBgn = sampBgn;
_tPlay = appnow();
_sPlay = t;
_fPlaying = true;
//info("playing at #{t}");
}
double sPlayCursor1Nolock() const { return _sPlay + (appnow() - _tPlay); }
mutable arLock _lock; // guards all member variables
double _sPlay;
double _sPlayPrev;
double _tPlay;
bool _fPlaying;
long _sampBgn;
};
S2Splay s2s;
GLuint texNoise;
int pixelSize[2] = {1000,1000};
double dxChar = 0.01;
#define font GLUT_BITMAP_9_BY_15
// As z from 0 to 1, lerp from min to max.
double geometriclerp(double z, double min, double max)
{
if (z<0.0 || min<0.0 || max<0.0)
return -1.0; // handle error arbitrarily
z = sqrt(z );
min = sqrt(min);
max = sqrt(max);
return sq((z-min) / (max-min));
}
// To set color: *before* glRasterPos2d, call glColor (with lighting disabled).
char sprintfbuf[10000];
void putsGlut(const char* pch = sprintfbuf)
{
while (*pch) glutBitmapCharacter(font, *pch++);
}
void prepTexture(const GLuint t)
{
glBindTexture(GL_TEXTURE_2D, t);
assert(glIsTexture(t) == GL_TRUE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
#ifdef _MSC_VER
inline float drand48() { return float(rand()) / float(RAND_MAX); }
#endif
WorkerPool* pool = NULL;
int Feature::mb = mbUnknown;
std::vector<Feature*> features;
std::vector<GLuint> myPrgs;
bool fShaderValid(const int i)
{
return 0<=i && i<int(myPrgs.size()) && myPrgs[i]!=0;
}
void shaderUse(const int i = -1)
{
glUseProgram(fShaderValid(i) ? myPrgs[i] : 0);
}
GLfloat paletteBrightness = 1.0;
void setPalette(const int iShader, const GLfloat r, const GLfloat g, const GLfloat b) {
static GLfloat bufPalette[3*128]; // One bufPalette is enough for multiple shaders.
for (int i=0; i<128; ++i) {
const GLfloat z(paletteBrightness * sq(i/127.0f));
switch (iShader) {
default:
bufPalette[3*i+0] = z * r;
bufPalette[3*i+1] = z * g;
bufPalette[3*i+2] = z * b;
break;
case 0:
// waveform
bufPalette[3*i+0] = i<127 ? 0.0f : r;
bufPalette[3*i+1] = i<127 ? 0.0f : g;
bufPalette[3*i+2] = i<127 ? 0.0f : b;
break;
case 1:
// blackbody: black red yellow white.
double hsv[3] = { cb(z) * 0.27, 1.0 - fi(z), z };
extern void RgbFromHsv(double*);
RgbFromHsv(hsv);
bufPalette[3*i+0] = GLfloat(hsv[0]);
bufPalette[3*i+1] = GLfloat(hsv[1]);
bufPalette[3*i+2] = GLfloat(hsv[2]);
break;
}
}
assert(fShaderValid(iShader));
assert( glGetUniformLocation(myPrgs[iShader], "palette") >= 0);
glUniform1fv(glGetUniformLocation(myPrgs[iShader], "palette"), 3*128, bufPalette);
}
void shaderRestart(const int iShader, const double r, const double g, const double b) {
// Recompiling the shaders may be overkill for just redoing setPalette().
shaderUse();
if (fShaderValid(iShader))
glDeleteProgram(myPrgs[iShader]);
if (int(myPrgs.size()) < iShader+1) myPrgs.resize(iShader+1, -1);
myPrgs[iShader] = glCreateProgram();
const GLuint& myPrg = myPrgs[iShader];
assert(myPrg > 0);
const GLuint myVS = glCreateShader(GL_VERTEX_SHADER);
const GLuint myFS = glCreateShader(GL_FRAGMENT_SHADER);
// For GLSL 1.30+, should pedantically define my own AttrMultiTexCoord0 instead of deprecated gl_MultiTexCoord0.
const GLchar* prgV = "varying float u; void main() { gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; u = gl_MultiTexCoord0.s; }";
const GLchar* prgF = "varying float u; uniform sampler1D heatmap; uniform float palette[3*128]; \n void main() {\n\
float i = texture1D(heatmap, u).r; // 0 to 1\n\
int j = int(i*127.0) * 3; // 0 to 127*3, by 3's\n\
// gl_FragColor = vec4(i,1.0-i,1.0-i,1.0);\n\
gl_FragColor = vec4(palette[j],palette[j+1],palette[j+2],1.0);\n\
}";
glShaderSource(myVS, 1, &prgV, NULL);
glShaderSource(myFS, 1, &prgF, NULL);
int ret = 0;
//int cch=0, cch2=0; char sz[10000] = "";
glCompileShader(myVS); glGetShaderiv(myVS, GL_COMPILE_STATUS, &ret); assert(ret != GL_FALSE);
//glGetShaderiv(myFS, GL_INFO_LOG_LENGTH, &cch);
//glGetShaderInfoLog(myFS, cch, &cch2, sz);
//if (cch2>0) printf("vert compile: %s\n", sz);
glCompileShader(myFS); glGetShaderiv(myFS, GL_COMPILE_STATUS, &ret); assert(ret != GL_FALSE);
//cch = cch2 = 0;
//glGetShaderiv(myFS, GL_INFO_LOG_LENGTH, &cch);
//glGetShaderInfoLog(myFS, cch, &cch2, sz);
//if (cch2>0) printf("frag compile: %s\n", sz);
glAttachShader(myPrg, myVS);
glAttachShader(myPrg, myFS);
glLinkProgram(myPrg); glGetProgramiv(myPrg, GL_LINK_STATUS, &ret); assert(ret != GL_FALSE);
//cch = cch2 = 0;
//glGetProgramiv(myPrg, GL_INFO_LOG_LENGTH, &cch);
//glGetProgramInfoLog(myPrg, cch, &cch2, sz);
//if (cch2>0) printf("shader link: %d, %s\n", r, sz);
// 128 works, but 256 fails to glLinkProgram (and segfaults in glGetProgramInfoLog).
// 3000-ish bytes may be the maximum for a uniform array.
//
// Alternatives: UBO; texelFetch() a buffer texture (TBO), SSBO.
// http://stackoverflow.com/questions/7954927/glsl-passing-a-list-of-values-to-fragment-shader
// http://rastergrid.com/blog/2010/01/uniform-buffers-vs-texture-buffers/
shaderUse(iShader); // before calling any glUniform()s, so they know which program to refer to.
setPalette(iShader, GLfloat(r),GLfloat(g),GLfloat(b));
glActiveTexture(GL_TEXTURE0); // use texture unit 0
assert( glGetUniformLocation(myPrg, "heatmap") >= 0);
glUniform1i(glGetUniformLocation(myPrg, "heatmap"), 0); // Bind sampler to texture unit 0. www.opengl.org/wiki/Texture#Texture_image_units
}
void kickShaders()
{
shaderRestart(0, 0.2, 1.0, 0.2); // waveform is green
for (unsigned i=1; i<features.size(); ++i)
shaderRestart(i, 0.9-0.2*i, 0.7, 0.4+0.1*i);
}
void shaderInit()
{
glewInit();
assert(glewIsSupported("GL_VERSION_2_0"));
kickShaders();
}
// Top of timeline, measured from bottom of window (y==0) to top of window (y==1).
// todo: in resize(), keep this a constant # of pixels, e.g. yTimeline = 20 / pixelSize[1];
const double yTimeline = 0.03;
#undef WAVEDRAW
#ifdef WAVEDRAW
// Measured from top of timeline (y==0) to top of window (y==1).
// Within the transformation that uses yTimeline.
// (Could adapt to # of channels and # of features? Or will interleaving replace this?)
const double yBetweenWaveformAndFeatures = 0.2;
#else
const double yBetweenWaveformAndFeatures = 0.0;
#endif
void drawFeatures()
{
if (features.empty())
return;
std::vector<Feature*>::const_iterator f;
// Compute y's: amortize among vectorsizes. Sqrt gives "thin" features more space.
double rgdy[100]; //hardcoded;; instead, grow a vector.
assert(features.size() < 100);
int i=0;
double sum = 0.0;
for (f=features.begin(); f!=features.end(); ++f) {
// Waveform-features have vectorsize = 50, so hope for about 50 vertical pixels.
// todo: adapt to pixelSize[1]
const double dy = !strcmp((*f)->name(), "waveform-as-feature") ? 1.5 : sqrt(double((*f)->vectorsize()));
sum += rgdy[i++] = dy;
assert(i < 100); //hardcoded;;
}
// rgdy[0 .. i-1] are heights.
double rgy[100]; //hardcoded;;
rgy[0] = yBetweenWaveformAndFeatures;
rgy[i] = 1.0;
{
const double rescale = sum / (rgy[i] - rgy[0]);
for (int j=1; j<i; ++j)
rgy[j] = rgy[j-1] + rgdy[j-1] / rescale;
// rgy [0 .. i] are boundaries between features.
}
for (f=features.begin(),i=0; f!=features.end(); ++f,++i) {
shaderUse(i);
const double* p = rgy + i;
glDisable(GL_TEXTURE_2D);
glEnable(GL_TEXTURE_1D);
glColor4d(0.9,1.0,0.4, 1.0);
const int jMax = (*f)->vectorsize();
for (int ichunk=0; ichunk < (*f)->cchunk; ++ichunk) {
for (int j=0; j<jMax; ++j) {
const double chunkL = ichunk / double((*f)->cchunk); // e.g., 5/8
const double chunkR = (ichunk+1) / double((*f)->cchunk); // e.g., 6/8
const double tBoundL = lerp(chunkL, tShowBound[0], tShowBound[1]);
const double tBoundR = lerp(chunkR, tShowBound[0], tShowBound[1]);
const double xL = (tBoundL - tShow[0]) / (tShow[1] - tShow[0]);
const double xR = (tBoundR - tShow[0]) / (tShow[1] - tShow[0]);
if (xR < 0.0 || 1.0 < xL)
continue; // offscreen
assert(glIsTexture((*f)->rgTex[ichunk].tex[j]) == GL_TRUE);
glBindTexture(GL_TEXTURE_1D, (*f)->rgTex[ichunk].tex[j]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
const double yMin = lerp(double(j )/jMax, p[0], p[1]);
const double yMax = lerp(double(j+1)/jMax, p[0], p[1]);
assert(p[0]<=yMin && yMin<yMax && yMax<=p[1]);
glBegin(GL_QUADS);
glTexCoord1d(0.0); glVertex2d(xL, yMin); glVertex2d(xL, yMax);
glTexCoord1d(1.0); glVertex2d(xR, yMax); glVertex2d(xR, yMin);
glEnd();
}
}
glDisable(GL_TEXTURE_1D);
glColor4f(1,1,0,1);
glRasterPos2d(0.01, p[0] + 0.005);
putsGlut((*f)->name());
}
}
unsigned int channels = 0; // == wavedrawers.size()
#ifdef WAVEDRAW
// Convert 0..32768 to what drawWaveformScaled() will scale the waveform by. (bug: for actual pixels, consider yTimeline too? *=(1-yTimeline) ?)
double scaleWavFromSampmax(const double s)
{
assert(0.0 <= s && s <= 32768.0);
const double sMin = 25.0; // Threshold == 10 * log10(sMin^2 / 32768^2) == about -62 dB
return 0.99 / std::max(s, sMin);
}
const double scaleWavDefault = scaleWavFromSampmax(32768.0);
class WaveDraw {
public:
double scaleWav;
double scaleWavAim;
const CHello* cacheWav;
WaveDraw(const CHello* p) : scaleWav(scaleWavDefault), scaleWavAim(scaleWavDefault), cacheWav(p)
{ if (!p) quit("failed to cache wav"); }
void update()
{
// Asymmetric. Grow slowly, shrink quickly.
// Slowly, but not so slow that it distracts while nothing else changes.
// Aim should complete within about 0.15 seconds.
//
// Copypaste.
double lowpass = 0.0345 * exp(67.0 * secsPerFrame) * (scaleWavAim > scaleWav ? 5.0 : 20.0);
// Disable aim/show at slow frame rates, to avoid flicker.
if (secsPerFrame > 1.0/30.0)
lowpass = 1.0;
if (lowpass > 1.0)
lowpass = 1.0;
const double lowpass1 = 1.0 - lowpass;
scaleWav = scaleWav*lowpass1 + scaleWavAim*lowpass;
}
};
std::vector<WaveDraw> wavedrawers;
void drawWaveformScaled(const float* minmaxes, const double yScale) {
// As yScale from default 331000. to zoomedin 5000.0,
// color from brightgreen 0.1,1.0,0.2 to cyan 0.0,0.25,0.3,
// roughly constant #pixels times brightness.
double ramp = yScale==scaleWavDefault ? 1.0 :
(0.85/yScale - 5000.0) / (33100.0 - 5000.0) / 11.0; // 1.0 downto 0.009
ramp = std::max(ramp, 0.44); // Not too dark.
glColor4d(lerp(ramp,0.07,0.1), geometriclerp(ramp,0.15,1.0), lerp(ramp,0.06,0.15), 1.0);
glPushMatrix();
glScaled(1.0/pixelSize[0], yScale, 1.0);
glBegin(GL_LINES);
for (int x = 0; x < pixelSize[0]; ++x) {
glVertex2f(GLfloat(x), minmaxes[x*2]);
glVertex2f(GLfloat(x), minmaxes[x*2+1]);
}
glEnd();
glPopMatrix();
}
void drawWaveform()
{
shaderUse();
// 0 < x < 1
// y above timeline, and rescale audio values from +-32768.
// Adaptively scale (vertically zoom).
// Convert x-pixel extent to [t,t+dt] from [t-dt/2, t+dt/2]. Edge-centered not body-centered, sort of.
const double hack = (tShow[1] - tShow[0])*0.5 * (pixelSize[0] / (pixelSize[0]-1));
const double YWavMax = features.empty() ? 1.0 : yBetweenWaveformAndFeatures;
const double heightPerChannel = (YWavMax)/channels;
const double yTweak = (YWavMax/2) /channels;
assert(channels == wavedrawers.size());
unsigned i=0;
for (std::vector<WaveDraw>::iterator it = wavedrawers.begin(); it != wavedrawers.end(); ++it,++i) {
float dst[2];
it->cacheWav->getbatch(dst, tShow[0]+hack, tShow[1]+hack, 1, 1.0/(scaleWavDefault * pixelSize[1]));
float& xmin = dst[0];
float& xmax = dst[1];
it->scaleWavAim = scaleWavFromSampmax(std::max(abs(xmin), abs(xmax)));
glPushMatrix();
// The Y-extent of a monophonic waveform is 0 .. yBetweenWaveformAndFeatures.
// 0..1 height is then yBetweenWaveformAndFeatures/2.
// 0..1 height is then YWavMax/2.
// Draw channels from top to bottom.
const double centerOfChannel = heightPerChannel*0.5 + (channels-1-i)*heightPerChannel;
glTranslated(0.0, centerOfChannel, 0.0);
glScaled(1.0, yTweak, 1.0);
// Scaled waveform is dark echo behind bright unscaled one.
// getbatch()'s last arg avoids vanishingly short vertical lines, which would render as a missing horizontal line.
float minmaxes[9000*2]; // 9000 hardcoded
assert(9000 > pixelSize[0]);
it->cacheWav->getbatch(minmaxes, tShow[0], tShow[1], pixelSize[0], 0.5/(it->scaleWav * pixelSize[1])/yTweak);
// When zoomed in so only a thin dark line is barely visible, make this an area by extending each minmax to zero.
// For example, [.2,.3] becomes [0,.3]; [-.8,-.4] becomes [-.8,0]; [-.1,.1] is unchanged.
// (Even prettier would be to extend only to the scaleWavDefault curve, instead of all the way to the x-axis.)
for (int x = 0; x < pixelSize[0]; ++x) {
float& yMin = minmaxes[x*2];
float& yMax = minmaxes[x*2+1];
if (yMin > 0.0) yMin = 0.0;
if (yMax < 0.0) yMax = 0.0;
}
drawWaveformScaled(minmaxes, it->scaleWav);
// Bug in cache? When multichannel and only partially zoomed in (>1 value per x-pixel), lines are sometimes dotted.
// But increasing 0.5 makes the lines so fat that they're ugly.
it->cacheWav->getbatch(minmaxes, tShow[0], tShow[1], pixelSize[0], 0.5/(scaleWavDefault * pixelSize[1])/yTweak/yZoom);
drawWaveformScaled(minmaxes, scaleWavDefault);
glPopMatrix();
}
}
#endif
double sMouseRuler = 0.0;
void drawMouseRuler()
{
shaderUse();
const double xL = glFromSecond(sMouseRuler);
const double xR = xL + 0.06;
if (xR < 0.0 || xL > 1.0)
return; // offscreen
// (Abandoned purple horizontal fade to right of sharp line,
// because multichannel might interleave waveforms and heatmap features.)
// Sharp onset, drawn after polygons so it's over them.
glColor3f(1,0,1); // purple
glBegin(GL_LINE_STRIP);
glVertex2d(xL, 0.0);
glVertex2d(xL, 1.0);
glEnd();
}
class Flash {
public:
Flash(double fadeFrames=20.0):
_fadeStep(1.0/fadeFrames), _t(-1.0) {
memset(_color, 0, sizeof(_color));
memset(_colorFaded, 0, sizeof(_colorFaded));
};
void blink(const double t, const float r, const float g, const float b) {
_t = t;
_color[0] = _colorFaded[0] = r;
_color[1] = _colorFaded[1] = g;
_color[2] = _colorFaded[2] = b;
_colorFaded[3] = 0.0;
_color[3] = 1.0;
};
void draw() {
shaderUse();
if (_color[3] <= 0.0)
return; // faded away
_color[3] -= float(_fadeStep); // fade
const double x = glFromSecond(_t);
const double xL = x - 0.08;
const double xR = x + 0.08;
if (xR < -0.01 || xL > 1.01)
return; // cull offscreen
glBegin(GL_QUAD_STRIP);
glColor4fv(_colorFaded);
glVertex2d(xL, 0.0);
glVertex2d(xL, 1.0);
glColor4fv(_color);
glVertex2d(x, 0.0);
glVertex2d(x, 1.0);
glColor4fv(_colorFaded);
glVertex2d(xR, 0.0);
glVertex2d(xR, 1.0);
glEnd();
glColor4fv(_color);
glBegin(GL_LINE_STRIP);
glVertex2d(x, 0.0);
glVertex2d(x, 1.0);
glEnd();
};
private:
double _fadeStep;
double _t; // offset in seconds
float _color[4];
float _colorFaded[4];
};
Flash flashLimits[2];
void limitBlink(const int i)
{
assert(i==0 || i==1);
flashLimits[i].blink(tShowBound[i], 1.0f, 0.1f, 0.1f);
}
void zoomBlink(const int i)
{
assert(i==0 || i==1);
flashLimits[i].blink(tShow[i], 0.8f, 0.4f, 0.1f);
}
void aimCrop()
{
if (tAim[0] < tShowBound[0]) {
tAim[0] = tShowBound[0];
limitBlink(0);
}
if (tAim[1] > tShowBound[1]) {
tAim[1] = tShowBound[1];
limitBlink(1);
}
}
void aimCropY()
{
if (yAim[0] < yShowBound[0]) {
yAim[0] = yShowBound[0];
//printf("limitBlinkY(0);\n");;;;
}
if (yAim[1] > yShowBound[1]) {
yAim[1] = yShowBound[1];
//printf("limitBlinkY(1);\n");;;;
}
}
bool fHeld = false; // Left mouse button is held down.
bool fHeldRight = false; // Right mouse button is held down.
bool fDrag = false; // Mouse was left-dragged, not merely left-clicked.
double xyMouse[2] = {0.5, 0.15}; // Mouse position in GL coords.
double xMouseAim = 0.0, yMouseAim = 0.0;// Mouse position in world coords. Setpoint for xyMouse.
bool fReshaped = false;
// Update tShow and yShow from tAim and yAim, from xyMouse.
void aim()
{
if (!fReshaped)
return; // pixelSize[] not yet defined
double lowpass = 0.0345 * exp(67.0 * secsPerFrame);
// Disable aim/show at slow frame rates, to avoid flicker.
if (secsPerFrame > 1.0/30.0)
lowpass = 1.0;
if (lowpass > 1.0)
lowpass = 1.0;
const double lowpass1 = 1.0 - lowpass;
xyMouse[0] = xyMouse[0]*lowpass1 + xMouseAim*lowpass;
xyMouse[1] = xyMouse[1]*lowpass1 + yMouseAim*lowpass;
// Update tShow and tShowPrev from tAim.
assert(tShowBound[0] < tShowBound[1]);
assert(tAim[0] < tAim[1]);
// If tAim is disjoint with tShowBound (!!), pan it back into range.
if (tAim[0] >= tShowBound[1]) {
tAim[0] -= tAim[1] - tShowBound[1];
tAim[1] = tShowBound[1];
limitBlink(1);
}
else if (tAim[1] <= tShowBound[0]) {
tAim[1] += tShowBound[0] - tAim[0];
tAim[0] = tShowBound[0];
limitBlink(0);
}
assert(tAim[0] < tShowBound[1]);
assert(tAim[1] > tShowBound[0]);
aimCrop();
// Clamp zoomin, tweaked for 5 msec undersampling.
// (This may interact with the constraint on tShowBound,
// but any oscillation should converge.)
const double samplesPerPixelMin = 1.0;// For EEG, 1.0. For audio, 100.0 * (0.005 * SR) * 3.
const double dtZoomMin = samplesPerPixelMin * pixelSize[0] / SR;
const bool fZoominLimit = tAim[1] - tAim[0] < dtZoomMin;
if (fZoominLimit) {
const double tFixed = (tAim[0] + tAim[1]) / 2.0;
tAim[0] = tFixed - dtZoomMin * 0.50001;
tAim[1] = tFixed + dtZoomMin * 0.50001;
}
aimCrop();
for (int i=0; i<2; ++i) {
tShow[i] = tShow[i]*lowpass1 + tAim[i]*lowpass;
if (fZoominLimit)
zoomBlink(i);
}
tShowPrev[0] = tShow[0];
tShowPrev[1] = tShow[1];
// Update yShow and yShowPrev from yAim.
assert(yShowBound[0] < yShowBound[1]);
assert(yAim[0] < yAim[1]);
// If yAim is disjoint with yShowBound (!!), pan it back into range.
if (yAim[0] >= yShowBound[1]) {
yAim[0] -= yAim[1] - yShowBound[1];
yAim[1] = yShowBound[1];
}
else if (yAim[1] <= yShowBound[0]) {
yAim[1] += yShowBound[0] - yAim[0];
yAim[0] = yShowBound[0];
}
assert(yAim[0] < yShowBound[1]);
assert(yAim[1] > yShowBound[0]);
aimCropY();
const double dyZoomMin = 1.0 / channels;
const bool fZoominLimitY = yAim[1] - yAim[0] < dyZoomMin;
if (fZoominLimitY) {
// printf("Hit fZoominLimitY %.2f.\n", dyZoomMin); // aimCropY will also warn.
const double yFixed = (yAim[0] + yAim[1]) / 2.0;
yAim[0] = yFixed - dyZoomMin * 0.50001;
yAim[1] = yFixed + dyZoomMin * 0.50001;
}
aimCropY();
assert(yShowBound[0] <= yAim[0]); assert(yAim[1] <= yShowBound[1]);
assert(yShowBound[0] <= yShow[0]); assert(yShow[1] <= yShowBound[1]);
for (int i=0; i<2; ++i) {
yShow[i] = yShow[i]*lowpass1 + yAim[i]*lowpass;
/*if (fZoominLimitY)
zoomBlinkY(i);*/
}
//printf("\t\t\t\t\tyShow %.2f .. %.2f\n", yShow[0], yShow[1]);;;;
assert(yShowBound[0] - 1e-5 <= yShow[0]); assert(yShow[1] <= yShowBound[1] + 1e-5);
yShowPrev[0] = yShow[0];
yShowPrev[1] = yShow[1];
#ifdef WAVEDRAW
// todo: in Windows, try PPL's parallel_for_each. Good for an EEG's 90+ WaveDraw's.
std::for_each(wavedrawers.begin(), wavedrawers.end(), std::mem_fun_ref(&WaveDraw::update));
#endif
}
#if 0
void debugYCoords()
{
for (double y = -1.0; y < 2.0; y += 0.01) {
glRasterPos2d(0.5, y);
char sz[80];
sprintf(sz, "%.2f", y);
putsGlut(sz);
}
}
#endif
void scrollwheelY(double y, const bool fIn)
{
#ifndef yscroll_disable
// Undo yTimeline transformation: map 0..1 to yTimeline..1.
y = (y - yTimeline) / (1.0-yTimeline);
const double yFixed = yFromGL(y);
assert(yShow[0] <= yFixed);
assert(yFixed <= yShow[1]);
//printf("scrollY at %.3f, yFixed %.3f\n", y, yFixed);;;;
const double zoom = fIn ? 1.0/1.08 : 1.08; // Smaller than for x aka t, because range is also smaller.
yAim[0] = yFixed + (yAim[0]-yFixed) * zoom;
yAim[1] = yFixed + (yAim[1]-yFixed) * zoom;
#endif
}
// later, increase step for successive steps in same direction, resetting this after 0.5 seconds elapse.
void scrollwheel(const double x, const bool fIn, const bool fFast)
{
const double tFixed = secondFromGL(x);
double zoom = fFast ? 1.14 : 1.19; // fFast is actually reversed. hold key down, vs mouse wheel.
if (fIn)
zoom = 1.0 / zoom;
tAim[0] = tFixed + (tAim[0]-tFixed) * zoom;
tAim[1] = tFixed + (tAim[1]-tFixed) * zoom;
}
int qsortCompare(const void* a, const void* b)
{
const double _ = ((const double*)a)[2] - ((const double*)b)[2];
return _<0.0 ? 1 : _>0.0 ? -1 : 0;
}
void drawTimeline()
{
const int iMax = 61;
static bool fFirst = true;
static double pow2[iMax];
int i;
if (fFirst) {
for (i=0; i<iMax; ++i) pow2[i] = pow(2.0, i-iMax/2);
}
const double spanMin = 1e-5; // long streaks, low frequency, zoomed in
const double spanMax = 1.0; // grainy, high frequency, zoomed out
double uua[iMax][3]; // Each entry is [u,u,alpha]. u's are uv texture coords.
int iMic = iMax+1;
int iMac = -1;
for (i=0; i<iMax; ++i) {
double* p = uua[i];
p[0] = tShow[0] * pow2[i]; // left end
p[1] = tShow[1] * pow2[i]; // right end
const double span = p[1] - p[0];
// Ignore entries whose span is out of range.
if (span>=spanMin && span<=spanMax) {
if (i<iMic) iMic=i;
if (i>iMac) iMac=i;
#ifndef M_PI
#define M_PI (3.1415926535)
#endif
p[2] = cos(geometriclerp(span, spanMin, spanMax) *2.0*M_PI ) /-2.0 +0.5; // opacity
}
}
const int diFew = 4;
if (iMic+diFew > iMac)
return; // Should never happen.
// Sort by decreasing opacity.
qsort(uua + iMic, iMac-iMic, 3*sizeof(double), qsortCompare);
// Keep the first few (the most opaque).
memmove(uua, uua+iMic, diFew*3*sizeof(double));
// Normalize sum of opacities.
double opacity = 0.0;
for (i=0; i<diFew; ++i) opacity += uua[i][2];
for (i=0; i<diFew; ++i) uua[i][2] /= opacity;
// Avoid roundoff error when used as uv coords.
for (i=0; i<diFew; ++i) {
if (uua[i][0] < 1.0)
continue;
const double f = floor(uua[i][0]);
uua[i][0] -= f;
uua[i][1] -= f;
}
// Draw.
shaderUse();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texNoise);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glPushMatrix();
glBegin(GL_QUADS);
for (i=0; i<diFew; ++i) {
const double* p = uua[i];
// todo: brighter (more contrast) when rest of screen has less contrast.
glColor4d(0.05,0.4,0.4, p[2]);
glTexCoord2d(p[0], 0.0); glVertex2f(0.0, 0.0);
glTexCoord2d(p[0], 1.0); glVertex2f(0.0, 1.0);
glTexCoord2d(p[1], 1.0); glVertex2f(1.0, 1.0);
glTexCoord2d(p[1], 0.0); glVertex2f(1.0, 0.0);