Skip to content
This repository was archived by the owner on Feb 22, 2023. It is now read-only.

Draft: [camera_android] Add NV21 as an image stream format #6985

Closed
wants to merge 37 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
37be5c5
Fix padding issue
acoutts Jan 12, 2023
45d2c58
New approach that is more efficient
acoutts Jan 13, 2023
d2492c8
Refactored image reader to enable testing
acoutts Jan 13, 2023
bd55965
Added tests for image stream reader
acoutts Jan 17, 2023
88079a9
Added tests for buffer trimming
acoutts Jan 17, 2023
fee7979
Formatter
acoutts Jan 17, 2023
f0f0640
Bump pubspec version
acoutts Jan 17, 2023
df99b02
Optimize imports
acoutts Jan 17, 2023
90b2993
Cleanup
acoutts Jan 17, 2023
f5c7f8f
Imports cleanup
acoutts Jan 17, 2023
fd858eb
Imports
acoutts Jan 17, 2023
b1f292e
Imports
acoutts Jan 17, 2023
e6e1f58
Update Camera.java
acoutts Jan 17, 2023
800878f
Update CameraRegionUtils.java
acoutts Jan 17, 2023
56995bb
Update ImageStreamReader.java
acoutts Jan 17, 2023
5efd3e6
Format imports on tests
acoutts Jan 17, 2023
6667183
Formatters
acoutts Jan 18, 2023
b7dec7f
Licenses
acoutts Jan 18, 2023
0b8d812
Merge remote-tracking branch 'upstream/main' into fix-handle-padding
acoutts Jan 18, 2023
ce2a3b9
Added support for NV21 streaming on android as a new image format
acoutts Jan 20, 2023
404a954
Remove unused parameter
acoutts Jan 20, 2023
3ec602e
Add NV21 type conversion
acoutts Jan 20, 2023
a010585
Add legacy code path for nv21 to camera package
acoutts Jan 22, 2023
8bd8710
Clean up log messages
acoutts Feb 17, 2023
7b7708b
Formatters
acoutts Feb 17, 2023
d18a997
Dependency overrides as per contributing guidelines
acoutts Feb 17, 2023
37fa30d
Fix tests for image stream reader
acoutts Feb 17, 2023
c4c1719
Test cleanup
acoutts Feb 17, 2023
bf18e06
Added tests for removing padding
acoutts Feb 17, 2023
628a16a
Formatter
acoutts Feb 17, 2023
0ddc5d4
Merge remote-tracking branch 'upstream/main' into fix-handle-padding
acoutts Feb 17, 2023
651d202
Update CHANGELOG.md
acoutts Feb 17, 2023
cbfb447
Changelogs
acoutts Feb 17, 2023
1d1ecbf
Update CHANGELOG.md
acoutts Feb 17, 2023
804ddc7
Update ImageStreamReader.java
acoutts Feb 17, 2023
5a10847
Comments
acoutts Feb 17, 2023
198c55d
comments
acoutts Feb 17, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/camera/camera/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
## 0.10.4
* Adds NV21 as an image streaming option for Android.

## 0.10.3

* Adds back use of Optional type.
Expand Down
7 changes: 7 additions & 0 deletions packages/camera/camera/example/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,3 +30,10 @@ dev_dependencies:

flutter:
uses-material-design: true

# FOR TESTING ONLY. DO NOT MERGE.
dependency_overrides:
camera_android:
path: ../../../camera/camera_android
camera_platform_interface:
path: ../../../camera/camera_platform_interface
3 changes: 3 additions & 0 deletions packages/camera/camera/lib/src/camera_image.dart
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ ImageFormatGroup _asImageFormatGroup(dynamic rawFormat) {
// android.graphics.ImageFormat.JPEG
case 256:
return ImageFormatGroup.jpeg;
// android.graphics.ImageFormat.NV21
case 17:
return ImageFormatGroup.nv21;
}
}

