Skip to content

Commit c5c44ee

Browse files
authored
[camera] add custom path ouput to recording (flutter#11774)
This PR introduces the ability to save videos to custom locations, taking into account the limitations and behavior of each platform. Due to platform-specific security restrictions and limitations: * On Android, I was able to save videos directly to `/storage/emulated/0/Download/video.mp4` without issues. * On iOS, I was able to save videos to `On My iPhone -> Camera Example -> Movies`. * On Windows, the behavior is similar to Android. Closes flutter#91680 ## Pre-Review Checklist **Note**: The Flutter team is currently trialing the use of [Gemini Code Assist for GitHub](https://developers.google.com/gemini-code-assist/docs/review-github-code). Comments from the `gemini-code-assist` bot should not be taken as authoritative feedback from the Flutter team. If you find its comments useful you can update your code accordingly, but if you are unsure or disagree with the feedback, please feel free to wait for a Flutter team member's review for guidance on which automated comments should be addressed. [^1]: Regular contributors who have demonstrated familiarity with the repository guidelines only need to comment if the PR is not auto-exempted by repo tooling.
1 parent 7ab8ce1 commit c5c44ee

56 files changed

Lines changed: 844 additions & 126 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎packages/camera/camera_android/CHANGELOG.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1-
## NEXT
1+
## 0.10.12
22

3+
* Adds support for custom video output path in video recording.
34
* Updates minimum supported SDK version to Flutter 3.41/Dart 3.11.
45

56
## 0.10.11+1

‎packages/camera/camera_android/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,13 @@ $ flutter pub add camera_android
1616
when recording a video with sound enabled and trying to play it back, the duration won't be correct and
1717
you will only see the first frame.
1818

19+
## Custom Video Recording Path
20+
21+
Although it is possible to use an absolute path like `/storage/emulated/0/Download/video.mp4`, this is a fragile practice and may fail on many devices or Android versions due to **Scoped Storage** restrictions.
22+
23+
- **Best Practice:** Always use the [path_provider](https://pub.dev/packages/path_provider) package to fetch a safe, writable directory.
24+
- **Recommended Directory:** Use `getTemporaryDirectory()` or `getApplicationDocumentsDirectory()`.
25+
1926
[1]: https://pub.dev/packages/camera
2027
[2]: https://flutter.dev/to/endorsed-federated-plugin
2128
[3]: https://pub.dev/packages/camera_android_camerax

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

Lines changed: 33 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -870,8 +870,9 @@ void unlockAutoFocus() {
870870
dartMessenger.error(flutterResult, errorCode, errorMessage, null));
871871
}
872872

873-
public void startVideoRecording(@Nullable EventChannel imageStreamChannel) {
874-
prepareRecording();
873+
public void startVideoRecording(
874+
@Nullable EventChannel imageStreamChannel, @Nullable String videoOutputPath) {
875+
prepareRecording(videoOutputPath);
875876

876877
if (imageStreamChannel != null) {
877878
setStreamHandler(imageStreamChannel);
@@ -1297,13 +1298,19 @@ public void onError(@NonNull String errorCode, @NonNull String errorMessage) {
12971298
}
12981299

12991300
@VisibleForTesting
1300-
void prepareRecording() {
1301-
final File outputDir = applicationContext.getCacheDir();
1302-
try {
1303-
captureFile = File.createTempFile("REC", ".mp4", outputDir);
1304-
} catch (IOException | SecurityException e) {
1305-
throw new Messages.FlutterError("cannotCreateFile", e.getMessage(), null);
1301+
void prepareRecording(@Nullable String videoOutputPath) {
1302+
if (videoOutputPath != null) {
1303+
validateOutputPath(videoOutputPath);
1304+
captureFile = new File(videoOutputPath);
1305+
} else {
1306+
final File outputDir = applicationContext.getCacheDir();
1307+
try {
1308+
captureFile = File.createTempFile("REC", ".mp4", outputDir);
1309+
} catch (IOException | SecurityException e) {
1310+
throw new Messages.FlutterError("cannotCreateFile", e.getMessage(), null);
1311+
}
13061312
}
1313+
13071314
try {
13081315
prepareMediaRecorder(captureFile.getAbsolutePath());
13091316
} catch (IOException e) {
@@ -1318,6 +1325,24 @@ void prepareRecording() {
13181325
setFpsCameraFeatureForRecording(cameraProperties);
13191326
}
13201327

1328+
private void validateOutputPath(String path) {
1329+
File file = new File(path);
1330+
if (file.isDirectory()) {
1331+
throw new Messages.FlutterError("IOError", "The output path is a directory: " + path, null);
1332+
}
1333+
File parent = file.getParentFile();
1334+
if (parent != null && !parent.exists()) {
1335+
throw new Messages.FlutterError(
1336+
"IOError", "The parent directory does not exist: " + parent.getAbsolutePath(), null);
1337+
}
1338+
1339+
String lowerPath = path.toLowerCase(Locale.ROOT);
1340+
if (!lowerPath.endsWith(".mp4")) {
1341+
throw new Messages.FlutterError(
1342+
"IOError", "Invalid video extension. Supported extensions: .mp4", null);
1343+
}
1344+
}
1345+
13211346
private void setStreamHandler(EventChannel imageStreamChannel) {
13221347
imageStreamChannel.setStreamHandler(
13231348
new EventChannel.StreamHandler() {

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,8 +175,8 @@ public void takePicture(@NonNull Messages.Result<String> result) {
175175
}
176176

177177
@Override
178-
public void startVideoRecording(@NonNull Boolean enableStream) {
179-
camera.startVideoRecording(enableStream ? imageStreamChannel : null);
178+
public void startVideoRecording(@NonNull Boolean enableStream, @Nullable String videoOutputPath) {
179+
camera.startVideoRecording(enableStream ? imageStreamChannel : null, videoOutputPath);
180180
}
181181

182182
@NonNull

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1229,7 +1229,7 @@ void create(
12291229
void takePicture(@NonNull Result<String> result);
12301230

12311231
/** Starts recording a video on the camera with the given ID. */
1232-
void startVideoRecording(@NonNull Boolean enableStream);
1232+
void startVideoRecording(@NonNull Boolean enableStream, @Nullable String videoOutputPath);
12331233

12341234
/**
12351235
* Ends video recording on the camera with the given ID and returns the path to the resulting
@@ -1524,8 +1524,9 @@ public void error(Throwable error) {
15241524
ArrayList<Object> wrapped = new ArrayList<>();
15251525
ArrayList<Object> args = (ArrayList<Object>) message;
15261526
Boolean enableStreamArg = (Boolean) args.get(0);
1527+
String videoOutputPathArg = (String) args.get(1);
15271528
try {
1528-
api.startVideoRecording(enableStreamArg);
1529+
api.startVideoRecording(enableStreamArg, videoOutputPathArg);
15291530
wrapped.add(0, null);
15301531
} catch (Throwable exception) {
15311532
wrapped = wrapError(exception);

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

Lines changed: 115 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
5454
import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature;
5555
import io.flutter.plugins.camera.media.ImageStreamReader;
56+
import io.flutter.plugins.camera.media.MediaRecorderBuilder;
5657
import io.flutter.view.TextureRegistry;
5758
import java.io.Closeable;
5859
import java.io.File;
@@ -207,6 +208,14 @@ public void before() {
207208

208209
camera.captureSession = mockCaptureSession;
209210
camera.previewRequestBuilder = mockPreviewRequestBuilder;
211+
212+
final SensorOrientationFeature mockSensorOrientationFeature =
213+
mockCameraFeatureFactory.createSensorOrientationFeature(
214+
mockCameraProperties, mockActivity, mockDartMessenger);
215+
final DeviceOrientationManager mockDeviceOrientationManager =
216+
mock(DeviceOrientationManager.class);
217+
when(mockSensorOrientationFeature.getDeviceOrientationManager())
218+
.thenReturn(mockDeviceOrientationManager);
210219
}
211220

212221
@After
@@ -712,6 +721,109 @@ public void resumeVideoRecording_shouldCallPauseWhenRecording() {
712721
verify(mockMediaRecorder, times(1)).resume();
713722
}
714723

724+
@Test
725+
public void startVideoRecording_usesCustomPath() throws IOException, CameraAccessException {
726+
final String customPath =
727+
new File(System.getProperty("java.io.tmpdir"), "custom_video.mp4").getAbsolutePath();
728+
final MediaRecorder mockMediaRecorder = mock(MediaRecorder.class);
729+
730+
final ArrayList<CaptureRequest.Builder> mockRequestBuilders = new ArrayList<>();
731+
CaptureRequest.Builder mockRequestBuilder = mock(CaptureRequest.Builder.class);
732+
mockRequestBuilders.add(mockRequestBuilder);
733+
final SurfaceTexture mockSurfaceTexture = mock(SurfaceTexture.class);
734+
final Size mockSize = mock(Size.class);
735+
final ImageReader mockPictureImageReader = mock(ImageReader.class);
736+
camera.pictureImageReader = mockPictureImageReader;
737+
final CameraDeviceWrapper fakeCamera =
738+
new FakeCameraDeviceWrapper(mockRequestBuilders, mockCaptureSession);
739+
740+
camera.cameraDevice = fakeCamera;
741+
742+
TextureRegistry.SurfaceTextureEntry cameraFlutterTexture = camera.flutterTexture;
743+
ResolutionFeature resolutionFeature = mockCameraFeatureFactory.mockResolutionFeature;
744+
745+
assertNotNull(cameraFlutterTexture);
746+
when(cameraFlutterTexture.surfaceTexture()).thenReturn(mockSurfaceTexture);
747+
748+
assertNotNull(resolutionFeature);
749+
when(resolutionFeature.getPreviewSize()).thenReturn(mockSize);
750+
751+
try (MockedConstruction<MediaRecorderBuilder> mockedBuilder =
752+
Mockito.mockConstruction(
753+
MediaRecorderBuilder.class,
754+
(mock, context) -> {
755+
MediaRecorderBuilder.RecordingParameters params =
756+
(MediaRecorderBuilder.RecordingParameters) context.arguments().get(1);
757+
assertEquals(customPath, params.outputFilePath);
758+
when(mock.setEnableAudio(anyBoolean())).thenReturn(mock);
759+
when(mock.setMediaOrientation(anyInt())).thenReturn(mock);
760+
when(mock.build()).thenReturn(mockMediaRecorder);
761+
})) {
762+
763+
camera.startVideoRecording(null, customPath);
764+
765+
assertEquals(1, mockedBuilder.constructed().size());
766+
}
767+
}
768+
769+
@SuppressWarnings("try")
770+
@Test
771+
public void startVideoRecording_errorsOnInvalidPath() throws IOException, CameraAccessException {
772+
final String invalidPath = "/non/existent/path.mp4";
773+
774+
try (MockedConstruction<MediaRecorderBuilder> mockedBuilder =
775+
Mockito.mockConstruction(
776+
MediaRecorderBuilder.class,
777+
(mock, context) -> {
778+
when(mock.setEnableAudio(anyBoolean())).thenReturn(mock);
779+
when(mock.setMediaOrientation(anyInt())).thenReturn(mock);
780+
when(mock.build()).thenThrow(new IOException("Invalid path"));
781+
})) {
782+
783+
Messages.FlutterError error =
784+
assertThrows(
785+
Messages.FlutterError.class,
786+
() -> {
787+
camera.startVideoRecording(null, invalidPath);
788+
});
789+
// Assert the IOError from validateOutputPath which is thrown prior to building.
790+
assertEquals("IOError", error.code);
791+
}
792+
}
793+
794+
@Test
795+
public void startVideoRecording_errorsOnDirectoryPath() {
796+
Messages.FlutterError error =
797+
assertThrows(
798+
Messages.FlutterError.class,
799+
() -> {
800+
camera.startVideoRecording(null, "/");
801+
});
802+
assertEquals("IOError", error.code);
803+
}
804+
805+
@Test
806+
public void startVideoRecording_errorsOnNonExistentParentPath() {
807+
Messages.FlutterError error =
808+
assertThrows(
809+
Messages.FlutterError.class,
810+
() -> {
811+
camera.startVideoRecording(null, "/non/existent/parent/file.mp4");
812+
});
813+
assertEquals("IOError", error.code);
814+
}
815+
816+
@Test
817+
public void startVideoRecording_errorsOnInvalidExtension() {
818+
Messages.FlutterError error =
819+
assertThrows(
820+
Messages.FlutterError.class,
821+
() -> {
822+
camera.startVideoRecording(null, "file.txt");
823+
});
824+
assertEquals("IOError", error.code);
825+
}
826+
715827
@Test
716828
public void setDescriptionWhileRecording_errorsWhenUnsupported() {
717829
MediaRecorder mockMediaRecorder = mock(MediaRecorder.class);
@@ -940,9 +1052,9 @@ public void startVideoRecording_shouldPullStreamsFromMediaRecorderAndImageReader
9401052

9411053
when(cameraFlutterTexture.surfaceTexture()).thenReturn(mockSurfaceTexture);
9421054
when(resolutionFeature.getPreviewSize()).thenReturn(mockSize);
943-
doNothing().when(cameraSpy).prepareRecording();
1055+
doNothing().when(cameraSpy).prepareRecording(any());
9441056

945-
cameraSpy.startVideoRecording(null);
1057+
cameraSpy.startVideoRecording(null, null);
9461058
verify(mockMediaRecorder, times(1))
9471059
.getSurface(); // stream pulled from media recorder's surface.
9481060
verify(
@@ -1362,7 +1474,7 @@ public void startVideoRecording_shouldApplySettingsToMediaRecorder()
13621474
assertNotNull(resolutionFeature);
13631475
when(resolutionFeature.getPreviewSize()).thenReturn(mockSize);
13641476

1365-
camera.startVideoRecording(null);
1477+
camera.startVideoRecording(null, null);
13661478

13671479
// region Check that FPS parameter affects AE range at which the camera captures frames.
13681480
assertEquals(camera.cameraFeatures.getFpsRange().getValue().getLower(), Integer.valueOf(fps));

‎packages/camera/camera_android/example/lib/camera_controller.dart‎

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -315,9 +315,26 @@ class CameraController extends ValueNotifier<CameraValue> {
315315
///
316316
/// The video is returned as a [XFile] after calling [stopVideoRecording].
317317
/// Throws a [CameraException] if the capture fails.
318-
Future<void> startVideoRecording({void Function(CameraImageData image)? streamCallback}) async {
318+
Future<void> startVideoRecording({
319+
void Function(CameraImageData image)? streamCallback,
320+
String? videoOutputPath,
321+
}) async {
322+
if (videoOutputPath != null) {
323+
final String lowerPath = videoOutputPath.toLowerCase();
324+
if (!lowerPath.endsWith('.mp4')) {
325+
throw CameraException(
326+
'InvalidFilePath',
327+
'Invalid video extension. Supported extensions: .mp4',
328+
);
329+
}
330+
}
331+
319332
await CameraPlatform.instance.startVideoCapturing(
320-
VideoCaptureOptions(_cameraId, streamCallback: streamCallback),
333+
VideoCaptureOptions(
334+
_cameraId,
335+
streamCallback: streamCallback,
336+
videoOutputPath: videoOutputPath,
337+
),
321338
);
322339
value = value.copyWith(
323340
isRecordingVideo: true,

‎packages/camera/camera_android/example/pubspec.yaml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ dependencies:
1414
# The example app is bundled with the plugin so we use a path dependency on
1515
# the parent directory to use the current plugin's version.
1616
path: ../
17-
camera_platform_interface: ^2.13.0
17+
camera_platform_interface: ^2.14.0
1818
flutter:
1919
sdk: flutter
2020
path_provider: ^2.0.0

‎packages/camera/camera_android/lib/src/android_camera.dart‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -186,14 +186,21 @@ class AndroidCamera extends CameraPlatform {
186186
Future<void> prepareForVideoRecording() async {}
187187

188188
@override
189-
Future<void> startVideoRecording(int cameraId, {Duration? maxVideoDuration}) async {
189+
Future<void> startVideoRecording(
190+
int cameraId, {
191+
Duration? maxVideoDuration,
192+
String? videoOutputPath,
193+
}) async {
190194
// Ignore maxVideoDuration, as it is unimplemented and deprecated.
191-
return startVideoCapturing(VideoCaptureOptions(cameraId));
195+
return startVideoCapturing(VideoCaptureOptions(cameraId, videoOutputPath: videoOutputPath));
192196
}
193197

194198
@override
195199
Future<void> startVideoCapturing(VideoCaptureOptions options) async {
196-
await _hostApi.startVideoRecording(options.streamCallback != null);
200+
await _hostApi.startVideoRecording(
201+
options.streamCallback != null,
202+
videoOutputPath: options.videoOutputPath,
203+
);
197204

198205
if (options.streamCallback != null) {
199206
_installStreamController().stream.listen(options.streamCallback);

‎packages/camera/camera_android/lib/src/messages.g.dart‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -640,15 +640,18 @@ class CameraApi {
640640
}
641641

642642
/// Starts recording a video on the camera with the given ID.
643-
Future<void> startVideoRecording(bool enableStream) async {
643+
Future<void> startVideoRecording(bool enableStream, {String? videoOutputPath}) async {
644644
final pigeonVar_channelName =
645645
'dev.flutter.pigeon.camera_android.CameraApi.startVideoRecording$pigeonVar_messageChannelSuffix';
646646
final pigeonVar_channel = BasicMessageChannel<Object?>(
647647
pigeonVar_channelName,
648648
pigeonChannelCodec,
649649
binaryMessenger: pigeonVar_binaryMessenger,
650650
);
651-
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[enableStream]);
651+
final Future<Object?> pigeonVar_sendFuture = pigeonVar_channel.send(<Object?>[
652+
enableStream,
653+
videoOutputPath,
654+
]);
652655
final pigeonVar_replyList = await pigeonVar_sendFuture as List<Object?>?;
653656

654657
_extractReplyValueOrThrow(pigeonVar_replyList, pigeonVar_channelName, isNullValid: true);

0 commit comments

Comments
 (0)