-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathscopewidget.cpp
494 lines (407 loc) · 13 KB
/
scopewidget.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
/*
* Copyright (C) 2020 - 2023 Judd Niemann - All Rights Reserved.
* You may use, distribute and modify this code under the
* terms of the GNU Lesser General Public License, version 2.1
*
* You should have received a copy of GNU Lesser General Public License v2.1
* with this file. If not, please refer to: https://github.com/jniemann66/sndscope.git
*/
#include "scopewidget.h"
#include <QVBoxLayout>
#include <QEvent>
#include <QDebug>
#include <cmath>
ScopeWidget::ScopeWidget(QWidget *parent) : QWidget(parent)
{
scopeDisplay = new ScopeDisplay(this);
audioController = new AudioController(this);
plotter = new Plotter;
plotter->moveToThread(&renderThread);
connect(&renderThread, &QThread::finished, plotter, &QObject::deleteLater);
renderThread.start();
auto mainLayout = new QVBoxLayout;
screenLayout = new QHBoxLayout;
constexpr int virtualFPS = 100; // number of virtual frames per second
constexpr int screenFPS = 150;
constexpr double plotInterval = 1000.0 / virtualFPS; // interval (in ms) between virtual frames
constexpr double screenUpdateInterval = 1000.0 / screenFPS;
plotTimer.setInterval(plotInterval);
screenUpdateTimer.setInterval(screenUpdateInterval);
const auto divs = scopeDisplay->getDivisions();
sweepParameters.horizontalDivisions = divs.first;
sweepParameters.verticalDivisions = divs.second;
sweepParameters.sweepUnused = {plotMode != Sweep};
setUpsampling(getUpsampling());
plotter->setTimeLimit_ms(plotInterval);
plotter->setSweepParameters(sweepParameters);
#ifdef SNDSCOPE_BLEND2D
scopeDisplay->getBlImageWrapper()->getQImage()->fill(backgroundColor);
plotter->setBlImageWrapper(scopeDisplay->getBlImageWrapper());
#else
scopeDisplay->getPixmap()->fill(backgroundColor);
plotter->setTimeLimit_ms(plotInterval);
plotter->setPixmap(scopeDisplay->getPixmap());
plotter->setSweepParameters(sweepParameters);
#endif
connect(scopeDisplay, &ScopeDisplay::pixmapResolutionChanged, this, [this](){
#ifdef SNDSCOPE_BLEND2D
const auto b = scopeDisplay->getBlImageWrapper();
plotter->setBlImageWrapper(b);
w = b->getQImage()->width();
h = b->getQImage()->height();
#else
const auto p = scopeDisplay->getPixmap();
plotter->setPixmap(p);
w = p->width();
h = p->height();
#endif
sweepParameters.setWidthFrameRate(w, audioFramesPerMs);
plotter->calcScaling();
});
connect(&plotTimer, &QTimer::timeout, this, [this]{
if(!paused) {
readInput();
// send audio to output
pushOut->write(reinterpret_cast<char*>(rawinputBuffer.data()), framesRead * audioFormat.bytesPerFrame());
// plot it
plotter->render(inputBuffers, framesAvailable, currentFrame);
}
});
connect(&screenUpdateTimer, &QTimer::timeout, this, [this] {
if(!paused) {
if(plotter->getFreshRender()) {
scopeDisplay->update();
plotter->setFreshRender(false);
}
}
});
connect(audioController, &AudioController::outputVolume, this, [this](qreal linearVol){
emit outputVolume(linearVol);
});
connect(plotter, &Plotter::renderedFrame, this, [this](int64_t frame){
emit renderedFrame(frame * msPerAudioFrame);
});
screenLayout->addWidget(scopeDisplay, 0, Qt::AlignHCenter);
mainLayout->addLayout(screenLayout);
setLayout(mainLayout);
plotTimer.start();
screenUpdateTimer.start();
outputDeviceInfo = QAudioDeviceInfo::defaultOutputDevice();
}
ScopeWidget::~ScopeWidget()
{
qDebug().noquote() << "Goodbye";
renderThread.quit();
renderThread.wait();
qDebug().noquote() << "See you next time";
}
QPair<bool, QString> ScopeWidget::loadSoundFile(const QString& filename)
{
sndfile.reset(new SndfileHandle(filename.toLatin1(), SFM_READ));
fileLoaded = (sndfile->error() == SF_ERR_NO_ERROR);
if(fileLoaded) {
// set up rendering parameters, based on soundfile properties
numInputChannels = sndfile->channels();
// initialize raw (interleaved) input buffer
rawinputBuffer.resize(numInputChannels * sndfile->samplerate()); // 1s of storage
// initialize channel input buffers
inputBuffers.resize(numInputChannels);
for(int ch = 0; ch < numInputChannels; ch++) {
size_t chbufSize = sndfile->samplerate() * upsampleFactor; // allow for upsampling
inputBuffers[ch].resize(chbufSize);
}
audioFramesPerMs = sndfile->samplerate() / 1000;
msPerAudioFrame = 1000.0 / sndfile->samplerate();
sweepParameters.setInputFrames_per_ms(audioFramesPerMs);
expectedFrames = plotTimer.interval() * audioFramesPerMs;
maxFramesToRead = rawinputBuffer.size() / sndfile->channels();
totalFrames = sndfile->frames();
returnToStart();
// set up audio
audioFormat.setSampleRate(sndfile->samplerate());
audioFormat.setChannelCount(sndfile->channels());
audioFormat.setSampleSize(32);
audioFormat.setCodec("audio/pcm");
audioFormat.setByteOrder(QAudioFormat::LittleEndian);
audioFormat.setSampleType(QAudioFormat::Float);
audioController->initializeAudio(audioFormat, outputDeviceInfo);
plotter->setExpectedFrames(expectedFrames);
plotter->setAudioFramesPerMs(audioFramesPerMs);
plotter->setNumInputChannels(audioFormat.channelCount());
plotter->calcScaling();
emit loadedFile();
}
return {fileLoaded, sndfile->strError()};
}
int ScopeWidget::getLengthMilliseconds() const
{
return static_cast<int>(msPerAudioFrame * sndfile->frames());
}
bool ScopeWidget::getPaused() const
{
return paused;
}
void ScopeWidget::setPaused(bool value)
{
// disallow unpause if file not loaded
if(!value && paused && !fileLoaded) {
return;
}
paused = value;
if(!paused) {
pushOut=audioController->start();
startFrame = currentFrame;
elapsedTimer.restart();
}
}
void ScopeWidget::returnToStart()
{
elapsedTimer.restart();
currentFrame = 0ll;
startFrame = 0ll;
if(sndfile != nullptr && !sndfile->error()) {
sndfile->seek(0ll, SEEK_SET);
}
}
void ScopeWidget::gotoPosition(int64_t milliSeconds)
{
elapsedTimer.restart();
if(sndfile != nullptr && !sndfile->error()) {
currentFrame = audioFramesPerMs * milliSeconds;
startFrame = currentFrame;
sndfile->seek(qMin(currentFrame, sndfile->frames()), SEEK_SET);
}
}
QColor ScopeWidget::getBackgroundColor() const
{
return backgroundColor;
}
void ScopeWidget::setBackgroundColor(const QColor &value)
{
backgroundColor = value;
}
void ScopeWidget::setPhosporColors(const QVector<QColor>& colors)
{
if(!colors.isEmpty()) {
plotter->setPhosphorColor(colors.at(0));
if(colors.count() > 1) {
plotter->setCompositionMode(QPainter::CompositionMode_HardLight);
plotter->setDarkencolor(colors.at(1));
} else {
plotter->setCompositionMode(QPainter::CompositionMode_SourceOver);
plotter->setDarkencolor(backgroundColor);
}
}
}
double ScopeWidget::getPersistence() const
{
return persistence;
}
void ScopeWidget::setPersistence(double time_ms)
{
// qDebug() << QStringLiteral("setting persistence to %1").arg(time_ms);
persistence = time_ms;
// define fraction of original brightness
constexpr double decayTarget = 0.2;
// set minimum darkening amount threshold. (If the darkening amount is too low, traces will never completely disappear)
constexpr qreal minDarkenAlpha = 32;
int darkenAlpha = 0;
int darkenNthFrame = 0;
do {
++darkenNthFrame; // for really long persistence, darkening operation may need to occur less often than once per frame
double n = std::max(1.0, time_ms / plotTimer.interval()) / darkenNthFrame; // number of frames to reach decayTarget (can't be zero)
darkenAlpha = std::min(std::max(1, static_cast<int>(255 * (1.0 - std::pow(decayTarget, (1.0 / n))))), 255);
} while (darkenAlpha < minDarkenAlpha);
auto darkenColor = plotter->getDarkencolor();
darkenColor.setAlpha(darkenAlpha);
plotter->setDarkencolor(darkenColor);
plotter->setDarkenNthFrame(darkenNthFrame);
}
QColor ScopeWidget::getPhosphorColor() const
{
return plotter->getPhosphorColor();
}
double ScopeWidget::getFocus() const
{
return focus;
}
void ScopeWidget::setFocus(double value)
{
constexpr double maxBeamWidth = 12;
focus = value;
plotter->setBeamWidth(qMax(0.5, (1.0 - (focus * 0.01)) * maxBeamWidth));
const auto beamWidth = plotter->getBeamWidth();
plotter->setBeamIntensity(8.0 / (beamWidth * beamWidth));
calcBeamAlpha();
}
double ScopeWidget::getBrightness() const
{
return brightness;
}
void ScopeWidget::setBrightness(double value)
{
brightness = value;
calcBeamAlpha();
}
void ScopeWidget::calcBeamAlpha()
{
beamAlpha = qMin(1.27 * brightness * plotter->getBeamIntensity(), 255.0);
auto phosphorColor = plotter->getPhosphorColor();
phosphorColor.setAlpha(beamAlpha);
plotter->setPhosphorColor(phosphorColor);
}
int64_t ScopeWidget::getTotalFrames() const
{
return totalFrames;
}
void ScopeWidget::readInput()
{
// estimate how far ahead to read
const int64_t toFrame = qMin(totalFrames - 1, startFrame + static_cast<int64_t>(elapsedTimer.elapsed() * audioFramesPerMs));
// read from file
framesRead = sndfile->readf(rawinputBuffer.data(), qMin(maxFramesToRead, toFrame - currentFrame));
currentFrame += framesRead;
constexpr bool debugExpectedFrames = false;
if constexpr(debugExpectedFrames) {
if(framesRead > expectedFrames)
qDebug() << "expected" << expectedFrames << "got" << framesRead;
}
// de-interleave
if(upsampling && numInputChannels <= 2) {
if(numInputChannels == 1) {
upsampler.upsampleBlockMono(inputBuffers[0].data(), rawinputBuffer.constData(), framesRead);
framesAvailable = framesRead * upsampleFactor;
} else if(numInputChannels == 2) {
upsampler.upsampleBlockStereo(inputBuffers[0].data(), inputBuffers[1].data(), rawinputBuffer.constData(), framesRead);
framesAvailable = framesRead * upsampleFactor;
}
} else {
for(int64_t f = 0ll; f < framesRead; f++) {
for(int ch = 0; ch < numInputChannels; ch++) {
inputBuffers[ch][f] = rawinputBuffer[f * numInputChannels + ch];
}
}
framesAvailable = framesRead;
}
}
void ScopeWidget::wipeScreen()
{
#ifdef SNDSCOPE_BLEND2D
// todo: wipe screen
#else
auto pixmap = scopeDisplay->getPixmap();
QPainter painter(pixmap);
painter.setCompositionMode(QPainter::CompositionMode_SourceOver);
QColor d{backgroundColor};
d.setAlpha(255);
// darken:
painter.fillRect(pixmap->rect(), d);
scopeDisplay->update();
#endif
}
QAudioDeviceInfo ScopeWidget::getOutputDeviceInfo() const
{
return outputDeviceInfo;
}
void ScopeWidget::setOutputDevice(const QAudioDeviceInfo &newOutputDeviceInfo)
{
bool changed = (outputDeviceInfo != newOutputDeviceInfo);
outputDeviceInfo = newOutputDeviceInfo;
if(changed && fileLoaded) {
audioController->initializeAudio(audioFormat, outputDeviceInfo);
}
}
Plotmode ScopeWidget::getPlotmode() const
{
return plotMode;
}
void ScopeWidget::setPlotmode(Plotmode newPlotmode)
{
plotMode = newPlotmode;
if(plotMode == Sweep) {
//
} else {
sweepParameters.sweepUnused = true;
}
plotter->setPlotMode(plotMode);
}
bool ScopeWidget::getUpsampling() const
{
return upsampling;
}
void ScopeWidget::setUpsampling(bool val)
{
upsampling = val;
sweepParameters.setUpsampleFactor(upsampling ? static_cast<double>(upsampleFactor) : 1.0);
plotter->setSweepParameters(sweepParameters);
if(upsampling) {
upsampler.reset();
}
}
void ScopeWidget::setAudioVolume(qreal linearVolume)
{
audioController->setOutputVolume(linearVolume);
}
void ScopeWidget::setSweepParameters(const SweepParameters &newSweepParameters)
{
double newDuration = newSweepParameters.duration_ms;
if(sweepParameters.duration_ms != newDuration) {
sweepParameters.setDuration_ms(newDuration);
}
const double &newTriggerLevel = newSweepParameters.triggerLevel;
const double &newTriggerTolerance = newSweepParameters.triggerTolerance;
if(sweepParameters.triggerLevel != newTriggerLevel || sweepParameters.triggerTolerance != newTriggerTolerance) {
sweepParameters.triggerLevel = newTriggerLevel;
sweepParameters.triggerTolerance = newTriggerTolerance;
sweepParameters.triggerMin = newTriggerLevel - sweepParameters.triggerTolerance;
sweepParameters.triggerMax = newTriggerLevel + sweepParameters.triggerTolerance;
if(paused) {
setShowTrigger(showTrigger);
}
}
sweepParameters.slope = newSweepParameters.slope;
sweepParameters.triggerEnabled = newSweepParameters.triggerEnabled;
sweepParameters.setWidthFrameRate(w, audioFramesPerMs);
if(plotter != nullptr) {
plotter->setSweepParameters(sweepParameters);
}
}
bool ScopeWidget::getShowTrigger() const
{
return showTrigger;
}
bool ScopeWidget::getconnectSamples() const
{
return plotter != nullptr && plotter->getconnectSamples();
}
void ScopeWidget::setShowTrigger(bool val)
{
showTrigger = (plotMode == Sweep) && val;
if(paused) {
#ifdef SNDSCOPE_BLEND2D
#else
auto pixmap = scopeDisplay->getPixmap();
QPainter painter(pixmap);
painter.beginNativePainting();
painter.setRenderHint(QPainter::Antialiasing, false);
painter.fillRect(pixmap->rect(), Qt::black);
if(showTrigger) {
plotter->drawTrigger(&painter);
}
painter.endNativePainting();
scopeDisplay->update();
#endif
} else {
plotter->setShowTrigger(showTrigger);
}
}
void ScopeWidget::setconnectSamples(bool val)
{
if(plotter != nullptr) {
plotter->setconnectSamples(val);
}
}
SweepParameters ScopeWidget::getSweepParameters() const
{
return sweepParameters;
}