#include <iostream>
-// Enables debugging, like writing a GNU Octave .m file to /tmp
-//#define DEBUG_AUDIOSPEC
+// (defined in the header file)
#ifdef DEBUG_AUDIOSPEC
-#include <fstream>
#include <QDebug>
-bool fileWritten = false;
#endif
+// Draw lines instead of single pixels.
+// This is about 25 % faster, especially when enlarging the scope to e.g. 1680x1050 px.
+#define AUDIOSPEC_LINES
+
#define MIN_DB_VALUE -120
#define MAX_FREQ_VALUE 96000
#define MIN_FREQ_VALUE 1000
-const QString AudioSpectrum::directions[] = {"North", "Northeast", "East", "Southeast"};
-
AudioSpectrum::AudioSpectrum(QWidget *parent) :
- AbstractAudioScopeWidget(false, parent),
+ AbstractAudioScopeWidget(true, parent),
m_fftTools(),
- m_rescaleMinDist(8),
- m_rescaleVerticalThreshold(2.0f),
- m_rescaleActive(false),
- m_rescalePropertiesLocked(false),
- m_rescaleScale(1)
+ m_lastFFT(),
+ m_lastFFTLock(1)
+ #ifdef DEBUG_AUDIOSPEC
+ ,m_timeTotal(0)
+ ,m_showTotal(0)
+ #endif
{
ui = new Ui::AudioSpectrum_UI;
ui->setupUi(this);
m_aResetHz = new QAction(i18n("Reset maximum frequency to sampling rate"), this);
+ m_aTrackMouse = new QAction(i18n("Track mouse"), this);
+ m_aTrackMouse->setCheckable(true);
m_menu->addSeparator();
m_menu->addAction(m_aResetHz);
+ m_menu->addAction(m_aTrackMouse);
m_menu->removeAction(m_aRealtime);
bool b = true;
b &= connect(m_aResetHz, SIGNAL(triggered()), this, SLOT(slotResetMaxFreq()));
b &= connect(ui->windowFunction, SIGNAL(currentIndexChanged(int)), this, SLOT(forceUpdate()));
+ b &= connect(this, SIGNAL(signalMousePositionChanged()), this, SLOT(forceUpdateHUD()));
Q_ASSERT(b);
+ // Note: These strings are used in both Spectogram and AudioSpectrum. Ideally change both (if necessary) to reduce workload on translators
ui->labelFFTSize->setToolTip(i18n("The maximum window size is limited by the number of samples per frame."));
ui->windowSize->setToolTip(i18n("A bigger window improves the accuracy at the cost of computational power."));
ui->windowFunction->setToolTip(i18n("The rectangular window function is good for signals with equal signal strength (narrow peak), but creates more smearing. See Window function on Wikipedia."));
writeConfig();
delete m_aResetHz;
+ delete m_aTrackMouse;
}
void AudioSpectrum::readConfig()
ui->windowSize->setCurrentIndex(scopeConfig.readEntry("windowSize", 0));
ui->windowFunction->setCurrentIndex(scopeConfig.readEntry("windowFunction", 0));
+ m_aTrackMouse->setChecked(scopeConfig.readEntry("trackMouse", true));
m_dBmax = scopeConfig.readEntry("dBmax", 0);
m_dBmin = scopeConfig.readEntry("dBmin", -70);
m_freqMax = scopeConfig.readEntry("freqMax", 0);
scopeConfig.writeEntry("windowSize", ui->windowSize->currentIndex());
scopeConfig.writeEntry("windowFunction", ui->windowFunction->currentIndex());
+ scopeConfig.writeEntry("trackMouse", m_aTrackMouse->isChecked());
scopeConfig.writeEntry("dBmax", m_dBmax);
scopeConfig.writeEntry("dBmin", m_dBmin);
if (m_customFreq) {
QImage AudioSpectrum::renderBackground(uint) { return QImage(); }
-QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels, const int num_samples)
+QImage AudioSpectrum::renderAudioScope(uint, const QVector<int16_t> audioFrame, const int freq, const int num_channels,
+ const int num_samples, const int)
{
if (audioFrame.size() > 63) {
if (!m_customFreq) {
m_fftTools.fftNormalized(audioFrame, 0, num_channels, freqSpectrum, windowType, fftWindow, 0);
+ // Store the current FFT window (for the HUD) and run the interpolation
+ // for easy pixel-based dB value access
+ QVector<float> dbMap;
+ m_lastFFTLock.acquire();
+ m_lastFFT = QVector<float>(fftWindow/2);
+ memcpy(m_lastFFT.data(), &(freqSpectrum[0]), fftWindow/2 * sizeof(float));
+
+ uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
+ dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -180);
+ m_lastFFTLock.release();
+
+
+ QTime drawTime = QTime::currentTime();
+
// Draw the spectrum
QImage spectrum(m_scopeRect.size(), QImage::Format_ARGB32);
spectrum.fill(qRgba(0,0,0,0));
const uint h = m_innerScopeRect.height();
const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
- float f;
- float x;
- float x_prev = 0;
- float val;
- int xi;
- for (uint i = 0; i < w; i++) {
-
- // i: Pixel coordinate
- // f: Target frequency
- // x: Frequency array index (float!) corresponding to the pixel
- // xi: floor(x)
-
- f = i/((float) w-1.0) * m_freqMax;
- x = 2*f/freq * (fftWindow/2 - 1);
- xi = (int) floor(x);
+ int yMax;
- if (x >= fftWindow/2) {
- break;
- }
-
- // Use linear interpolation in order to get smoother display
- if (i == 0 || xi == fftWindow/2-1) {
- // ... except if we are at the left or right border of the display or the spectrum
- val = freqSpectrum[xi];
- } else {
+#ifdef AUDIOSPEC_LINES
+ QPainter davinci(&spectrum);
+ davinci.setPen(AbstractScopeWidget::penThin);
+#endif
- if (freqSpectrum[xi] > freqSpectrum[xi+1]
- && x_prev < xi) {
- // This is a hack to preserve peaks.
- // Consider f = {0, 100, 0}
- // x = {0.5, 1.5}
- // Then x is 50 both times, and the 100 peak is lost.
- // Get it back here for the first x after the peak.
- val = freqSpectrum[xi];
- } else {
- val = (xi+1 - x) * freqSpectrum[xi]
- + (x - xi) * freqSpectrum[xi+1];
- }
+ for (uint i = 0; i < w; i++) {
+ yMax = (dbMap[i] - m_dBmin) / (m_dBmax-m_dBmin) * (h-1);
+ if (yMax < 0) {
+ yMax = 0;
+ } else if (yMax >= (int)h) {
+ yMax = h-1;
}
-
- // freqSpectrum values range from 0 to -inf as they are relative dB values.
- for (uint y = 0; y < h*(1 - (val - m_dBmax)/(m_dBmin-m_dBmax)) && y < h; y++) {
+#ifdef AUDIOSPEC_LINES
+ davinci.drawLine(leftDist + i, topDist + h-1, leftDist + i, topDist + h-1 - yMax);
+#else
+ for (int y = 0; y < yMax && y < (int)h; y++) {
spectrum.setPixel(leftDist + i, topDist + h-y-1, qRgba(225, 182, 255, 255));
}
-
- x_prev = x;
+#endif
}
- emit signalScopeRenderingFinished(start.elapsed(), 1);
-
#ifdef DEBUG_AUDIOSPEC
- if (!fileWritten || true) {
- std::ofstream mFile;
- mFile.open("/tmp/freq.m");
- if (!mFile) {
- qDebug() << "Opening file failed.";
- } else {
- mFile << "val = [ ";
-
- for (int sample = 0; sample < 256; sample++) {
- mFile << data[sample] << " ";
- }
- mFile << " ];\n";
+ m_showTotal++;
+ m_timeTotal += drawTime.elapsed();
+ qDebug() << widgetName() << " took " << drawTime.elapsed() << " ms for drawing. Average: " << ((float)m_timeTotal/m_showTotal) ;
+#endif
- mFile << "freq = [ ";
- for (int sample = 0; sample < 256; sample++) {
- mFile << freqData[sample].r << "+" << freqData[sample].i << "*i ";
- }
- mFile << " ];\n";
+ emit signalScopeRenderingFinished(start.elapsed(), 1);
- mFile.close();
- fileWritten = true;
- qDebug() << "File written.";
- }
- } else {
- qDebug() << "File already written.";
- }
-#endif
return spectrum;
} else {
const uint topDist = m_innerScopeRect.top() - m_scopeRect.top();
const uint leftDist = m_innerScopeRect.left() - m_scopeRect.left();
const uint dbDiff = ceil((float)minDistY/m_innerScopeRect.height() * (m_dBmax-m_dBmin));
+ const int mouseX = m_mousePos.x() - m_innerScopeRect.left();
+ const int mouseY = m_mousePos.y() - m_innerScopeRect.top();
QImage hud(m_scopeRect.size(), QImage::Format_ARGB32);
hud.fill(qRgba(0,0,0,0));
int x = 0;
const int rightBorder = leftDist + m_innerScopeRect.width()-1;
y = topDist + m_innerScopeRect.height() + textDistY;
- for (uint hz = 0; x <= rightBorder; hz += hzDiff) {
- davinci.setPen(AbstractScopeWidget::penLight);
+ for (int hz = 0; x <= rightBorder; hz += hzDiff) {
+ davinci.setPen(AbstractScopeWidget::penLighter);
x = leftDist + m_innerScopeRect.width() * ((float)hz)/m_freqMax;
if (x <= rightBorder) {
}
}
+ if (m_aTrackMouse->isChecked() && m_mouseWithinWidget && mouseX < m_innerScopeRect.width()-1) {
+ davinci.setPen(AbstractScopeWidget::penThin);
+
+ x = leftDist + mouseX;
+
+ float db = 0;
+ float freq = ((float) mouseX)/(m_innerScopeRect.width()-1) * m_freqMax;
+ bool drawDb = false;
+
+ m_lastFFTLock.acquire();
+ // We need to test whether the mouse is inside the widget
+ // because the position could already have changed in the meantime (-> crash)
+ if (m_lastFFT.size() > 0 && mouseX >= 0 && mouseX < m_innerScopeRect.width()) {
+ uint right = ((float) m_freqMax)/(m_freq/2) * (m_lastFFT.size() - 1);
+ QVector<float> dbMap = FFTTools::interpolatePeakPreserving(m_lastFFT, m_innerScopeRect.width(), 0, right, -120);
+
+ db = dbMap[mouseX];
+ y = topDist + m_innerScopeRect.height()-1 - (dbMap[mouseX] - m_dBmin) / (m_dBmax-m_dBmin) * (m_innerScopeRect.height()-1);
+
+ if (y < (int)topDist + m_innerScopeRect.height()-1) {
+ drawDb = true;
+ davinci.drawLine(x, y, leftDist + m_innerScopeRect.width()-1, y);
+ }
+ } else {
+ y = topDist + mouseY;
+ }
+ m_lastFFTLock.release();
+
+ if (y > (int)topDist + mouseY) {
+ y = topDist+ mouseY;
+ }
+ davinci.drawLine(x, y, x, topDist + m_innerScopeRect.height()-1);
+
+ if (drawDb) {
+ QPoint dist(20, -20);
+ QRect rect(
+ leftDist + mouseX + dist.x(),
+ topDist + mouseY + dist.y(),
+ 100,
+ 40
+ );
+ if (rect.right() > (int)leftDist + m_innerScopeRect.width()-1) {
+ // Mirror the rectangle at the y axis to keep it inside the widget
+ rect = QRect(
+ rect.topLeft() - QPoint(rect.width() + 2*dist.x(), 0),
+ rect.size());
+ }
+
+ QRect textRect(
+ rect.topLeft() + QPoint(12, 4),
+ rect.size()
+ );
+
+ davinci.fillRect(rect, AbstractScopeWidget::penBackground.brush());
+ davinci.setPen(AbstractScopeWidget::penLighter);
+ davinci.drawRect(rect);
+ davinci.drawText(textRect, QString(
+ i18n("%1 dB", QString("%1").arg(db, 0, 'f', 2))
+ + "\n"
+ + i18n("%1 kHz", QString("%1").arg(freq/1000, 0, 'f', 2))));
+ }
+
+ }
+
emit signalHUDRenderingFinished(start.elapsed(), 1);
return hud;
///// EVENTS /////
-void AudioSpectrum::mouseMoveEvent(QMouseEvent *event)
+void AudioSpectrum::handleMouseDrag(const QPoint movement, const RescaleDirection rescaleDirection, const Qt::KeyboardModifiers rescaleModifiers)
{
- QPoint movement = event->pos()-m_rescaleStartPoint;
-
- if (m_rescaleActive) {
- if (m_rescalePropertiesLocked) {
- // Direction is known, now adjust parameters
-
- // Reset the starting point to make the next moveEvent relative to the current one
- m_rescaleStartPoint = event->pos();
-
-
- if (!m_rescaleFirstRescaleDone) {
- // We have just learned the desired direction; Normalize the movement to one pixel
- // to avoid a jump by m_rescaleMinDist
-
- if (movement.x() != 0) {
- movement.setX(movement.x() / abs(movement.x()));
- }
- if (movement.y() != 0) {
- movement.setY(movement.y() / abs(movement.y()));
- }
-
- m_rescaleFirstRescaleDone = true;
- }
-
- if (m_rescaleClockDirection == AudioSpectrum::North) {
- // Nort-South direction: Adjust the dB scale
+ if (rescaleDirection == North) {
+ // Nort-South direction: Adjust the dB scale
- if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
+ if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
- // By default adjust the min dB value
- m_dBmin += movement.y();
+ // By default adjust the min dB value
+ m_dBmin += movement.y();
- } else {
+ } else {
- // Adjust max dB value if Shift is pressed.
- m_dBmax += movement.y();
+ // Adjust max dB value if Shift is pressed.
+ m_dBmax += movement.y();
- }
+ }
- // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
- // 0 is the upper bound, everything below -70 dB is most likely noise
+ // Ensure the dB values lie in [-100, 0] (or rather [MIN_DB_VALUE, 0])
+ // 0 is the upper bound, everything below -70 dB is most likely noise
+ if (m_dBmax > 0) {
+ m_dBmax = 0;
+ }
+ if (m_dBmin < MIN_DB_VALUE) {
+ m_dBmin = MIN_DB_VALUE;
+ }
+ // Ensure there is at least 6 dB between the minimum and the maximum value;
+ // lower values hardly make sense
+ if (m_dBmax - m_dBmin < 6) {
+ if ((rescaleModifiers & Qt::ShiftModifier) == 0) {
+ // min was adjusted; Try to adjust the max value to maintain the
+ // minimum dB difference of 6 dB
+ m_dBmax = m_dBmin + 6;
if (m_dBmax > 0) {
m_dBmax = 0;
+ m_dBmin = -6;
}
+ } else {
+ // max was adjusted, adjust min
+ m_dBmin = m_dBmax - 6;
if (m_dBmin < MIN_DB_VALUE) {
m_dBmin = MIN_DB_VALUE;
+ m_dBmax = MIN_DB_VALUE+6;
}
- // Ensure there is at least 6 dB between the minimum and the maximum value;
- // lower values hardly make sense
- if (m_dBmax - m_dBmin < 6) {
- if ((m_rescaleModifiers & Qt::ShiftModifier) == 0) {
- // min was adjusted; Try to adjust the max value to maintain the
- // minimum dB difference of 6 dB
- m_dBmax = m_dBmin + 6;
- if (m_dBmax > 0) {
- m_dBmax = 0;
- m_dBmin = -6;
- }
- } else {
- // max was adjusted, adjust min
- m_dBmin = m_dBmax - 6;
- if (m_dBmin < MIN_DB_VALUE) {
- m_dBmin = MIN_DB_VALUE;
- m_dBmax = MIN_DB_VALUE+6;
- }
- }
- }
-
- forceUpdateHUD();
- forceUpdateScope();
-
- } else if (m_rescaleClockDirection == AudioSpectrum::East) {
- // East-West direction: Adjust the maximum frequency
- m_freqMax -= 100*movement.x();
- if (m_freqMax < MIN_FREQ_VALUE) {
- m_freqMax = MIN_FREQ_VALUE;
- }
- if (m_freqMax > MAX_FREQ_VALUE) {
- m_freqMax = MAX_FREQ_VALUE;
- }
- m_customFreq = true;
-
- forceUpdateHUD();
- forceUpdateScope();
}
+ }
+ forceUpdateHUD();
+ forceUpdateScope();
- } else {
- // Detect the movement direction here.
- // This algorithm relies on the aspect ratio of dy/dx (size and signum).
- if (movement.manhattanLength() > m_rescaleMinDist) {
- float diff = ((float) movement.y())/movement.x();
-
- if (abs(diff) > m_rescaleVerticalThreshold || movement.x() == 0) {
- m_rescaleClockDirection = AudioSpectrum::North;
- } else if (abs(diff) < 1/m_rescaleVerticalThreshold) {
- m_rescaleClockDirection = AudioSpectrum::East;
- } else if (diff < 0) {
- m_rescaleClockDirection = AudioSpectrum::Northeast;
- } else {
- m_rescaleClockDirection = AudioSpectrum::Southeast;
- }
-#ifdef DEBUG_AUDIOSPEC
- qDebug() << "Diff is " << diff << "; chose " << directions[m_rescaleClockDirection] << " as direction";
-#endif
- m_rescalePropertiesLocked = true;
- }
+ } else if (rescaleDirection == East) {
+ // East-West direction: Adjust the maximum frequency
+ m_freqMax -= 100*movement.x();
+ if (m_freqMax < MIN_FREQ_VALUE) {
+ m_freqMax = MIN_FREQ_VALUE;
}
- } else {
- AbstractAudioScopeWidget::mouseMoveEvent(event);
- }
-}
-
-void AudioSpectrum::mousePressEvent(QMouseEvent *event)
-{
- if (event->button() == Qt::LeftButton) {
- // Rescaling mode starts
- m_rescaleActive = true;
- m_rescalePropertiesLocked = false;
- m_rescaleFirstRescaleDone = false;
- m_rescaleStartPoint = event->pos();
- m_rescaleModifiers = event->modifiers();
+ if (m_freqMax > MAX_FREQ_VALUE) {
+ m_freqMax = MAX_FREQ_VALUE;
+ }
+ m_customFreq = true;
- } else {
- AbstractAudioScopeWidget::mousePressEvent(event);
+ forceUpdateHUD();
+ forceUpdateScope();
}
}
-void AudioSpectrum::mouseReleaseEvent(QMouseEvent *event)
-{
- m_rescaleActive = false;
- m_rescalePropertiesLocked = false;
-
- AbstractAudioScopeWidget::mouseReleaseEvent(event);
-}
-
-const QString AudioSpectrum::cfgSignature(const int size)
-{
- return QString("s%1").arg(size);
-}
-
#ifdef DEBUG_AUDIOSPEC
#undef DEBUG_AUDIOSPEC