Skip to content

Commit 94fda02

Browse files
committed
[camera_android] Fix stopVideoRecording returning JPEG path during recording
Separate still-image and video capture file fields so takePicture() cannot overwrite the path returned by stopVideoRecording(). Fixes flutter/flutter#192927
1 parent d5ec6db commit 94fda02

4 files changed

Lines changed: 111 additions & 8 deletions

File tree

‎packages/camera/camera_android/CHANGELOG.md‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
## NEXT
2+
3+
* Fixes `stopVideoRecording` returning the JPEG path from `takePicture` when a photo is taken during video recording.
4+
15
## 0.10.12
26

37
* Adds support for custom video output path in video recording.

‎packages/camera/camera_android/android/src/main/java/io/flutter/plugins/camera/Camera.java‎

Lines changed: 25 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,18 @@ class Camera
135135
/** True when the preview is paused. */
136136
@VisibleForTesting boolean pausedPreview;
137137

138-
private File captureFile;
138+
/** File used for still image capture (takePicture). */
139+
@VisibleForTesting
140+
File captureFile;
141+
142+
/**
143+
* File used for video recording. Kept separate from {@link #captureFile} so
144+
* that calling
145+
* takePicture() during an active recording does not overwrite the video path
146+
* returned by
147+
* stopVideoRecording().
148+
*/
149+
private File videoCaptureFile;
139150

140151
/** Holds the current capture timeouts */
141152
private CaptureTimeoutsWrapper captureTimeouts;
@@ -883,7 +894,7 @@ public void startVideoRecording(
883894
startCapture(true, imageStreamChannel != null);
884895
} catch (CameraAccessException e) {
885896
recordingVideo = false;
886-
captureFile = null;
897+
videoCaptureFile = null;
887898
throw new Messages.FlutterError("videoRecordingFailed", e.getMessage(), null);
888899
}
889900
}
@@ -920,8 +931,14 @@ public String stopVideoRecording() {
920931
} catch (CameraAccessException | IllegalStateException | InterruptedException e) {
921932
throw new Messages.FlutterError("videoRecordingFailed", e.getMessage(), null);
922933
}
923-
String path = captureFile.getAbsolutePath();
924-
captureFile = null;
934+
if (videoCaptureFile == null) {
935+
throw new Messages.FlutterError(
936+
"videoRecordingFailed",
937+
"stopVideoRecording was called but videoCaptureFile was null.",
938+
null);
939+
}
940+
String path = videoCaptureFile.getAbsolutePath();
941+
videoCaptureFile = null;
925942
return path;
926943
}
927944

