From d5acc8adc5dee4e5dafffd7ade717216fb8f0549 Mon Sep 17 00:00:00 2001 From: Romain Vimont Date: Wed, 7 Feb 2018 15:50:38 +0100 Subject: [PATCH] Always release output buffer If rotation changed, the dequeued output buffer was never released. Move it to a finally block to avoid the leak. --- .../com/genymobile/scrcpy/ScreenEncoder.java | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java b/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java index 7da2ca2f..c2d61366 100644 --- a/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java +++ b/server/src/main/java/com/genymobile/scrcpy/ScreenEncoder.java @@ -86,21 +86,26 @@ public class ScreenEncoder implements Device.RotationListener { MediaCodec.BufferInfo bufferInfo = new MediaCodec.BufferInfo(); while (!checkRotationChanged() && !eof) { int outputBufferId = codec.dequeueOutputBuffer(bufferInfo, -1); - if (checkRotationChanged()) { - // must restart encoding with new size - break; - } - if (outputBufferId >= 0) { - ByteBuffer outputBuffer = codec.getOutputBuffer(outputBufferId); - while (outputBuffer.hasRemaining()) { - int remaining = outputBuffer.remaining(); - int len = Math.min(buf.length, remaining); - // the outputBuffer is probably direct (it has no underlying array), and LocalSocket does not expose channels, - // so we must copy the data locally to write them manually to the output stream - outputBuffer.get(buf, 0, len); - outputStream.write(buf, 0, len); + try { + if (checkRotationChanged()) { + // must restart encoding with new size + break; + } + if (outputBufferId >= 0) { + ByteBuffer outputBuffer = codec.getOutputBuffer(outputBufferId); + while (outputBuffer.hasRemaining()) { + int remaining = outputBuffer.remaining(); + int len = Math.min(buf.length, remaining); + // the outputBuffer is probably direct (it has no underlying array), and LocalSocket does not expose channels, + // so we must copy the data locally to write them manually to the output stream + outputBuffer.get(buf, 0, len); + outputStream.write(buf, 0, len); + } + } + } finally { + if (outputBufferId >= 0) { + codec.releaseOutputBuffer(outputBufferId, false); } - codec.releaseOutputBuffer(outputBufferId, false); } }