Skip to content

Commit

Permalink
Fix float to int16_t conversion
Browse files Browse the repository at this point in the history
Float values after mix or gain applied can exceed the (1.0; -1.0)
range. This caused distortion in audio instead of limiting values
at max.
  • Loading branch information
SuslikV committed Mar 16, 2020
1 parent 816118b commit c28a8bf
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions src/FFmpegWriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1525,11 +1525,23 @@ void FFmpegWriter::write_audio_packets(bool is_final) {
// Calculate total samples
total_frame_samples = samples_in_frame * channels_in_frame;

// Translate audio sample values back to 16 bit integers
for (int s = 0; s < total_frame_samples; s++, frame_position++)
// Translate sample value and copy into buffer
all_queued_samples[frame_position] = 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++, frame_position++) {
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
all_queued_samples[frame_position] = conv;
}

// Deallocate float array
delete[] frame_samples_float;
Expand Down

0 comments on commit c28a8bf

Please sign in to comment.