Expand Down
9 changes: 8 additions & 1 deletion packages/camera/camera/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ description: A Flutter plugin for controlling the camera. Supports previewing
Dart.
repository: https://github.com/flutter/plugins/tree/main/packages/camera/camera
issue_tracker: https://github.com/flutter/flutter/issues?q=is%3Aissue+is%3Aopen+label%3A%22p%3A+camera%22
version: 0.10.3
version: 0.10.4

environment:
sdk: ">=2.14.0 <3.0.0"
Expand Down Expand Up @@ -38,3 +38,10 @@ dev_dependencies:
mockito: ^5.0.0
plugin_platform_interface: ^2.0.0
video_player: ^2.0.0

# FOR TESTING ONLY. DO NOT MERGE.
dependency_overrides:
camera_android:
path: ../../camera/camera_android
camera_platform_interface:
path: ../../camera/camera_platform_interface
5 changes: 5 additions & 0 deletions packages/camera/camera_android/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
## 0.10.5

* Adds support for NV21 as a new streaming format in Android which includes correct handling of image padding when present.


## 0.10.4

* Temporarily fixes issue with requested video profiles being null by falling back to deprecated behavior in that case.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import android.hardware.camera2.params.SessionConfiguration;
import android.media.CamcorderProfile;
import android.media.EncoderProfiles;
import android.media.Image;
import android.media.ImageReader;
import android.media.MediaRecorder;
import android.os.Build;
Expand Down Expand Up @@ -59,19 +58,18 @@
import io.flutter.plugins.camera.features.sensororientation.DeviceOrientationManager;
import io.flutter.plugins.camera.features.sensororientation.SensorOrientationFeature;
import io.flutter.plugins.camera.features.zoomlevel.ZoomLevelFeature;
import io.flutter.plugins.camera.media.ImageStreamReader;
import io.flutter.plugins.camera.media.MediaRecorderBuilder;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import io.flutter.plugins.camera.types.CaptureTimeoutsWrapper;
import io.flutter.view.TextureRegistry.SurfaceTextureEntry;
import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Executors;

@FunctionalInterface
Expand Down Expand Up @@ -109,6 +107,7 @@ class Camera
supportedImageFormats = new HashMap<>();
supportedImageFormats.put("yuv420", ImageFormat.YUV_420_888);
supportedImageFormats.put("jpeg", ImageFormat.JPEG);
supportedImageFormats.put("nv21", ImageFormat.NV21);
}

/**
Expand All @@ -135,7 +134,7 @@ class Camera
private CameraDeviceWrapper cameraDevice;
private CameraCaptureSession captureSession;
private ImageReader pictureImageReader;
private ImageReader imageStreamReader;
private ImageStreamReader imageStreamReader;
/** {@link CaptureRequest.Builder} for the camera preview */
private CaptureRequest.Builder previewRequestBuilder;

Expand Down Expand Up @@ -307,7 +306,7 @@ public void open(String imageFormatGroup) throws CameraAccessException {
imageFormat = ImageFormat.YUV_420_888;
}
imageStreamReader =
ImageReader.newInstance(
new ImageStreamReader(
resolutionFeature.getPreviewSize().getWidth(),
resolutionFeature.getPreviewSize().getHeight(),
imageFormat,
Expand Down Expand Up @@ -1143,49 +1142,13 @@ public void onListen(Object o, EventChannel.EventSink imageStreamSink) {

@Override
public void onCancel(Object o) {
imageStreamReader.setOnImageAvailableListener(null, backgroundHandler);
imageStreamReader.removeListener(backgroundHandler);
}
});
}

