Skip to content

Commit

Permalink
fix #271718: clicking noise fix
Browse files Browse the repository at this point in the history
Implemented correct float sample values (from ogg) conversion to short
  • Loading branch information
anatoly-os committed Jun 1, 2018
1 parent 5d3b5e1 commit 209070b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
27 changes: 25 additions & 2 deletions audiofile/audiofile.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ bool AudioFile::open(const QByteArray& b)
idx = 0;
sf = sf_open_virtual(&sfio, SFM_READ, &info, this);
hasInstrument = sf_command(sf, SFC_GET_INSTRUMENT, &inst, sizeof(inst)) == SF_TRUE;

_type = info.format & SF_FORMAT_OGG ? fltp : s16p;
return sf != 0;
}

Expand All @@ -73,7 +73,30 @@ bool AudioFile::open(const QByteArray& b)

sf_count_t AudioFile::readData(short* data, sf_count_t frames)
{
return sf_readf_short(sf, data, frames);
//see https://musescore.org/en/node/22086#comment-83671
//see https://github.com/erikd/libsndfile/issues/16
//this code fixes the bug in libsndfile: float values are not normalized when reading .ogg
//this leads to overflowing signed short values, reverting a sign and clicking noise
sf_count_t resFrames = 0;
if (s16p == _type)
resFrames = sf_readf_short(sf, data, frames);
else {
//read native float values
float* dataF = new float[frames * channels()];
resFrames = sf_readf_float(sf, dataF, frames);
//find the maximum signal value
float maxSignal = 0.f;
for (int i = 0; i < resFrames; ++i) {
if (fabs(dataF[i]) > maxSignal)
maxSignal = dataF[i] > 0 ? dataF[i] : -dataF[i];
}
//convert normilized floats to signed short values
float adjScale = 1.f/maxSignal;
for (int i = 0; i < resFrames; ++i)
data[i] = adjScale * lrintf(dataF[i] * (dataF[i] > 0 ? SHRT_MAX : -SHRT_MIN));
}

return resFrames;
}

//---------------------------------------------------------
Expand Down
6 changes: 6 additions & 0 deletions audiofile/audiofile.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,18 @@
//---------------------------------------------------------

class AudioFile {
enum FormatType
{
s16p,
fltp
};
SF_INFO info;
SNDFILE* sf;
SF_INSTRUMENT inst;
bool hasInstrument;
QByteArray buf; // used during read of Sample
int idx;
FormatType _type;

public:
AudioFile();
Expand Down

0 comments on commit 209070b

Please sign in to comment.