Move mediaCodec.stop() to finally block

This will allow stopping MediaCodec only after the cleanup of other
components which must be performed beforehand.

PR #5455 <https://github.com/Genymobile/scrcpy/pull/5455>
This commit is contained in:
Romain Vimont 2024-11-10 09:00:32 +01:00
parent e226950cfa
commit 904f86152e

View File

@ -86,6 +86,7 @@ public class SurfaceEncoder implements AsyncProcessor {
format.setInteger(MediaFormat.KEY_HEIGHT, size.getHeight()); format.setInteger(MediaFormat.KEY_HEIGHT, size.getHeight());
Surface surface = null; Surface surface = null;
boolean mediaCodecStarted = false;
try { try {
mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE); mediaCodec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);
surface = mediaCodec.createInputSurface(); surface = mediaCodec.createInputSurface();
@ -93,6 +94,7 @@ public class SurfaceEncoder implements AsyncProcessor {
capture.start(surface); capture.start(surface);
mediaCodec.start(); mediaCodec.start();
mediaCodecStarted = true;
// Set the MediaCodec instance to "interrupt" (by signaling an EOS) on reset // Set the MediaCodec instance to "interrupt" (by signaling an EOS) on reset
reset.setRunningMediaCodec(mediaCodec); reset.setRunningMediaCodec(mediaCodec);
@ -108,9 +110,6 @@ public class SurfaceEncoder implements AsyncProcessor {
// The capture might have been closed internally (for example if the camera is disconnected) // The capture might have been closed internally (for example if the camera is disconnected)
alive = !stopped.get() && !capture.isClosed(); alive = !stopped.get() && !capture.isClosed();
} }
// do not call stop() on exception, it would trigger an IllegalStateException
mediaCodec.stop();
} catch (IllegalStateException | IllegalArgumentException e) { } catch (IllegalStateException | IllegalArgumentException e) {
Ln.e("Encoding error: " + e.getClass().getName() + ": " + e.getMessage()); Ln.e("Encoding error: " + e.getClass().getName() + ": " + e.getMessage());
if (!prepareRetry(size)) { if (!prepareRetry(size)) {
@ -119,6 +118,13 @@ public class SurfaceEncoder implements AsyncProcessor {
alive = true; alive = true;
} finally { } finally {
reset.setRunningMediaCodec(null); reset.setRunningMediaCodec(null);
if (mediaCodecStarted) {
try {
mediaCodec.stop();
} catch (IllegalStateException e) {
// ignore (just in case)
}
}
mediaCodec.reset(); mediaCodec.reset();
if (surface != null) { if (surface != null) {
surface.release(); surface.release();