-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWaveformRendering.cpp
More file actions
929 lines (730 loc) · 30.8 KB
/
Copy pathWaveformRendering.cpp
File metadata and controls
929 lines (730 loc) · 30.8 KB
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
#include "WaveformRendering.h"
// WaveformRendering implementation
WaveformRendering::WaveformRendering(BigBuffer &bigBufferArg)
: bigBuffer(bigBufferArg),
collapseButton("Collapse Button", juce::DrawableButton::ImageOnButtonBackground),
settingsButton("Settings Button", juce::DrawableButton::ImageOnButtonBackground),
deleteButton("Delete Button", juce::DrawableButton::ImageOnButtonBackground),
pauseButton("Pause Button", juce::DrawableButton::ImageOnButtonBackground),
mouseListenerWrapper(*this),
selectionDescriptionTimer([this] { timerSelectionDescriptionCallback(); })
{
settingsPanel = std::make_unique<SettingsPanel>(*this);
openGLContext.setOpenGLVersionRequired(juce::OpenGLContext::OpenGLVersion::openGL4_1);
random.setSeedRandomly();
addAndMakeVisible(collapseButton);
addAndMakeVisible(settingsButton);
addAndMakeVisible(deleteButton);
addAndMakeVisible(pauseButton);
menu = juce::PopupMenu();
menu.addItem(1, "Clear Selected Area");
saveToDiskButton.setButtonText("Save to Disk");
saveToDiskButton.setVisible(false);
saveToDiskButton.setColour(juce::TextButton::buttonColourId, juce::Colours::black);
saveToDiskButton.setColour(juce::TextButton::textColourOnId, juce::Colours::white);
addAndMakeVisible(saveToDiskButton);
saveToDiskButton.setLookAndFeel(&snagLAF);
menu.setLookAndFeel(&snagLAF);
collapseButton.setLookAndFeel(&snagLAF);
settingsButton.setLookAndFeel(&snagLAF);
deleteButton.setLookAndFeel(&snagLAF);
pauseButton.setLookAndFeel(&snagLAF);
processSelector.setLookAndFeel(&snagLAF);
collapseButton.setLookAndFeel(&snagLAF);
settingsButton.setLookAndFeel(&snagLAF);
deleteButton.setLookAndFeel(&snagLAF);
pauseButton.setLookAndFeel(&snagLAF);
selectionDescription.setInterceptsMouseClicks(false, false);
selectionDescription.setColour(juce::Label::textColourId, juce::Colours::white);
selectionDescription.setJustificationType(juce::Justification::right);
selectionDescription.setFont(snagLAF.dmSansFont->withHeight(20.0f));
addAndMakeVisible(selectionDescription);
setSelectionDescription(false, 0, "Discord", 44100, "mp3");
addAndMakeVisible(settingsPanel.get());
settingsPanel->setVisible(false);
addAndMakeVisible(processSelector);
processSelector.onChange = [this]() {
auto selectedProcess = processSelector.getSelectedId();
if (selectedProcess == this->getActiveProcess().processID) {
return;
}
std::cout << "Selected process: " << selectedProcess << std::endl;
if (selectedProcess == 0)
return;
auto processStruct = this->getProcessFromID(selectedProcess);
this->setActiveProcess(processStruct);
};
processSelector.addMouseListener(&mouseListenerWrapper, true);
// collapseButton.addMouseListener(&mouseListenerWrapper, true);
// settingsButton.addMouseListener(&mouseListenerWrapper, true);
// deleteButton.addMouseListener(&mouseListenerWrapper, true);
// pauseButton.addMouseListener(&mouseListenerWrapper, true);
settingsButton.onClick = [this]() {
this->setSettingsVisible(true);
};
pauseButton.onClick = [this]() {
this->bigBuffer.setPaused(!this->bigBuffer.getPaused());
};
deleteButton.onClick = [this]() {
this->deleteButtonClicked();
};
collapseButton.onClick = [this]() {
collapseBottomBar(!this->bottomBarCollapsed);
};
waveformData.clear();
minMaxData.clear();
waveformData.reserve(texWidth * texHeight * nImgChannels);
minMaxData.reserve(texWidth * texHeight * nImgChannels);
minMaxLargeData.reserve(texWidth * texHeight * nImgChannels);
for (int i = 0; i < texWidth * texHeight * nImgChannels; i++) {
waveformData.push_back(0.0f);
minMaxData.push_back(0.0f);
minMaxLargeData.push_back(0.0f);
}
zoomStartIdx = 0.0f;
zoomEndIdx = bigBuffer.bufferSize;
textureIDs = new GLuint[3];
openGLContext.setSwapInterval(1);
// so that i can draw on top of this
openGLContext.setComponentPaintingEnabled(true);
#if MACOSX
audioCapture.registerAudioBufferCallback(sckAudioCallback);
#endif
#if WIN32
audioCapture.registerAudioBufferCallback(sckAudioCallbackInterleaved);
#endif
collapseButton.setImages(rightChevronIcon.get());
settingsButton.setImages(settingsIcon.get());
deleteButton.setImages(trashIcon.get());
pauseButton.setImages(pauseIcon.get());
appState = ServiceLocator::getService<AppState>();
}
WaveformRendering::~WaveformRendering()
{
shutdownOpenGL();
saveToDiskButton.setLookAndFeel(nullptr);
menu.setLookAndFeel(nullptr);
collapseButton.setLookAndFeel(nullptr);
settingsButton.setLookAndFeel(nullptr);
deleteButton.setLookAndFeel(nullptr);
pauseButton.setLookAndFeel(nullptr);
processSelector.setLookAndFeel(nullptr);
collapseButton.setLookAndFeel(nullptr);
settingsButton.setLookAndFeel(nullptr);
deleteButton.setLookAndFeel(nullptr);
pauseButton.setLookAndFeel(nullptr);
}
void WaveformRendering::setSettingsVisible(bool visible)
{
settingsPanel->setVisible(visible);
if (visible) {
settingsPanel->toFront(true); // Bring to front when visible
}
collapseButton.setVisible(!visible);
settingsButton.setVisible(!visible);
processSelector.setVisible(!visible);
deleteButton.setVisible(!visible);
pauseButton.setVisible(!visible);
}
AppStruct WaveformRendering::getProcessFromID(int processID)
{
for (int i = 0; i < validApps.size(); i++) {
if (validApps[i].processID == processID) {
return validApps[i];
}
}
AppStruct app;
app.processID = -1;
app.applicationName = "All Processes";
app.bundleIdentifier = "allProcesses";
return app;
}
AppStruct WaveformRendering::getActiveProcess()
{
return currentActiveProcess;
}
void WaveformRendering::updateValidWindows()
{
const juce::MessageManagerLock mmLock;
validApps = audioCapture.getValidWindows();
// Sort processes by application name (except keep "All Processes" at the top)
if (validApps.size() > 1) {
// Extract "All Processes" entry
AppStruct allProcesses = validApps[0];
// Sort the rest of the processes by name
std::sort(validApps.begin() + 1, validApps.end(),
[](const AppStruct& a, const AppStruct& b) {
if (a.processID == -1) return false; // "All Processes" should be at the top
if (b.processID == -1) return true; // "All Processes" should be at the top
return std::string(a.applicationName) < std::string(b.applicationName);
});
// Make sure "All Processes" is at the beginning
if (validApps[0].processID != -1) {
validApps.insert(validApps.begin(), allProcesses);
}
}
processSelector.clear();
for (int i = 0; i < validApps.size(); i++) {
auto window = validApps[i];
auto appName = juce::String(window.applicationName);
if (window.processID != -1) {
appName += " (" + juce::String(window.processID) + ")";
}
if (window.applicationName.length() > 0) {
processSelector.addItem(appName, window.processID);
}
}
}
void WaveformRendering::deleteButtonClicked()
{
bigBuffer.resetToZeros();
bigBuffer.mainWriteIndex = 0;
currentlySelected = false;
zoomStartIdx = 0.0f;
zoomEndIdx = bigBuffer.bufferSize;
selectionStartIdx = 0.0f;
selectionEndIdx = 0.0f;
}
void WaveformRendering::sckAudioCallback(const float* leftChannel, const float* rightChannel, int numSamples, double sampleRate)
{
for (int i = 0; i < numSamples; i += 1) {
float left = leftChannel[i];
float right = rightChannel[i];
queueL.try_enqueue(left);
queueR.try_enqueue(right);
}
if (lastObservedSampleRate != sampleRate) {
lastObservedSampleRate = sampleRate;
}
// bigBuffer.pushBlock(leftChannel, rightChannel, numSamples);
}
void WaveformRendering::sckAudioCallbackInterleaved(const float* interleaved, const float* _, int numSamples, double sampleRate)
{
for (int i = 0; i < numSamples; i += 2) {
float left = interleaved[i];
float right = interleaved[i + 1];
queueL.try_enqueue(left);
queueR.try_enqueue(right);
}
if (lastObservedSampleRate != sampleRate) {
lastObservedSampleRate = sampleRate;
}
// bigBuffer.pushBlock(leftChannel, rightChannel, numSamples);
}
void WaveformRendering::mouseWheelMove(const MouseEvent & event, const MouseWheelDetails & wheel)
{
if (event.mods.isCtrlDown()) {
verticalZoom += wheel.deltaY;
verticalZoom = jlimit(0.1f, 10.0f, verticalZoom);
}
else {
auto x = event.x;
auto horizontalScroll = (wheel.deltaX) * (zoomEndIdx - zoomStartIdx) * 0.2;
float proportion = ((float)x / (float)getWidth());
auto delta = wheel.deltaY * (zoomEndIdx - zoomStartIdx) * 0.4;
zoomStartIdx += delta * proportion;
zoomEndIdx -= delta * (1.0f - proportion);
zoomStartIdx -= horizontalScroll;
zoomEndIdx -= horizontalScroll;
zoomStartIdx = jlimit(0.0f, (float)bigBuffer.bufferSize - getWidth() * 16 - 1, zoomStartIdx );
zoomEndIdx = jlimit(zoomStartIdx + getWidth() * 16 + 1, (float)bigBuffer.bufferSize, zoomEndIdx);
}
}
void WaveformRendering::exportSelection()
{
// Check if there's a valid selection
int bufferSize = (int)jmax(selectionEndIdx - selectionStartIdx, 0.f);
if (bufferSize <= 0) {
return;
}
// Create temporary arrays to hold the selected audio data
float* leftChannel = new float[bufferSize];
float* rightChannel = new float[bufferSize];
// Copy the selected audio data from the big buffer
for (int i = 0; i < bufferSize; i++) {
leftChannel[i] = bigBuffer.mainBufferL[(int)selectionStartIdx + i];
rightChannel[i] = bigBuffer.mainBufferR[(int)selectionStartIdx + i];
}
auto recordingsLocation = appState->getRecordingsLocation();
auto format = appState->getFormat();
Exporter exporter;
// Export the audio using settings from AppState
bool success = exporter.exportBuffer(
leftChannel,
rightChannel,
bufferSize,
lastObservedSampleRate,
currentActiveProcess.applicationName,
static_cast<Exporter::ExportFormat>(format),
recordingsLocation
);
// Clean up the temporary arrays
delete[] leftChannel;
delete[] rightChannel;
}
void WaveformRendering::mouseMove(const MouseEvent & event)
{
float mouseX = (float)event.position.x;
float eventRelX = jmap(mouseX, 0.0f, (float)getWidth(), zoomStartIdx, zoomEndIdx);
// check if we are not at the edges, so we dont drag the edges
// convert from the view space to the screen space
auto selectionStartScreen = jmap(selectionStartIdx, zoomStartIdx, zoomEndIdx, 0.0f, (float)getWidth());
auto selectionEndScreen = jmap(selectionEndIdx, zoomStartIdx, zoomEndIdx, 0.0f, (float)getWidth());
// get the distance to the start and end of the selection
auto startDist = abs(mouseX - selectionStartScreen);
auto endDist = abs(mouseX - selectionEndScreen);
if (startDist < 10.0f && currentlySelected) {
setMouseCursor(juce::MouseCursor::RightEdgeResizeCursor);
} else if (endDist < 10.0f && currentlySelected) {
setMouseCursor(juce::MouseCursor::LeftEdgeResizeCursor);
} else if (eventRelX < selectionEndIdx && eventRelX > selectionStartIdx) {
setMouseCursor(juce::MouseCursor::DraggingHandCursor);
} else {
setMouseCursor(juce::MouseCursor::NormalCursor);
}
}
void WaveformRendering::mouseUp(const MouseEvent & event)
{
if (currentlySelected) {
auto formatString = juce::String(appState->getFormatName(appState->getFormat()));
setSelectionDescription(true, selectionEndIdx - selectionStartIdx, currentActiveProcess.applicationName, lastObservedSampleRate, formatString);
startEdgeSelected = false;
endEdgeSelected = false;
}
if (selectionDescriptionTimer.isTimerRunning()) {
selectionDescriptionTimer.stopTimer();
}
}
void WaveformRendering::mouseDown(const MouseEvent & event)
{
zoomDragStartIndex = zoomStartIdx;
zoomDragEndIndex = zoomEndIdx;
if (event.mods.isPopupMenu()) {
menu.showMenuAsync(juce::PopupMenu::Options(), [this](int result) {
if (result == 1) {
selectionStartIdx = 0.0f;
selectionEndIdx = 0.0f;
currentlySelected = false;
setSelectionDescription(false, 0, "", 44100, "");
}
});
return;
}
// middle mouse button should not do anything, only when dragging
if (event.mods.isMiddleButtonDown()) {
return;
}
float mouseX = (float)event.getMouseDownX();
float eventRelX = jmap(mouseX, 0.0f, (float)getWidth(), zoomStartIdx, zoomEndIdx);
// check if we are not at the edges, so we dont drag the edges
// convert from the view space to the screen space
auto selectionStartScreen = jmap(selectionStartIdx, zoomStartIdx, zoomEndIdx, 0.0f, (float)getWidth());
auto selectionEndScreen = jmap(selectionEndIdx, zoomStartIdx, zoomEndIdx, 0.0f, (float)getWidth());
// get the distance to the start and end of the selection
auto startDist = abs(mouseX - selectionStartScreen);
auto endDist = abs(mouseX - selectionEndScreen);
// check range
if (startDist < 10.0f && currentlySelected) {
startEdgeSelected = true;
selectionStartIdx = eventRelX;
} else if (endDist < 10.0f && currentlySelected) {
endEdgeSelected = true;
selectionEndIdx = eventRelX;
} else if (eventRelX < selectionEndIdx && eventRelX > selectionStartIdx) {
exportSelection();
return;
} else {
selectionStartIdx = 0.0f;
selectionEndIdx = 0.0f;
currentlySelected = false;
setSelectionDescription(false, 0, "", 44100, "");
}
if (!selectionDescriptionTimer.isTimerRunning()) {
selectionDescriptionTimer.startTimerHz(10);
}
}
void WaveformRendering::mouseDrag(const MouseEvent & event)
{
if (event.mods.isCommandDown() || event.mods.isMiddleButtonDown()) {
float delta = ((float)event.getOffsetFromDragStart().x / (float)getWidth()) * (zoomEndIdx - zoomStartIdx);
zoomStartIdx = zoomDragStartIndex - delta;
zoomEndIdx = zoomDragEndIndex - delta;
zoomStartIdx = jlimit(0.0f, (float)bigBuffer.bufferSize, zoomStartIdx);
zoomEndIdx = jlimit(zoomStartIdx, (float)bigBuffer.bufferSize, zoomEndIdx);
} else {
float mouseX = (float)event.getMouseDownX();
float eventRelX = jmap(mouseX, 0.0f, (float)getWidth(), zoomStartIdx, zoomEndIdx);
float offsetX = (float)event.getDistanceFromDragStartX();
if (abs(event.getDistanceFromDragStartX()) > 0) {
currentlySelected = true;
}
// we want to see if we dragged near any of the endpoints of a selection, if not, we want to start a new selection.
// make it so that the width is consistent no matter what zoom level we are at.
// The drag click target will be 10 pixels wide.
float dragOffset = jmap(mouseX + offsetX, 0.0f, (float)getWidth(), zoomStartIdx, zoomEndIdx);
if (selectionStartIdx > selectionEndIdx && (startEdgeSelected || endEdgeSelected)) {
std::swap(selectionStartIdx, selectionEndIdx);
startEdgeSelected = !startEdgeSelected;
endEdgeSelected = !endEdgeSelected;
}
if (startEdgeSelected) {
selectionStartIdx = dragOffset;
} else if (endEdgeSelected) {
selectionEndIdx = dragOffset;
} else if (!startEdgeSelected && !endEdgeSelected) { // using jmin and jmax so we dont have negative width
selectionStartIdx = jmin(eventRelX, dragOffset);
selectionEndIdx = jmax(eventRelX, dragOffset);
}
}
selectionStartIdx = jlimit(0.0f, (float)bigBuffer.bufferSize, selectionStartIdx);
selectionEndIdx = jlimit(0.0f, (float)bigBuffer.bufferSize, selectionEndIdx);
}
void WaveformRendering::mouseMagnify(const MouseEvent & event, float scaleFactor)
{
if (event.mods.isCtrlDown()) {
verticalZoom += scaleFactor;
verticalZoom = jlimit(0.1f, 10.0f, verticalZoom);
}
else {
auto x = event.x;
auto y = event.y;
// the proportion across the x axis which the zoom influences
float proportion = ((float)x / (float)getWidth());
auto delta = (scaleFactor - 1.0f) * (zoomEndIdx - zoomStartIdx);
zoomStartIdx += delta * proportion;
zoomEndIdx -= delta * (1.0f - proportion);
zoomStartIdx = jlimit(0.0f, (float)bigBuffer.bufferSize, zoomStartIdx);
zoomEndIdx = jlimit(zoomStartIdx + getWidth() + 1, (float)bigBuffer.bufferSize, zoomEndIdx);
}
}
void WaveformRendering::initialise()
{
std::cout << juce::gl::glGetString(juce::gl::GL_VERSION) << std::endl;
// Generate 1 buffer, using our vbo variable to store its ID.
openGLContext.extensions.glGenBuffers(1, &vbo);
// Generate 1 more buffer, this time using our IBO variable.
openGLContext.extensions.glGenBuffers(1, &ibo);
// Create four vertices each with a different colour.
vertexBuffer = {
{
{ -1.f, -1.f },
{ 0.f, 0.f }
},
{
{ 1.f, -1.f },
{ 1.f, 0.f }
},
{
{ 1.f, 1.f },
{ 1.f, 1.f }
},
{
{ -1.f, 1.f },
{ 0.f, 1.f }
}
};
// We need 6 indices, 1 for each corner of the two triangles.
indexBuffer = {
0, 1, 2,
2, 3, 0
};
// Bind the VBO.
openGLContext.extensions.glBindBuffer(juce::gl::GL_ARRAY_BUFFER, vbo);
// Send the vertices data.
openGLContext.extensions.glBufferData(
juce::gl::GL_ARRAY_BUFFER, // The type of data we're sending.
sizeof(Vertex) * (long)vertexBuffer.size(), // The size (in bytes) of the data.
vertexBuffer.data(), // A pointer to the actual data.
juce::gl::GL_STATIC_DRAW // How we want the buffer to be drawn.
);
// Bind the IBO.
openGLContext.extensions.glBindBuffer(juce::gl::GL_ELEMENT_ARRAY_BUFFER, ibo);
// Send the indices data.
openGLContext.extensions.glBufferData(
juce::gl::GL_ELEMENT_ARRAY_BUFFER,
sizeof(unsigned int) * (long)indexBuffer.size(),
indexBuffer.data(),
juce::gl::GL_STATIC_DRAW
);
vertexShader =
R"(
#version 410
// Input attributes.
layout (location = 0) in vec4 position;
layout (location = 1) in vec2 textureCoord;
// Output to fragment shader.
out vec2 uv;
void main()
{
// Set the position to the attribute we passed in.
gl_Position = position;
uv = textureCoord;
}
)";
// Load fragment shader from binary resources
fragmentShader = juce::String(BinaryData::fragment_glsl);
// Create an instance of OpenGLShaderProgram
shaderProgram.reset(new OpenGLShaderProgram(openGLContext));
if (shaderProgram->addVertexShader(vertexShader)
&& shaderProgram->addFragmentShader(fragmentShader)
&& shaderProgram->link())
{
shaderProgram->use();
}
else
{
jassertfalse;
}
// prep the texture mwahaha
juce::gl::glGenTextures(3, textureIDs);
// select the first texture which is the waveform buffer
juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 0);
juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[0]);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_MIN_FILTER, juce::gl::GL_LINEAR_MIPMAP_LINEAR);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_MAG_FILTER, juce::gl::GL_LINEAR_MIPMAP_LINEAR);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_WRAP_S, juce::gl::GL_CLAMP_TO_EDGE);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_WRAP_T, juce::gl::GL_CLAMP_TO_EDGE);
juce::gl::glTexImage1D(juce::gl::GL_TEXTURE_1D, 0, juce::gl::GL_RGBA, texWidth, 0, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, waveformData.data());
juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
// select the second texture which is the minMax height buffer
juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 1);
juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[1]);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_MIN_FILTER, juce::gl::GL_LINEAR_MIPMAP_LINEAR);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_MAG_FILTER, juce::gl::GL_LINEAR_MIPMAP_LINEAR);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_WRAP_S, juce::gl::GL_CLAMP_TO_EDGE);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_WRAP_T, juce::gl::GL_CLAMP_TO_EDGE);
juce::gl::glTexImage1D(juce::gl::GL_TEXTURE_1D, 0, juce::gl::GL_RGBA, texWidth, 0, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, minMaxData.data());
juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
// select the third texture which is the minMax Large height buffer
juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 2);
juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[2]);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_MIN_FILTER, juce::gl::GL_LINEAR_MIPMAP_LINEAR);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_MAG_FILTER, juce::gl::GL_LINEAR_MIPMAP_LINEAR);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_WRAP_S, juce::gl::GL_CLAMP_TO_EDGE);
juce::gl::glTexParameteri(juce::gl::GL_TEXTURE_1D, juce::gl::GL_TEXTURE_WRAP_T, juce::gl::GL_CLAMP_TO_EDGE);
juce::gl::glTexImage1D(juce::gl::GL_TEXTURE_1D, 0, juce::gl::GL_RGBA, texWidth, 0, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, minMaxLargeData.data());
juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
auto waveformTexlocation = juce::gl::glGetUniformLocation(shaderProgram->getProgramID(), "waveformTexture");
auto minMaxTexlocation = juce::gl::glGetUniformLocation(shaderProgram->getProgramID(), "minMaxTexture");
auto minMaxLargeTexlocation = juce::gl::glGetUniformLocation(shaderProgram->getProgramID(), "minMaxLargeTexture");
gl::glUseProgram(shaderProgram->getProgramID());
juce::gl::glUniform1i(waveformTexlocation, 0);
juce::gl::glUniform1i(minMaxTexlocation, 1);
juce::gl::glUniform1i(minMaxLargeTexlocation, 2);
// Set up settings panel close callback
settingsPanel->onClose = [this]() {
setSettingsVisible(false);
};
}
void WaveformRendering::shutdown()
{
delete[] textureIDs;
}
void WaveformRendering::render()
{
OpenGLHelpers::clear(Colours::black);
// get stuff from queue and put it into the big buffer
bool valid = true;
// extract all the data from the queue
while (valid) {
float left = 0.0f;
float right = 0.0f;
valid = queueR.try_dequeue(right);
if (!valid) break;
valid = queueL.try_dequeue(left);
if (!valid) break;
bigBuffer.pushBlock(&left, &right, 1);
}
float pixelToSampleRatio = (zoomEndIdx - zoomStartIdx) / getWidth();
float mipLevel = log2(pixelToSampleRatio / (bigBuffer.firstDepthSkipAmt * 0.5f) + 0.01f) * 0.45f;
mipLevel = jlimit(1.0f, 4.0f, mipLevel);
float easing = 0.3f;
float invEasing = 1.0f - easing;
currentZoomStartIdx = currentZoomStartIdx * invEasing + zoomStartIdx * easing;
currentZoomEndIdx = currentZoomEndIdx * invEasing + zoomEndIdx * easing;
int floatsInTexture = texWidth * nImgChannels * texHeight;
float currentWriteIdx = bigBuffer.mainWriteIndex;
for (size_t i = 0; i < (size_t)floatsInTexture; i += 4) {
float newIdx = juce::jmap((float)i, 0.0f, (float)(floatsInTexture), currentZoomStartIdx, currentZoomEndIdx); // original
waveformData[i] = bigBuffer.getFreqData(newIdx, 0);
waveformData[i + 1] = bigBuffer.getFreqData(newIdx, 1);
waveformData[i + 2] = bigBuffer.getFreqData(newIdx, 2);
waveformData[i + 3] = (uint8)((bigBuffer.getRawWaveform(newIdx) * 0.5 + 0.5) * 255);
minMaxData[i] = bigBuffer.getSampleMax(newIdx, 2.f);
minMaxData[i + 1] = bigBuffer.getSampleMin(newIdx, 2.f);
minMaxData[i + 2] = bigBuffer.getSampleMax(newIdx, 1.f);
minMaxData[i + 3] = bigBuffer.getSampleMin(newIdx, 1.f);
minMaxLargeData[i] = bigBuffer.getSampleMax(newIdx, 3.f);
minMaxLargeData[i + 1] = bigBuffer.getSampleMin(newIdx, 3.f);
minMaxLargeData[i + 2] = bigBuffer.getSampleMax(newIdx, 4.f);
minMaxLargeData[i + 3] = bigBuffer.getSampleMin(newIdx, 4.f);
// waveformData[i] = bigBuffer.buffer[newIdx];
}
currentWriteIdx = jmap(currentWriteIdx, currentZoomStartIdx, currentZoomEndIdx, 0.0f, (float)texWidth);
shaderProgram->setUniform("writeHead", currentWriteIdx / (float)texWidth);
shaderProgram->setUniform("mipLevel", mipLevel);
shaderProgram->setUniform("zoomLvl", jlimit(0.0f, 1.0f, pixelToSampleRatio / (bigBuffer.firstDepthSkipAmt * 2)));
shaderProgram->setUniform("selectionStart", jmap(selectionStartIdx, currentZoomStartIdx, currentZoomEndIdx, 0.0f, 1.0f));
shaderProgram->setUniform("selectionEnd", jmap(selectionEndIdx, currentZoomStartIdx, currentZoomEndIdx, 0.0f, 1.0f));
shaderProgram->setUniform("currentlySelected", currentlySelected);
shaderProgram->setUniform("renderWidth", (float)getWidth());
shaderProgram->setUniform("renderHeight", (float)getHeight());
shaderProgram->use();
// update every rerender
// if (!textureIsDirty) {
// juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 0);
// juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[0]);
// juce::gl::glTexSubImage1D(juce::gl::GL_TEXTURE_1D, 0, 0, texWidth, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, waveformData.data());
// juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
// juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 1);
// juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[1]);
// juce::gl::glTexSubImage1D(juce::gl::GL_TEXTURE_1D, 0, 0, texWidth, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, minMaxData.data());
// juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
// } else {
// supposedly using TexImage instead wont cause an unnecessary rerender?
juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 0);
juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[0]);
// supposedly, the _sub_ variant can lead to stalls and forced rerenders. benchmark this!
juce::gl::glTexImage1D(juce::gl::GL_TEXTURE_1D, 0, juce::gl::GL_RGBA, texWidth, 0, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, waveformData.data());
juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 1);
juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[1]);
juce::gl::glTexImage1D(juce::gl::GL_TEXTURE_1D, 0, juce::gl::GL_RGBA, texWidth, 0, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, minMaxData.data());
juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
juce::gl::glActiveTexture(juce::gl::GL_TEXTURE0 + 2);
juce::gl::glBindTexture(juce::gl::GL_TEXTURE_1D, textureIDs[2]);
juce::gl::glTexImage1D(juce::gl::GL_TEXTURE_1D, 0, juce::gl::GL_RGBA, texWidth, 0, juce::gl::GL_RGBA, juce::gl::GL_FLOAT, minMaxLargeData.data());
juce::gl::glGenerateMipmap(juce::gl::GL_TEXTURE_1D);
textureIsDirty = false;
// }
float timeValue = getFrameCounter();
shaderProgram->setUniform("curframe", timeValue);
openGLContext.extensions.glBindBuffer(juce::gl::GL_ARRAY_BUFFER, vbo);
openGLContext.extensions.glBindBuffer(juce::gl::GL_ELEMENT_ARRAY_BUFFER, ibo);
// Enable the position attribute.
openGLContext.extensions.glVertexAttribPointer(
0, // The attribute's index (AKA location).
2, // How many values this attribute contains.
juce::gl::GL_FLOAT, // The attribute's type (float).
juce::gl::GL_FALSE, // Tells OpenGL NOT to normalise the values.
sizeof(Vertex), // How many bytes to move to find the attribute with
// the same index in the next vertex.
nullptr // How many bytes to move from the start of this vertex
// to find this attribute (the default is 0 so we just
// pass nullptr here).
);
openGLContext.extensions.glEnableVertexAttribArray(0);
openGLContext.extensions.glVertexAttribPointer(
1, // This attribute has an index of 1
2, // This time we have 2 value (u, v)
juce::gl::GL_FLOAT,
juce::gl::GL_FALSE,
sizeof(Vertex),
(GLvoid*)(sizeof(float) * 2)
);
openGLContext.extensions.glEnableVertexAttribArray(1);
juce::gl::glDrawElements(
juce::gl::GL_TRIANGLES, // Tell OpenGL to render triangles.
indexBuffer.size(), // How many indices we have.
juce::gl::GL_UNSIGNED_INT, // What type our indices are.
nullptr
);
openGLContext.extensions.glDisableVertexAttribArray(0);
openGLContext.extensions.glDisableVertexAttribArray(1);
}
void WaveformRendering::paint(juce::Graphics &g)
{
// rectangle at centered bottom which is rounded, in same region as the bottom text.
if (currentlySelected) {
auto selectionDescriptionBounds = getLocalBounds();
selectionDescriptionBounds = selectionDescriptionBounds.removeFromTop(35);
// width of text component
auto textWidth = selectionDescription.getFont().getStringWidth(selectionDescription.getText());
// make the rectangle a bit bigger than the text
g.setColour(Colours::black);
g.fillRoundedRectangle(selectionDescriptionBounds.removeFromRight(textWidth + 20).toFloat(), 10.0f);
}
}
void WaveformRendering::resized()
{
// when the texture is resized, mark it as dirty so when we do the render, it calls glTexImage2D and not glTexSubImage2D
settingsPanel->setBounds(getLocalBounds());
texWidth = jmin((int)((float)getWidth() * 2.f), 2048);
textureIsDirty = true;
std::cout << "resized to " << texWidth << std::endl;
auto againBounds = getLocalBounds();
againBounds.reduce(10, 10);
againBounds = againBounds.removeFromBottom(40);
saveToDiskButton.setBounds(againBounds.withRight(140));
collapseButton.setBounds(againBounds.removeFromRight(40));
againBounds.removeFromRight(5);
settingsButton.setBounds(againBounds.removeFromRight(40));
againBounds.removeFromRight(5);
pauseButton.setBounds(againBounds.removeFromRight(40));
againBounds.removeFromRight(5);
deleteButton.setBounds(againBounds.removeFromRight(40));
againBounds.removeFromRight(5);
processSelector.setBounds(againBounds.removeFromRight(180));
auto selectionDescriptionBounds = getLocalBounds();
selectionDescriptionBounds = selectionDescriptionBounds.removeFromTop(40);
selectionDescription.setBounds(selectionDescriptionBounds);
}
void WaveformRendering::prepareToPlay(int numChannels, double sampleRate)
{
this->sampleRate = 48000;
bigBuffer.prepareToPlay(numChannels, 48000);
const juce::MessageManagerLock mmLock;
updateValidWindows();
processSelector.setSelectedId(-1);
}
void WaveformRendering::setActiveProcess(AppStruct process)
{
currentActiveProcess = process;
audioCapture.setActiveProcess(process);
}
void WaveformRendering::collapseBottomBar(bool collapse)
{
bottomBarCollapsed = collapse;
if (collapse) {
collapseButton.setImages(leftChevronIcon.get());
settingsButton.setVisible(false);
deleteButton.setVisible(false);
pauseButton.setVisible(false);
processSelector.setVisible(false);
} else {
collapseButton.setImages(rightChevronIcon.get());
settingsButton.setVisible(true);
deleteButton.setVisible(true);
pauseButton.setVisible(true);
processSelector.setVisible(true);
}
resized();
}
void WaveformRendering::timerSelectionDescriptionCallback()
{
auto formatString = juce::String(appState->getFormatName(appState->getFormat()));
setSelectionDescription(currentlySelected, selectionEndIdx - selectionStartIdx, currentActiveProcess.applicationName, lastObservedSampleRate, formatString);
}
void WaveformRendering::setSelectionDescription(bool isSelected, double timeSamples, juce::String appName, double sr, juce::String format)
{
// convert time from the samples to seconds, but it isnt limited to 60 range
double timeSeconds = timeSamples / sr;
int minutes = (int)timeSeconds / 60;
int seconds = (int)timeSeconds % 60;
int milliseconds = (int)(timeSeconds * 1000) % 1000;
juce::String time = "";
if (timeSeconds < 1) {
time += juce::String(seconds) + "s " + juce::String(milliseconds) + "ms";
} else {
time += juce::String(minutes) + "m " + juce::String(seconds) + "s " + juce::String(milliseconds) + "ms";
}
if (isSelected) {
selectionDescription.setText(time + " - " + juce::String(sr) + " - " + format, juce::dontSendNotification);
selectionDescription.setVisible(true);
saveToDiskButton.setVisible(true);
} else {
selectionDescription.setText("", juce::dontSendNotification);
selectionDescription.setVisible(false);
saveToDiskButton.setVisible(false);
}
}