@@ -1301,21 +1318,21 @@ public void onError(@NonNull String errorCode, @NonNull String errorMessage) {
13011318
void prepareRecording(@Nullable String videoOutputPath) {
13021319
if (videoOutputPath != null) {
13031320
validateOutputPath(videoOutputPath);
1304-
captureFile = new File(videoOutputPath);
1321+
videoCaptureFile = new File(videoOutputPath);
13051322
} else {
13061323
final File outputDir = applicationContext.getCacheDir();
13071324
try {
1308-
captureFile = File.createTempFile("REC", ".mp4", outputDir);
1325+
videoCaptureFile = File.createTempFile("REC", ".mp4", outputDir);
13091326
} catch (IOException | SecurityException e) {
13101327
throw new Messages.FlutterError("cannotCreateFile", e.getMessage(), null);
13111328
}
13121329
}
13131330

13141331
try {
1315-
prepareMediaRecorder(captureFile.getAbsolutePath());
1332+
prepareMediaRecorder(videoCaptureFile.getAbsolutePath());
13161333
} catch (IOException e) {
13171334
recordingVideo = false;
1318-
captureFile = null;
1335+
videoCaptureFile = null;
13191336
throw new Messages.FlutterError("videoRecordingFailed", e.getMessage(), null);
13201337
}
13211338
// Re-create autofocus feature so it's using video focus mode now.

‎packages/camera/camera_android/android/src/test/java/io/flutter/plugins/camera/CameraTest.java‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
import static org.junit.Assert.assertFalse;
99
import static org.junit.Assert.assertNotNull;
1010
import static org.junit.Assert.assertThrows;
11+
import static org.junit.Assert.assertTrue;
1112
import static org.mockito.ArgumentMatchers.any;
1213
import static org.mockito.ArgumentMatchers.eq;
1314
import static org.mockito.Mockito.*;
@@ -1518,6 +1519,60 @@ public void pausePreview_doesNotCallStopRepeatingWhenCameraClosed() throws Camer
15181519
verify(mockCaptureSession, never()).stopRepeating();
15191520
}
15201521

1522+
@SuppressWarnings("try")
1523+
@Test
1524+
public void stopVideoRecording_returnsVideoPath_evenIfTakePictureOverwroteCaptureFile()
1525+
throws Exception {
1526+
final String videoPath = new File(System.getProperty("java.io.tmpdir"), "test_video.mp4").getAbsolutePath();
1527+
final String jpegPath = new File(System.getProperty("java.io.tmpdir"), "test_photo.jpg").getAbsolutePath();
1528+
1529+
final MediaRecorder mockMediaRecorder = mock(MediaRecorder.class);
1530+
camera.mediaRecorder = mockMediaRecorder;
1531+
camera.recordingVideo = true;
1532+
camera.captureSession = mockCaptureSession;
1533+
1534+
// Avoid real preview restart work in stopVideoRecording.
1535+
Camera cameraSpy = spy(camera);
1536+
doNothing().when(cameraSpy).startPreview(any());
1537+
1538+
// prepareRecording sets videoCaptureFile to the .mp4 path.
1539+
try (MockedConstruction<MediaRecorderBuilder> mockedBuilder = Mockito.mockConstruction(
1540+
MediaRecorderBuilder.class,
1541+
(mock, context) -> {
1542+
when(mock.setEnableAudio(anyBoolean())).thenReturn(mock);
1543+
when(mock.setMediaOrientation(anyInt())).thenReturn(mock);
1544+
when(mock.build()).thenReturn(mockMediaRecorder);
1545+
})) {
1546+
cameraSpy.prepareRecording(videoPath);
1547+
}
1548+
1549+
// Simulate takePicture() overwriting the shared field with a JPEG path
1550+
// (this is the bug we fixed by introducing videoCaptureFile).
1551+
cameraSpy.captureFile = new File(jpegPath);
1552+
1553+
// Act
1554+
String resultPath = cameraSpy.stopVideoRecording();
1555+
1556+
// Assert: must still be the video path, not the JPEG from takePicture.
1557+
assertEquals(videoPath, resultPath);
1558+
assertFalse(resultPath.endsWith(".jpg"));
1559+
assertTrue(resultPath.endsWith(".mp4"));
1560+
}
1561+
1562+
@Test
1563+
public void stopVideoRecording_throwsWhenVideoCaptureFileIsNull() throws Exception {
1564+
camera.recordingVideo = true;
1565+
camera.mediaRecorder = mock(MediaRecorder.class);
1566+
camera.captureSession = mockCaptureSession;
1567+
1568+
Camera cameraSpy = spy(camera);
1569+
doNothing().when(cameraSpy).startPreview(any());
1570+
1571+
// videoCaptureFile left null
1572+
Messages.FlutterError error = assertThrows(Messages.FlutterError.class, cameraSpy::stopVideoRecording);
1573+
assertEquals("videoRecordingFailed", error.code);
1574+
}
1575+
15211576
/// Allow to use `new android.util.Range(Integer, Integer)`
15221577
private static class RangeConstruction implements Closeable {
15231578
final Map<Range<Integer>, Integer> lowers = new HashMap<>();

‎packages/camera/camera_android/example/integration_test/camera_test.dart‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,5 +398,32 @@ void main() {
398398
expect(lengths[n], greaterThan(0));
399399
}
400400
});
401+
402+
testWidgets('stopVideoRecording returns mp4 after takePicture during recording', (
403+
WidgetTester tester,
404+
) async {
405+
final List<CameraDescription> cameras = await CameraPlatform.instance.availableCameras();
406+
if (cameras.isEmpty) {
407+
return;
408+
}
409+
410+
final controller = CameraController(cameras[0]);
411+
await controller.initialize();
412+
await controller.prepareForVideoRecording();
413+
414+
await controller.startVideoRecording();
415+
await Future<void>.delayed(const Duration(milliseconds: 500));
416+
417+
final XFile photo = await controller.takePicture();
418+
expect(photo.path.toLowerCase(), endsWith('.jpg'));
419+
420+
await Future<void>.delayed(const Duration(seconds: 1));
421+
422+
final XFile video = await controller.stopVideoRecording();
423+
expect(video.path.toLowerCase(), endsWith('.mp4'));
424+
expect(video.path, isNot(equals(photo.path)));
425+
426+
await controller.dispose();
427+
});
401428
});
402429
}

0 commit comments

Comments
 (0)