private void setImageStreamImageAvailableListener(final EventChannel.EventSink imageStreamSink) {
imageStreamReader.setOnImageAvailableListener(
reader -> {
Image img = reader.acquireNextImage();
// Use acquireNextImage since image reader is only for one image.
if (img == null) return;

List<Map<String, Object>> planes = new ArrayList<>();
for (Image.Plane plane : img.getPlanes()) {
ByteBuffer buffer = plane.getBuffer();

byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes, 0, bytes.length);

Map<String, Object> planeBuffer = new HashMap<>();
planeBuffer.put("bytesPerRow", plane.getRowStride());
planeBuffer.put("bytesPerPixel", plane.getPixelStride());
planeBuffer.put("bytes", bytes);

planes.add(planeBuffer);
}

Map<String, Object> imageBuffer = new HashMap<>();
imageBuffer.put("width", img.getWidth());
imageBuffer.put("height", img.getHeight());
imageBuffer.put("format", img.getFormat());
imageBuffer.put("planes", planes);
imageBuffer.put("lensAperture", this.captureProps.getLastLensAperture());
imageBuffer.put("sensorExposureTime", this.captureProps.getLastSensorExposureTime());
Integer sensorSensitivity = this.captureProps.getLastSensorSensitivity();
imageBuffer.put(
"sensorSensitivity", sensorSensitivity == null ? null : (double) sensorSensitivity);

final Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> imageStreamSink.success(imageBuffer));
img.close();
},
backgroundHandler);
imageStreamReader.subscribeListener(this.captureProps, imageStreamSink, backgroundHandler);
}

