Skip to content

Commit 75f2cf7

Browse files
author
Mikachu2333
committed
fix DCT overflow
manually set smooth arg to fix that
1 parent 4bddc87 commit 75f2cf7

File tree

1 file changed

+27
-1
lines changed
  • src/codecs/mozjpeg/encoder

1 file changed

+27
-1
lines changed

src/codecs/mozjpeg/encoder/mod.rs

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,14 +125,38 @@ impl EncoderTrait for MozJpegEncoder {
125125
let mut comp = mozjpeg::Compress::new(format);
126126

127127
comp.set_size(width, height);
128+
129+
// When using custom quantization tables with very high quality settings (>= 85),
130+
// DCT coefficients can overflow. Instead of reducing quality, we apply smoothing
131+
// to normalize the data and prevent coefficient overflow.
132+
let has_custom_qtables = luma_qtable.is_some() || chroma_qtable.is_some();
133+
let safe_smoothing = if has_custom_qtables && self.options.quality >= 85.0 {
134+
// Apply moderate smoothing to prevent DCT coefficient overflow
135+
// This helps normalize extreme pixel values without reducing quality
136+
let applied_smoothing = if self.options.smoothing > 0 {
137+
self.options.smoothing.max(10)
138+
} else {
139+
10
140+
};
141+
log::warn!(
142+
"High quality ({}) with custom quantization tables detected. \
143+
Applying smoothing ({}) to prevent DCT coefficient overflow.",
144+
self.options.quality,
145+
applied_smoothing
146+
);
147+
applied_smoothing
148+
} else {
149+
self.options.smoothing
150+
};
151+
128152
comp.set_quality(self.options.quality);
129153

130154
if self.options.progressive {
131155
comp.set_progressive_mode();
132156
}
133157

134158
comp.set_optimize_coding(self.options.optimize_coding);
135-
comp.set_smoothing_factor(self.options.smoothing);
159+
comp.set_smoothing_factor(safe_smoothing);
136160
comp.set_color_space(match format {
137161
mozjpeg::ColorSpace::JCS_GRAYSCALE => {
138162
log::warn!("Input colorspace is GRAYSCALE, using GRAYSCALE as output");
@@ -158,6 +182,8 @@ impl EncoderTrait for MozJpegEncoder {
158182
comp.set_chroma_sampling_pixel_sizes((sb, sb), (sb, sb))
159183
}
160184

185+
// Apply custom quantization tables
186+
// Smoothing (applied above) will handle DCT coefficient normalization
161187
if let Some(qtable) = luma_qtable {
162188
comp.set_luma_qtable(qtable)
163189
}

0 commit comments

Comments
 (0)