Skip to content

Commit

Permalink
Fix float to int16_t conversion in resampler
Browse files Browse the repository at this point in the history
The backward conversion int16_t to float in libopenshot has range
(1.0; -1.0], thus conversion -1.0f to int16_t should be secured.

Float values can exceed the (1.0; -1.0) range. This can cause
distortion in audio instead of limiting values  at max/min for the
int16_t.
  • Loading branch information
SuslikV committed Mar 26, 2020
1 parent 54a82ff commit 455b6e9
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/FrameMapper.cpp
Expand Up @@ -785,10 +785,23 @@ void FrameMapper::ResampleMappedAudio(std::shared_ptr<Frame> frame, int64_t orig
// Create a new array (to hold all S16 audio samples for the current queued frames)
int16_t* frame_samples = (int16_t*) av_malloc(sizeof(int16_t)*total_frame_samples);

// Translate audio sample values back to 16 bit integers
for (int s = 0; s < total_frame_samples; s++)
// Translate sample value and copy into buffer
frame_samples[s] = int(frame_samples_float[s] * (1 << 15));
// Translate audio sample values back to 16 bit integers with saturation
float valF;
int16_t conv;
const int16_t max16 = 32767;
const int16_t min16 = -32768;
for (int s = 0; s < total_frame_samples; s++) {
valF = frame_samples_float[s] * (1 << 15);
if (valF > max16)
conv = max16;
else if (valF < min16)
conv = min16;
else
conv = int(valF + 32768.5) - 32768; // +0.5 is for rounding

// Copy into buffer
frame_samples[s] = conv;
}


// Deallocate float array
Expand Down

0 comments on commit 455b6e9

Please sign in to comment.