Debian Codegraph @

src/gui/chanOsc.cpp

raw
1 /**
2 * Furnace Tracker - multi-system chiptune tracker
3 * Copyright (C) 2021-2025 tildearrow and contributors
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #define _USE_MATH_DEFINES
21 #include "gui.h"
22 #include "../ta-log.h"
23 #include "imgui.h"
24 #include "imgui_internal.h"
25 #include "misc/cpp/imgui_stdlib.h"
26
27 #define FURNACE_FFT_SIZE 4096
28 #define FURNACE_FFT_RATE 80.0
29 #define FURNACE_FFT_CUTOFF 0.1
30
31 const char* chanOscRefs[]={
32 _N("None (0%)"),
33 _N("None (50%)"),
34 _N("None (100%)"),
35
36 _N("Frequency"),
37 _N("Volume"),
38 _N("Channel"),
39 _N("Brightness"),
40
41 _N("Note Trigger")
42 };
43
44 const char* autoColsTypes[]={
45 _N("Off"),
46 _N("Mode 1"),
47 _N("Mode 2"),
48 _N("Mode 3")
49 };
50
51 static void _drawOsc(const ImDrawList* drawList, const ImDrawCmd* cmd) {
52 if (cmd!=NULL) {
53 if (cmd->UserCallbackData!=NULL) {
54 ((FurnaceGUI*)(((PendingDrawOsc*)cmd->UserCallbackData)->gui))->runPendingDrawOsc((PendingDrawOsc*)cmd->UserCallbackData);
55 }
56 }
57 }
58
59 float FurnaceGUI::computeGradPos(int type, int chan) {
60 switch (type) {
61 case GUI_OSCREF_NONE:
62 return 0.0f;
63 break;
64 case GUI_OSCREF_CENTER:
65 return 0.5f;
66 break;
67 case GUI_OSCREF_MAX:
68 return 1.0f;
69 break;
70 case GUI_OSCREF_FREQUENCY:
71 return chanOscChan[chan].pitch;
72 break;
73 case GUI_OSCREF_VOLUME:
74 return chanOscVol[chan];
75 break;
76 case GUI_OSCREF_CHANNEL:
77 return (float)chan/(float)(e->getTotalChannelCount()-1);
78 break;
79 case GUI_OSCREF_BRIGHT:
80 return chanOscBright[chan];
81 break;
82 case GUI_OSCREF_NOTE_TRIGGER:
83 return keyHit1[chan];
84 break;
85 }
86 return 0.0f;
87 }
88
89 void FurnaceGUI::calcChanOsc() {
90 std::vector<DivDispatchOscBuffer*> oscBufs;
91 std::vector<ChanOscStatus*> oscFFTs;
92 std::vector<int> oscChans;
93
94 int chans=e->getTotalChannelCount();
95
96 for (int i=0; i<chans; i++) {
97 int tryAgain=i;
98 DivDispatchOscBuffer* buf=e->getOscBuffer(i);
99 while (buf==NULL) {
100 if (--tryAgain<0) break;
101 buf=e->getOscBuffer(tryAgain);
102 }
103 if (buf!=NULL && e->curSubSong->chanShowChanOsc[i]) {
104 // 30ms should be enough
105 int displaySize=65536.0f*0.03f;
106 if (e->isRunning()) {
107 short minLevel=32767;
108 short maxLevel=-32768;
109 unsigned short needlePos=buf->needle>>16;
110 for (unsigned short i=needlePos-displaySize; i!=needlePos; i++) {
111 short y=buf->data[i];
112 if (y==-1) continue;
113 if (minLevel>y) minLevel=y;
114 if (maxLevel<y) maxLevel=y;
115 }
116 float estimate=pow((float)(maxLevel-minLevel)/32768.0f,0.5f);
117 if (estimate>1.0f) estimate=1.0f;
118 chanOscVol[i]=MAX(chanOscVol[i]*0.87f,estimate);
119 }
120 } else {
121 chanOscVol[i]=MAX(chanOscVol[i]*0.87f,0.0f);
122 }
123 if (chanOscVol[i]<0.00001f) chanOscVol[i]=0.0f;
124 }
125 }
126
127 void FurnaceGUI::drawChanOsc() {
128 if (nextWindow==GUI_WINDOW_CHAN_OSC) {
129 chanOscOpen=true;
130 ImGui::SetNextWindowFocus();
131 nextWindow=GUI_WINDOW_NOTHING;
132 }
133 if (!chanOscOpen) return;
134 ImGui::SetNextWindowSizeConstraints(ImVec2(64.0f*dpiScale,32.0f*dpiScale),ImVec2(canvasW,canvasH));
135 if (ImGui::Begin("Oscilloscope (per-channel)",&chanOscOpen,globalWinFlags,_("Oscilloscope (per-channel)"))) {
136 bool centerSettingReset=false;
137 ImDrawList* dl=ImGui::GetWindowDrawList();
138 if (chanOscOptions) {
139 if (ImGui::BeginTable("ChanOscSettings",2)) {
140 ImGui::TableNextRow();
141 ImGui::TableNextColumn();
142 ImGui::AlignTextToFramePadding();
143 ImGui::Text(_("Columns"));
144 ImGui::SameLine();
145 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
146 if (ImGui::InputInt("##COSColumns",&chanOscCols,1,3)) {
147 if (chanOscCols<1) chanOscCols=1;
148 if (chanOscCols>64) chanOscCols=64;
149 }
150
151 ImGui::TableNextColumn();
152 ImGui::Text(_("Size (ms)"));
153 ImGui::SameLine();
154 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
155 if (ImGui::InputFloat("##COSWinSize",&chanOscWindowSize,1.0f,10.0f)) {
156 if (chanOscWindowSize<1.0f) chanOscWindowSize=1.0f;
157 if (chanOscWindowSize>50.0f) chanOscWindowSize=50.0f;
158 }
159
160 ImGui::TableNextRow();
161 ImGui::TableNextColumn();
162 ImGui::AlignTextToFramePadding();
163 ImGui::Text(_("Automatic columns"));
164 ImGui::SameLine();
165 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
166 const char* previewColType=autoColsTypes[chanOscAutoColsType&3];
167 if (ImGui::BeginCombo("##AutoCols",previewColType)) {
168 for (int j=0; j<4; j++) {
169 const bool isSelected=(chanOscAutoColsType==j);
170 if (ImGui::Selectable(autoColsTypes[j],isSelected)) chanOscAutoColsType=j;
171 if (isSelected) ImGui::SetItemDefaultFocus();
172 }
173 ImGui::EndCombo();
174 }
175
176 ImGui::TableNextColumn();
177 if (ImGui::Checkbox(_("Center waveform"),&chanOscWaveCorr)) {
178 centerSettingReset=true;
179 }
180
181 ImGui::TableNextRow();
182 ImGui::TableNextColumn();
183 if (ImGui::Checkbox(_("Randomize phase on note"),&chanOscRandomPhase)) {
184 }
185
186 ImGui::TableNextColumn();
187 ImGui::Text("DC offset correction");
188 ImGui::SameLine();
189 if (ImGui::RadioButton("Off###_cocs0",chanOscCenterStrat==0)) {
190 chanOscCenterStrat=0;
191 }
192 ImGui::SameLine();
193 if (ImGui::RadioButton("Normal###_cocs1",chanOscCenterStrat==1)) {
194 chanOscCenterStrat=1;
195 }
196 ImGui::SameLine();
197 if (ImGui::RadioButton("High-pass###_cocs2",chanOscCenterStrat==2)) {
198 chanOscCenterStrat=2;
199 }
200
201 ImGui::TableNextRow();
202 ImGui::TableNextColumn();
203 ImGui::AlignTextToFramePadding();
204 ImGui::Text(_("Amplitude"));
205 ImGui::SameLine();
206 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
207 if (CWSliderFloat("##COSAmp",&chanOscAmplify,0.0f,2.0f)) {
208 if (chanOscAmplify<0.0f) chanOscAmplify=0.0f;
209 if (chanOscAmplify>2.0f) chanOscAmplify=2.0f;
210 }
211
212 ImGui::TableNextColumn();
213 ImGui::AlignTextToFramePadding();
214 ImGui::Text(_("Line size"));
215 ImGui::SameLine();
216 ImGui::SetNextItemWidth(ImGui::GetContentRegionAvail().x);
217 if (CWSliderFloat("##COSLine",&chanOscLineSize,0.25f,16.0f)) {
218 if (chanOscLineSize<0.25f) chanOscLineSize=0.26f;
219 if (chanOscLineSize>16.0f) chanOscLineSize=16.0f;
220 }
221
222
223 ImGui::EndTable();
224 }
225
226 ImGui::Checkbox(_("Gradient"),&chanOscUseGrad);
227
228 if (chanOscUseGrad) {
229 if (chanOscGradTex==NULL) {
230 chanOscGradTex=rend->createTexture(true,chanOscGrad.width,chanOscGrad.height,true,bestTexFormat);
231
232 if (chanOscGradTex==NULL) {
233 logE(_("error while creating gradient texture!"));
234 } else {
235 updateChanOscGradTex=true;
236 }
237 }
238
239 if (ImGui::BeginTable("ChanOscGradSet",2)) {
240 ImGui::TableSetupColumn("c0",ImGuiTableColumnFlags_WidthFixed);
241 ImGui::TableSetupColumn("c1",ImGuiTableColumnFlags_WidthStretch);
242
243 ImGui::TableNextRow();
244 ImGui::TableNextColumn();
245 if (chanOscGradTex!=NULL) {
246 if (updateChanOscGradTex) {
247 chanOscGrad.render();
248 if (rend->updateTexture(chanOscGradTex,chanOscGrad.grad.get(),chanOscGrad.width*4)) {
249 updateChanOscGradTex=false;
250 } else {
251 logE(_("error while updating gradient texture!"));
252 }
253 }
254
255 ImVec2 gradLeft=ImGui::GetCursorPos();
256 ImVec2 gradSize=ImVec2(400.0f*dpiScale,400.0f*dpiScale);
257 ImGui::Image(rend->getTextureID(chanOscGradTex),gradSize,ImVec2(0,0),ImVec2(rend->getTextureU(chanOscGradTex),rend->getTextureV(chanOscGradTex)));
258 ImVec2 gradLeftAbs=ImGui::GetItemRectMin();
259 if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) {
260 if (chanOscGrad.points.size()<32) {
261 chanOscGrad.points.push_back(Gradient2DPoint(
262 (ImGui::GetMousePos().x-gradLeftAbs.x)/gradSize.x,
263 (ImGui::GetMousePos().y-gradLeftAbs.y)/gradSize.y
264 ));
265 updateChanOscGradTex=true;
266 }
267 }
268
269 ImVec2 oldCurPos=ImGui::GetCursorPos();
270 int index=0;
271 int removePoint=-1;
272 for (Gradient2DPoint& i: chanOscGrad.points) {
273 ImGui::PushID(index+16);
274 ImGui::SetCursorPos(ImVec2(gradLeft.x+i.x*gradSize.x-8.0*dpiScale,gradLeft.y+i.y*gradSize.y-8.0*dpiScale));
275 if (ImGui::InvisibleButton("gradPoint",ImVec2(16.0*dpiScale,16.0*dpiScale))) {
276 if (!i.grab) {
277 ImGui::OpenPopup("gradPointSettings");
278 }
279 }
280 if (ImGui::IsItemHovered() || ImGui::IsItemActive()) {
281 ImGui::SetTooltip("(%.1f, %.1f)",i.x*100.0f,(1.0f-i.y)*100.0f);
282 }
283 if (ImGui::IsItemClicked(ImGuiMouseButton_Middle)) {
284 removePoint=index;
285 }
286 if (ImGui::IsItemActive()) {
287 float mX=(ImGui::GetMousePos().x-gradLeftAbs.x)/gradSize.x;
288 float mY=(ImGui::GetMousePos().y-gradLeftAbs.y)/gradSize.y;
289
290 if (i.grab || (fabs(i.x-mX)>0.015 || fabs(i.y-mY)>0.015)) {
291 i.x=mX;
292 i.y=mY;
293 i.grab=true;
294
295 if (i.x<0) i.x=0;
296 if (i.x>1) i.x=1;
297 if (i.y<0) i.y=0;
298 if (i.y>1) i.y=1;
299 updateChanOscGradTex=true;
300 }
301 } else {
302 i.grab=false;
303 i.prevX=i.x;
304 i.prevY=i.y;
305 }
306 if (ImGui::BeginPopup("gradPointSettings",ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_AlwaysAutoResize)) {
307 if (ImGui::ColorPicker4(_("Color"),(float*)&i.color)) {
308 updateChanOscGradTex=true;
309 }
310 ImGui::AlignTextToFramePadding();
311 ImGui::Text(_("Distance"));
312 ImGui::SameLine();
313 float pDist=i.distance*100.0f;
314 if (ImGui::SliderFloat("##PDistance",&pDist,0.0f,150.0f,"%.1f%%")) {
315 i.distance=pDist/100.0f;
316 updateChanOscGradTex=true;
317 }
318
319 ImGui::AlignTextToFramePadding();
320 ImGui::Text(_("Spread"));
321 ImGui::SameLine();
322 float pSpread=i.spread*100.0f;
323 if (ImGui::SliderFloat("##PSpread",&pSpread,0.0f,150.0f,"%.1f%%")) {
324 i.spread=pSpread/100.0f;
325 updateChanOscGradTex=true;
326 }
327
328 pushDestColor();
329 if (ImGui::Button(_("Remove"))) {
330 removePoint=index;
331 ImGui::CloseCurrentPopup();
332 }
333 popDestColor();
334
335 ImGui::EndPopup();
336 }
337
338 dl->AddCircle(ImVec2(gradLeftAbs.x+i.x*gradSize.x,gradLeftAbs.y+i.y*gradSize.y),8.0*dpiScale,ImGui::ColorConvertFloat4ToU32(ImVec4(0.5,0.5,0.5,1.0)),6,2.0f*dpiScale);
339 dl->AddCircle(ImVec2(gradLeftAbs.x+i.x*gradSize.x,gradLeftAbs.y+i.y*gradSize.y),5.0*dpiScale,ImGui::ColorConvertFloat4ToU32(ImVec4(0.1,0.1,0.1,1.0)),6,2.0f*dpiScale);
340
341 ImGui::PopID();
342 index++;
343 }
344 ImGui::SetCursorPos(oldCurPos);
345
346 if (removePoint>=0) {
347 chanOscGrad.points.erase(chanOscGrad.points.begin()+removePoint);
348 updateChanOscGradTex=true;
349 }
350 }
351
352 ImGui::TableNextColumn();
353 if (ImGui::ColorEdit4(_("Background"),(float*)&chanOscGrad.bgColor)) {
354 updateChanOscGradTex=true;
355 }
356 ImGui::Combo(_("X Axis##AxisX"),&chanOscColorX,LocalizedComboGetter,chanOscRefs,GUI_OSCREF_MAX);
357 ImGui::Combo(_("Y Axis##AxisY"),&chanOscColorY,LocalizedComboGetter,chanOscRefs,GUI_OSCREF_MAX);
358
359 ImGui::EndTable();
360 }
361 } else {
362 ImGui::SetNextItemWidth(400.0f*dpiScale);
363 ImGui::ColorPicker4(_("Color"),(float*)&chanOscColor);
364 }
365
366 ImGui::AlignTextToFramePadding();
367 ImGui::Text(_("Text format:"));
368 ImGui::SameLine();
369 ImGui::InputText("##TextFormat",&chanOscTextFormat);
370 if (ImGui::IsItemHovered()) {
371 if (ImGui::BeginTooltip()) {
372 ImGui::TextUnformatted(_(
373 "format guide:\n"
374 "- %c: channel name\n"
375 "- %C: channel short name\n"
376 "- %d: channel number (starting from 0)\n"
377 "- %D: channel number (starting from 1)\n"
378 "- %n: channel note\n"
379 "- %i: instrument name\n"
380 "- %I: instrument number (decimal)\n"
381 "- %x: instrument number (hex)\n"
382 "- %s: chip name\n"
383 "- %p: chip part number\n"
384 "- %S: chip ID\n"
385 "- %v: volume (decimal)\n"
386 "- %V: volume (percentage)\n"
387 "- %b: volume (hex)\n"
388 "- %l: new line\n"
389 "- %%: percent sign"
390 ));
391 ImGui::EndTooltip();
392 }
393 }
394
395 ImGui::ColorEdit4(_("Text color"),(float*)&chanOscTextColor);
396
397 if (ImGui::Button(_("OK"))) {
398 chanOscOptions=false;
399 }
400 } else {
401 ImGui::PushStyleVar(ImGuiStyleVar_CellPadding,ImVec2(0.0f,0.0f));
402 float availY=ImGui::GetContentRegionAvail().y;
403 if (ImGui::BeginTable("ChanOsc",chanOscCols,ImGuiTableFlags_Borders|ImGuiTableFlags_NoClip)) {
404 std::vector<DivDispatchOscBuffer*> oscBufs;
405 std::vector<ChanOscStatus*> oscFFTs;
406 std::vector<int> oscChans;
407 int chans=e->getTotalChannelCount();
408 ImGuiWindow* window=ImGui::GetCurrentWindow();
409
410 ImGuiStyle& style=ImGui::GetStyle();
411 ImVec2 waveform[1024];
412
413 // check work thread
414 if (chanOscWorkPool==NULL) {
415 logV(_("creating chan osc work pool"));
416 chanOscWorkPool=new DivWorkPool(settings.chanOscThreads);
417 }
418
419 // fill buffers
420 for (int i=0; i<chans; i++) {
421 DivDispatchOscBuffer* buf=e->getOscBuffer(i);
422 if (buf!=NULL && e->curSubSong->chanShowChanOsc[i]) {
423 oscBufs.push_back(buf);
424 oscFFTs.push_back(&chanOscChan[i]);
425 oscChans.push_back(i);
426 }
427 }
428
429 // process
430 for (size_t i=0; i<oscBufs.size(); i++) {
431 ChanOscStatus* fft_=oscFFTs[i];
432
433 fft_->relatedBuf=oscBufs[i];
434 fft_->relatedCh=oscChans[i];
435
436 if (fft_->relatedBuf!=NULL) {
437 // prepare
438 if (centerSettingReset) {
439 fft_->relatedBuf->readNeedle=fft_->relatedBuf->needle>>16;
440 }
441
442 // check FFT status existence
443 if (!fft_->ready) {
444 logD(_("creating FFT plan for channel %d"),fft_->relatedCh);
445 fft_->inBuf=(double*)fftw_malloc(FURNACE_FFT_SIZE*sizeof(double));
446 fft_->outBuf=(fftw_complex*)fftw_malloc(FURNACE_FFT_SIZE*sizeof(fftw_complex));
447 fft_->corrBuf=(double*)fftw_malloc(FURNACE_FFT_SIZE*sizeof(double));
448 fft_->plan=fftw_plan_dft_r2c_1d(FURNACE_FFT_SIZE,fft_->inBuf,fft_->outBuf,FFTW_ESTIMATE);
449 fft_->planI=fftw_plan_dft_c2r_1d(FURNACE_FFT_SIZE,fft_->outBuf,fft_->corrBuf,FFTW_ESTIMATE);
450 if (fft_->plan==NULL) {
451 logE(_("failed to create plan!"));
452 } else if (fft_->planI==NULL) {
453 logE(_("failed to create inverse plan!"));
454 } else if (fft_->inBuf==NULL || fft_->outBuf==NULL || fft_->corrBuf==NULL) {
455 logE(_("failed to create FFT buffers"));
456 } else {
457 fft_->ready=true;
458 }
459 }
460
461 if (fft_->ready && e->isRunning()) {
462 fft_->windowSize=chanOscWindowSize;
463 fft_->waveCorr=chanOscWaveCorr;
464 chanOscWorkPool->push([](void* fft_v) {
465 ChanOscStatus* fft=(ChanOscStatus*)fft_v;
466 DivDispatchOscBuffer* buf=fft->relatedBuf;
467
468 // the STRATEGY
469 // 1. FFT of windowed signal
470 // 2. inverse FFT of auto-correlation
471 // 3. find size of one period
472 // 4. DFT of the fundamental of ONE PERIOD
473 // 5. now we can get phase information
474 //
475 // I have a feeling this could be simplified to two FFTs or even one...
476 // if you know how, please tell me
477
478 // initialization
479 double phase=0.0;
480 int displaySize=65536.0f*(fft->windowSize/1000.0f);
481 int displaySize2=65536.0f*(fft->windowSize/500.0f);
482 fft->loudEnough=false;
483 fft->needle=buf->needle>>16;
484
485 // first FFT
486 int k=0;
487 short lastSample=0;
488 memset(fft->inBuf,0,FURNACE_FFT_SIZE*sizeof(double));
489 if (displaySize2<FURNACE_FFT_SIZE) {
490 for (int j=-FURNACE_FFT_SIZE; j<FURNACE_FFT_SIZE; j++) {
491 const short newData=buf->data[(unsigned short)(fft->needle-displaySize2+((j*displaySize2)/(FURNACE_FFT_SIZE)))];
492 if (newData!=-1) lastSample=newData;
493 if (j<0) continue;
494 fft->inBuf[j]=(double)lastSample/32768.0;
495 if (fft->inBuf[j]>0.001 || fft->inBuf[j]<-0.001) fft->loudEnough=true;
496 fft->inBuf[j]*=0.55-0.45*cos(M_PI*(double)j/(double)(FURNACE_FFT_SIZE>>1));
497 }
498 } else {
499 for (unsigned short j=fft->needle-displaySize2; j!=fft->needle; j++, k++) {
500 const int kIn=(k*FURNACE_FFT_SIZE)/displaySize2;
501 if (kIn>=FURNACE_FFT_SIZE) break;
502 if (buf->data[j]!=-1) lastSample=buf->data[j];
503 fft->inBuf[kIn]=(double)lastSample/32768.0;
504 if (fft->inBuf[kIn]>0.001 || fft->inBuf[kIn]<-0.001) fft->loudEnough=true;
505 fft->inBuf[kIn]*=0.55-0.45*cos(M_PI*(double)kIn/(double)(FURNACE_FFT_SIZE>>1));
506 }
507 }
508
509 // only proceed if not quiet
510 if (fft->loudEnough) {
511 fftw_execute(fft->plan);
512
513 // auto-correlation and second FFT
514 for (int j=0; j<FURNACE_FFT_SIZE; j++) {
515 fft->outBuf[j][0]/=FURNACE_FFT_SIZE;
516 fft->outBuf[j][1]/=FURNACE_FFT_SIZE;
517 fft->outBuf[j][0]=fft->outBuf[j][0]*fft->outBuf[j][0]+fft->outBuf[j][1]*fft->outBuf[j][1];
518 fft->outBuf[j][1]=0;
519 }
520 fft->outBuf[0][0]=0;
521 fft->outBuf[0][1]=0;
522 fft->outBuf[1][0]=0;
523 fft->outBuf[1][1]=0;
524 fftw_execute(fft->planI);
525
526 // window
527 for (int j=0; j<(FURNACE_FFT_SIZE>>1); j++) {
528 fft->corrBuf[j]*=1.0-((double)j/(double)(FURNACE_FFT_SIZE<<1));
529 }
530
531 // find size of period
532 double waveLenCandL=DBL_MAX;
533 double waveLenCandH=DBL_MIN;
534 fft->waveLen=FURNACE_FFT_SIZE-1;
535 fft->waveLenBottom=0;
536 fft->waveLenTop=0;
537
538 // find lowest point
539 for (int j=(FURNACE_FFT_SIZE>>2); j>2; j--) {
540 if (fft->corrBuf[j]<waveLenCandL) {
541 waveLenCandL=fft->corrBuf[j];
542 fft->waveLenBottom=j;
543 }
544 }
545
546 // find highest point
547 for (int j=(FURNACE_FFT_SIZE>>1)-1; j>fft->waveLenBottom; j--) {
548 if (fft->corrBuf[j]>waveLenCandH) {
549 waveLenCandH=fft->corrBuf[j];
550 fft->waveLen=j;
551 }
552 }
553 fft->waveLenTop=fft->waveLen;
554
555 // did we find the period size?
556 if (fft->waveLen<(FURNACE_FFT_SIZE-32)) {
557 // we got pitch
558 fft->pitch=pow(1.0-(fft->waveLen/(double)(FURNACE_FFT_SIZE>>1)),4.0);
559
560 fft->waveLen*=(double)displaySize*2.0/(double)FURNACE_FFT_SIZE;
561
562 // DFT of one period (x_1)
563 double dft[2];
564 dft[0]=0.0;
565 dft[1]=0.0;
566 lastSample=0;
567 for (int j=fft->needle-1-displaySize-(int)fft->waveLen, k=-(displaySize>>1); k<fft->waveLen; j++, k++) {
568 if (buf->data[j&0xffff]!=-1) lastSample=buf->data[j&0xffff];
569 if (k<0) continue;
570 double one=((double)lastSample/32768.0);
571 double two=(double)k*(-2.0*M_PI)/fft->waveLen;
572 dft[0]+=one*cos(two);
573 dft[1]+=one*sin(two);
574 }
575
576 // calculate and lock into phase
577 phase=(0.5+(atan2(dft[1],dft[0])/(2.0*M_PI)));
578
579 fft->debugPhase=phase;
580
581 if (fft->waveCorr) {
582 fft->needle-=(phase+(fft->phaseOff*2))*fft->waveLen;
583 }
584 }
585 }
586
587 fft->needle-=displaySize;
588 },fft_);
589 }
590 }
591 }
592 chanOscWorkPool->wait();
593
594 // 0: none
595 // 1: sqrt(chans)
596 // 2: sqrt(chans+1)
597 // 3: sqrt(chans)+1
598 switch (chanOscAutoColsType) {
599 case 1:
600 chanOscCols=sqrt(oscChans.size());
601 break;
602 case 2:
603 chanOscCols=sqrt(oscChans.size()+1);
604 break;
605 case 3:
606 chanOscCols=sqrt(oscChans.size())+1;
607 break;
608 }
609 if (chanOscCols<1) chanOscCols=1;
610 if (chanOscCols>64) chanOscCols=64;
611
612 int rows=(oscBufs.size()+(chanOscCols-1))/chanOscCols;
613
614 // render
615 for (size_t i=0; i<oscBufs.size(); i++) {
616 if (i%chanOscCols==0) ImGui::TableNextRow();
617 ImGui::TableNextColumn();
618
619 DivDispatchOscBuffer* buf=oscBufs[i];
620 ChanOscStatus* fft=oscFFTs[i];
621 int ch=oscChans[i];
622 if (buf==NULL) {
623 ImGui::Text(_("Error!"));
624 } else {
625 ImVec2 size=ImGui::GetContentRegionAvail();
626 size.y=availY/rows;
627
628 ImVec2 minArea=window->DC.CursorPos;
629 ImVec2 maxArea=ImVec2(
630 minArea.x+size.x,
631 minArea.y+size.y
632 );
633 ImRect rect=ImRect(minArea,maxArea);
634 ImRect inRect=rect;
635 inRect.Min.x+=dpiScale;
636 inRect.Min.y+=2.0*dpiScale;
637 inRect.Max.x-=dpiScale;
638 inRect.Max.y-=2.0*dpiScale;
639
640 int precision=inRect.Max.x-inRect.Min.x;
641 if (precision<1) precision=1;
642 if (precision>1024) precision=1024;
643
644 ImGui::ItemSize(size,style.FramePadding.y);
645 if (ImGui::ItemAdd(rect,ImGui::GetID("chOscDisplay"))) {
646 if (!e->isRunning()) {
647 if (rend->supportsDrawOsc() && settings.shaderOsc) {
648 memset(fft->oscTex,0,2048*sizeof(float));
649 } else {
650 for (unsigned short j=0; j<precision; j++) {
651 float x=(float)j/(float)precision;
652 waveform[j]=ImLerp(inRect.Min,inRect.Max,ImVec2(x,0.5f));
653 }
654 }
655 } else {
656 int displaySize=65536.0f*(chanOscWindowSize/1000.0f);
657 int displaySize2=65536.0f*(chanOscWindowSize/500.0f);
658
659 float minLevel=1.0f;
660 float maxLevel=-1.0f;
661
662 if (debugFFT) {
663 // FFT debug code!
664 double maxavg=0.0;
665 for (unsigned short j=0; j<(FURNACE_FFT_SIZE>>1); j++) {
666 if (fabs(fft->corrBuf[j]>maxavg)) {
667 maxavg=fabs(fft->corrBuf[j]);
668 }
669 }
670 if (maxavg>0.0000001) maxavg=0.5/maxavg;
671
672 if (rend->supportsDrawOsc() && settings.shaderOsc) {
673 for (unsigned short j=0; j<precision && j<2048; j++) {
674 float y;
675 if (j>=precision/2) {
676 y=fft->inBuf[((j-(precision/2))*FURNACE_FFT_SIZE*2)/(precision)];
677 } else {
678 y=fft->corrBuf[(j*FURNACE_FFT_SIZE)/precision]*maxavg;
679 }
680 fft->oscTex[j]=y*2.0;
681 }
682 } else {
683 for (unsigned short j=0; j<precision; j++) {
684 float x=(float)j/(float)precision;
685 float y;
686 if (j>=precision/2) {
687 y=fft->inBuf[((j-(precision/2))*FURNACE_FFT_SIZE*2)/(precision)];
688 } else {
689 y=fft->corrBuf[(j*FURNACE_FFT_SIZE)/precision]*maxavg;
690 }
691 waveform[j]=ImLerp(inRect.Min,inRect.Max,ImVec2(x,0.5f-y));
692 }
693 }
694 if (fft->loudEnough) {
695 String cPhase=fmt::sprintf("\n%.1f (b: %d t: %d)\nSIZES: %d, %d, %d\nPHASE %f",fft->waveLen,fft->waveLenBottom,fft->waveLenTop,displaySize,displaySize2,FURNACE_FFT_SIZE,fft->debugPhase);
696 dl->AddText(inRect.Min,0xffffffff,cPhase.c_str());
697
698 dl->AddLine(
699 ImLerp(inRect.Min,inRect.Max,ImVec2((double)fft->waveLenBottom/(double)FURNACE_FFT_SIZE,0.0)),
700 ImLerp(inRect.Min,inRect.Max,ImVec2((double)fft->waveLenBottom/(double)FURNACE_FFT_SIZE,1.0)),
701 0xffffff00
702 );
703 dl->AddLine(
704 ImLerp(inRect.Min,inRect.Max,ImVec2((double)fft->waveLenTop/(double)FURNACE_FFT_SIZE,0.0)),
705 ImLerp(inRect.Min,inRect.Max,ImVec2((double)fft->waveLenTop/(double)FURNACE_FFT_SIZE,1.0)),
706 0xff00ff00
707 );
708 dl->AddLine(
709 ImLerp(inRect.Min,inRect.Max,ImVec2(0.75-(fft->debugPhase*0.25),0.0)),
710 ImLerp(inRect.Min,inRect.Max,ImVec2(0.75-(fft->debugPhase*0.25),1.0)),
711 0xff00ffff
712 );
713 } else {
714 if (debugFFT) {
715 dl->AddText(inRect.Min,0xffffffff,"\nquiet");
716 }
717 }
718 } else {
719 // find the first sample
720 float y=0;
721 for (int j=0; j<32768; j++) {
722 const short y_s=buf->data[(fft->needle-j)&0xffff];
723 if (y_s!=-1) {
724 y=(float)y_s/32768.0f;
725 break;
726 }
727 }
728 if (chanOscCenterStrat==0) { // DC correction off
729 fft->dcOff=0;
730 } else if (chanOscCenterStrat==1) { // normal DC correction
731 float y1=y;
732 if (minLevel>y1) minLevel=y1;
733 if (maxLevel<y1) maxLevel=y1;
734 for (unsigned short j=fft->needle; j!=((fft->needle+displaySize)&0xffff); j++) {
735 const short y_s=buf->data[j];
736 if (y_s!=-1) {
737 y1=(float)y_s/32768.0f;
738 if (minLevel>y1) minLevel=y1;
739 if (maxLevel<y1) maxLevel=y1;
740 }
741 }
742 fft->dcOff=(minLevel+maxLevel)*0.5f;
743 }
744 // render chan osc
745 if (displaySize<precision) {
746 for (int j=0; j<precision; j++) {
747 const short y_s=buf->data[(unsigned short)(fft->needle+(j*displaySize/precision))];
748 if (y_s!=-1) {
749 y=(float)y_s/32768.0f;
750 if (j<0) continue;
751 if (minLevel>y) minLevel=y;
752 if (maxLevel<y) maxLevel=y;
753 }
754 if (j<0) continue;
755 float yOut=y-fft->dcOff;
756 if (chanOscCenterStrat==2) {
757 fft->dcOff+=(y-fft->dcOff)*0.001;
758 }
759 if (yOut<-0.5f) yOut=-0.5f;
760 if (yOut>0.5f) yOut=0.5f;
761 yOut*=chanOscAmplify*2.0f;
762 fft->oscTex[j]=yOut;
763 }
764 } else {
765 int k=0;
766 for (unsigned short j=fft->needle; j!=((fft->needle+displaySize)&0xffff); j++, k++) {
767 const short y_s=buf->data[j];
768 const int kTex=(k*precision)/displaySize;
769 if (kTex>=precision) break;
770 if (y_s!=-1) {
771 y=(float)y_s/32768.0f;
772 if (k<0) continue;
773 if (minLevel>y) minLevel=y;
774 if (maxLevel<y) maxLevel=y;
775 }
776 if (kTex<0) continue;
777 float yOut=y-fft->dcOff;
778 if (chanOscCenterStrat==2) {
779 fft->dcOff+=(y-fft->dcOff)*0.001;
780 }
781 if (yOut<-0.5f) yOut=-0.5f;
782 if (yOut>0.5f) yOut=0.5f;
783 yOut*=chanOscAmplify*2.0f;
784 fft->oscTex[kTex]=yOut;
785 }
786 }
787
788 if (!(rend->supportsDrawOsc() && settings.shaderOsc)) {
789 for (unsigned short j=0; j<precision; j++) {
790 float x=(float)j/(float)precision;
791 waveform[j]=ImLerp(inRect.Min,inRect.Max,ImVec2(x,0.5f-fft->oscTex[j]*0.5f));
792 }
793 }
794 }
795 }
796 ImU32 color=ImGui::GetColorU32(chanOscColor);
797 if (chanOscUseGrad) {
798 float xVal=computeGradPos(chanOscColorX,ch);
799 float yVal=computeGradPos(chanOscColorY,ch);
800
801 xVal=CLAMP(xVal,0.0f,1.0f);
802 yVal=CLAMP(yVal,0.0f,1.0f);
803
804 color=chanOscGrad.get(xVal,1.0f-yVal);
805 }
806
807 if (rend->supportsDrawOsc() && settings.shaderOsc) {
808 fft->drawOp.gui=this;
809 fft->drawOp.data=fft->oscTex;
810 fft->drawOp.len=precision;
811 fft->drawOp.pos0=inRect.Min;
812 fft->drawOp.pos1=inRect.Max;
813 fft->drawOp.color=ImGui::ColorConvertU32ToFloat4(color);
814 fft->drawOp.lineSize=dpiScale*chanOscLineSize;
815
816 dl->AddCallback(_drawOsc,&fft->drawOp);
817 dl->AddCallback(ImDrawCallback_ResetRenderState,NULL);
818 } else {
819 //ImGui::PushClipRect(inRect.Min,inRect.Max,false);
820 //ImDrawListFlags prevFlags=dl->Flags;
821 //dl->Flags&=~(ImDrawListFlags_AntiAliasedLines|ImDrawListFlags_AntiAliasedLinesUseTex);
822 dl->AddPolyline(waveform,precision,color,ImDrawFlags_None,dpiScale*chanOscLineSize);
823 //dl->Flags=prevFlags;
824 //ImGui::PopClipRect();
825 }
826
827 //ImGui::PushClipRect(inRect.Min,inRect.Max,false);
828 if (!chanOscTextFormat.empty()) {
829 String text;
830 bool inFormat=false;
831
832 for (char j: chanOscTextFormat) {
833 if (inFormat) {
834 switch (j) {
835 case 'c':
836 text+=e->getChannelName(ch);
837 break;
838 case 'C':
839 text+=e->getChannelShortName(ch);
840 break;
841 case 'd':
842 text+=fmt::sprintf("%d",ch);
843 break;
844 case 'D':
845 text+=fmt::sprintf("%d",ch+1);
846 break;
847 case 'i': {
848 DivChannelState* chanState=e->getChanState(ch);
849 if (chanState==NULL) break;
850 DivInstrument* ins=e->getIns(chanState->lastIns);
851 text+=ins->name;
852 break;
853 }
854 case 'I': {
855 DivChannelState* chanState=e->getChanState(ch);
856 if (chanState==NULL) break;
857 text+=fmt::sprintf("%d",chanState->lastIns);
858 break;
859 }
860 case 'x': {
861 DivChannelState* chanState=e->getChanState(ch);
862 if (chanState==NULL) break;
863 if (chanState->lastIns<0) {
864 text+="??";
865 } else {
866 text+=fmt::sprintf("%.2X",chanState->lastIns);
867 }
868 break;
869 }
870 case 's': {
871 text+=e->getSystemName(e->sysOfChan[ch]);
872 break;
873 }
874 case 'p': {
875 text+=FurnaceGUI::getSystemPartNumber(e->sysOfChan[ch],e->song.systemFlags[e->dispatchOfChan[ch]]);
876 break;
877 }
878 case 'S': {
879 text+=fmt::sprintf("%d",e->dispatchOfChan[ch]);
880 break;
881 }
882 case 'v': {
883 DivChannelState* chanState=e->getChanState(ch);
884 if (chanState==NULL) break;
885 text+=fmt::sprintf("%d",chanState->volume>>8);
886 break;
887 }
888 case 'V': {
889 DivChannelState* chanState=e->getChanState(ch);
890 if (chanState==NULL) break;
891 double volMax=chanState->volMax>>8;
892 if (volMax<1) volMax=1;
893 text+=fmt::sprintf("%.1f%%",((double)(chanState->volume>>8)/volMax)*100);
894 break;
895 }
896 case 'b': {
897 DivChannelState* chanState=e->getChanState(ch);
898 if (chanState==NULL) break;
899 text+=fmt::sprintf("%.2X",chanState->volume>>8);
900 break;
901 }
902 case 'n': {
903 DivChannelState* chanState=e->getChanState(ch);
904 if (chanState==NULL || !(chanState->keyOn)) break;
905 short tempNote=chanState->note; //all of this conversion is necessary because notes 100-102 are special chars
906 short noteMod=tempNote%12+12; //also note 0 is a BUG, hence +12 on the note and -1 on the octave
907 short oct=tempNote/12-1;
908 text+=fmt::sprintf("%s",noteName(noteMod,oct));
909 break;
910 }
911 case 'l': {
912 text+='\n';
913 break;
914 }
915 case '%':
916 text+='%';
917 break;
918 default:
919 text+='%';
920 text+=j;
921 break;
922 }
923 inFormat=false;
924 } else {
925 if (j=='%') {
926 inFormat=true;
927 } else {
928 text+=j;
929 }
930 }
931 }
932 dl->AddText(ImLerp(inRect.Min,inRect.Max,ImVec2(0.0f,0.0f)),ImGui::GetColorU32(chanOscTextColor),text.c_str());
933 }
934
935 //ImGui::PopClipRect();
936 }
937 }
938 }
939 ImGui::EndTable();
940
941 if (ImGui::IsItemClicked(ImGuiMouseButton_Right)) {
942 chanOscOptions=!chanOscOptions;
943 }
944 if (ImGui::IsItemHovered() && CHECK_LONG_HOLD) {
945 NOTIFY_LONG_HOLD;
946 chanOscOptions=!chanOscOptions;
947 }
948 }
949 ImGui::PopStyleVar();
950 }
951 }
952 if (ImGui::IsWindowFocused(ImGuiFocusedFlags_ChildWindows)) curWindow=GUI_WINDOW_CHAN_OSC;
953 ImGui::End();
954 }