private void closeCaptureSession() {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
// Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package io.flutter.plugins.camera.media;

import android.graphics.ImageFormat;
import android.media.Image;
import android.media.ImageReader;
import android.os.Handler;
import android.os.Looper;
import android.view.Surface;
import androidx.annotation.NonNull;
import androidx.annotation.VisibleForTesting;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugins.camera.types.CameraCaptureProperties;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

// Wraps an ImageReader to allow for testing of the image handler.
public class ImageStreamReader {

/**
* The image format we are going to send back to dart. Usually it's the same as streamImageFormat
* but in the case of NV21 we will actually request YUV frames but convert it to NV21 before
* sending to dart.
*/
private final int dartImageFormat;

private final ImageReader imageReader;
private final ImageStreamReaderUtils imageStreamReaderUtils;

/**
* Creates a new instance of the {@link ImageStreamReader}.
*
* @param imageReader is the image reader that will receive frames
* @param imageStreamReaderUtils is an instance of {@link ImageStreamReaderUtils}
*/
@VisibleForTesting
public ImageStreamReader(
ImageReader imageReader, int dartImageFormat, ImageStreamReaderUtils imageStreamReaderUtils) {
this.imageReader = imageReader;
this.dartImageFormat = dartImageFormat;
this.imageStreamReaderUtils = imageStreamReaderUtils;
}

/**
* Creates a new instance of the {@link ImageStreamReader}.
*
* @param width is the image width
* @param height is the image height
* @param imageFormat is the {@link ImageFormat} that should be returned to dart.
* @param maxImages is how many images can be acquired at one time, usually 1.
*/
public ImageStreamReader(int width, int height, int imageFormat, int maxImages) {
this.dartImageFormat = imageFormat;
this.imageReader =
ImageReader.newInstance(width, height, computeStreamImageFormat(imageFormat), maxImages);
this.imageStreamReaderUtils = new ImageStreamReaderUtils();
}

/**
* Returns the image format to stream based on a requested input format. Usually it's the same
* except when dart is requesting NV21. In that case we stream YUV420 and process it into NV21
* before sending the frames over.
*
* @param dartImageFormat is the image format dart is requesting.
* @return the image format that should be streamed from the camera.
*/
@VisibleForTesting
public static int computeStreamImageFormat(int dartImageFormat) {
if (dartImageFormat == ImageFormat.NV21) {
return ImageFormat.YUV_420_888;
} else {
return dartImageFormat;
}
}

/**
* Processes a new frame (image) from the image reader and send the frame to Dart.
*
* @param image is the image which needs processed as an {@link Image}
* @param captureProps is the capture props from the camera class as {@link
* CameraCaptureProperties}
* @param imageStreamSink is the image stream sink from dart as a dart {@link
* EventChannel.EventSink}
*/
@VisibleForTesting
public void onImageAvailable(
@NonNull Image image,
CameraCaptureProperties captureProps,
EventChannel.EventSink imageStreamSink) {
try {
Map<String, Object> imageBuffer = new HashMap<>();

// Get plane data ready
if (dartImageFormat == ImageFormat.NV21) {
imageBuffer.put("planes", parsePlanesForNv21(image));
} else {
imageBuffer.put("planes", parsePlanesForYuvOrJpeg(image));
}

imageBuffer.put("width", image.getWidth());
imageBuffer.put("height", image.getHeight());
imageBuffer.put("format", dartImageFormat);
imageBuffer.put("lensAperture", captureProps.getLastLensAperture());
imageBuffer.put("sensorExposureTime", captureProps.getLastSensorExposureTime());
Integer sensorSensitivity = captureProps.getLastSensorSensitivity();
imageBuffer.put(
"sensorSensitivity", sensorSensitivity == null ? null : (double) sensorSensitivity);

final Handler handler = new Handler(Looper.getMainLooper());
handler.post(() -> imageStreamSink.success(imageBuffer));
image.close();

} catch (IllegalStateException e) {
// Handle "buffer is inaccessible" errors that can happen on some devices from ImageStreamReaderUtils.yuv420ThreePlanesToNV21()
final Handler handler = new Handler(Looper.getMainLooper());
handler.post(
() ->
imageStreamSink.error(
"IllegalStateException",
"Caught IllegalStateException: " + e.getMessage(),
null));
image.close();
}
}

/**
* Given an input image, will return a list of maps suitable to send back to dart where
* each map describes the image plane.
*
* For Yuv / Jpeg, we do no further processing on the frame so we simply send it as-is.
*
* @param image - the image to process.
* @return parsed map describing the image planes to be sent to dart.
*/
public List<Map<String, Object>> parsePlanesForYuvOrJpeg(@NonNull Image image) {
List<Map<String, Object>> planes = new ArrayList<>();

// For YUV420 and JPEG, just send the data as-is for each plane.
for (Image.Plane plane : image.getPlanes()) {
ByteBuffer buffer = plane.getBuffer();

byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes, 0, bytes.length);

Map<String, Object> planeBuffer = new HashMap<>();
planeBuffer.put("bytesPerRow", plane.getRowStride());
planeBuffer.put("bytesPerPixel", plane.getPixelStride());
planeBuffer.put("bytes", bytes);

planes.add(planeBuffer);
}
return planes;
}

/**
* Given an input image, will return a single-plane NV21 image. Assumes YUV420 as an input type.
*
* @param image - the image to process.
* @return parsed map describing the image planes to be sent to dart.
*/
public List<Map<String, Object>> parsePlanesForNv21(@NonNull Image image) {
List<Map<String, Object>> planes = new ArrayList<>();

// We will convert the YUV data to NV21 which is a single-plane image
ByteBuffer bytes =
imageStreamReaderUtils.yuv420ThreePlanesToNV21(
image.getPlanes(), image.getWidth(), image.getHeight());

Map<String, Object> planeBuffer = new HashMap<>();
planeBuffer.put("bytesPerRow", image.getWidth());
planeBuffer.put("bytesPerPixel", 1);
planeBuffer.put("bytes", bytes.array());
planes.add(planeBuffer);
return planes;
}

/** Returns the image reader surface. */
public Surface getSurface() {
return imageReader.getSurface();
}

/**
* Subscribes the image stream reader to handle incoming images using onImageAvailable().
*
* @param captureProps is the capture props from the camera class as {@link
* CameraCaptureProperties}
* @param imageStreamSink is the image stream sink from dart as {@link EventChannel.EventSink}
* @param handler is generally the background handler of the camera as {@link Handler}
*/
public void subscribeListener(
CameraCaptureProperties captureProps,
EventChannel.EventSink imageStreamSink,
Handler handler) {
imageReader.setOnImageAvailableListener(
reader -> {
Image image = reader.acquireNextImage();
if (image == null) return;

onImageAvailable(image, captureProps, imageStreamSink);
},
handler);
}

/**
* Removes the listener from the image reader.
*
* @param handler is generally the background handler of the camera
*/
public void removeListener(Handler handler) {
imageReader.setOnImageAvailableListener(null, handler);
}

/** Closes the image reader. */
public void close() {
imageReader.close();
}
}
Loading