From 81979e0f29ccbd425158da6c49604550e437ff62 Mon Sep 17 00:00:00 2001 From: Dmitry Pentin Date: Thu, 27 May 2021 19:23:35 +0300 Subject: [PATCH] Improved flush logic after main encode methods run --- .../Components/Encoder/HuffmanScanEncoder.cs | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanScanEncoder.cs b/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanScanEncoder.cs index 571a806982..d694731249 100644 --- a/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanScanEncoder.cs +++ b/src/ImageSharp/Formats/Jpeg/Components/Encoder/HuffmanScanEncoder.cs @@ -108,9 +108,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder } } - // Pad the last byte with 1's. - this.Emit(0x7f, 7); - this.target.Write(this.emitBuffer, 0, this.emitLen); + this.FlushInternalBuffer(); } /// @@ -181,9 +179,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder } } - // Pad the last byte with 1's. - this.Emit(0x7f, 7); - this.target.Write(this.emitBuffer, 0, this.emitLen); + this.FlushInternalBuffer(); } /// @@ -224,9 +220,7 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder } } - // Pad the last byte with 1's. - this.Emit(0x7f, 7); - this.target.Write(this.emitBuffer, 0, this.emitLen); + this.FlushInternalBuffer(); } /// @@ -376,5 +370,25 @@ namespace SixLabors.ImageSharp.Formats.Jpeg.Components.Encoder this.EmitHuff(index, (runLength << 4) | bt); this.Emit(b & ((1 << bt) - 1), bt); } + + /// + /// Writes remaining bytes from internal buffer to the target stream. + /// + /// Pads last byte with 1's if necessary + private void FlushInternalBuffer() + { + // pad last byte with 1's + int padBitsCount = 8 - (this.bitCount % 8); + if (padBitsCount != 0) + { + this.Emit(0xff, padBitsCount); + } + + // flush remaining bytes + if (this.emitLen != 0) + { + this.target.Write(this.emitBuffer, 0, this.emitLen); + } + } } }