@ -27,6 +27,7 @@ import android.view.SurfaceHolder;
import androidx.annotation.NonNull ;
import androidx.annotation.NonNull ;
import androidx.annotation.Nullable ;
import androidx.annotation.Nullable ;
import androidx.annotation.RequiresApi ;
import androidx.annotation.RequiresApi ;
import androidx.annotation.VisibleForTesting ;
import androidx.annotation.WorkerThread ;
import androidx.annotation.WorkerThread ;
import com.google.android.gms.tasks.Task ;
import com.google.android.gms.tasks.Task ;
@ -81,7 +82,7 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
private static final int FRAME_PROCESSING_FORMAT = ImageFormat . NV21 ;
private static final int FRAME_PROCESSING_FORMAT = ImageFormat . NV21 ;
private static final int FRAME_PROCESSING_INPUT_FORMAT = ImageFormat . YUV_420_888 ;
private static final int FRAME_PROCESSING_INPUT_FORMAT = ImageFormat . YUV_420_888 ;
private static final long METER_TIMEOUT = 2500 ;
@VisibleForTesting static final long METER_TIMEOUT = 2500 ;
private final CameraManager mManager ;
private final CameraManager mManager ;
private String mCameraId ;
private String mCameraId ;
@ -96,17 +97,19 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
private Size mFrameProcessingSize ;
private Size mFrameProcessingSize ;
private ImageReader mFrameProcessingReader ; // need this or the reader surface is collected
private ImageReader mFrameProcessingReader ; // need this or the reader surface is collected
private final WorkerHandler mFrameConversionHandler ;
private final WorkerHandler mFrameConversionHandler ;
private final Object mFrameProcessingImageLock = new Object ( ) ;
private Surface mFrameProcessingSurface ;
private Surface mFrameProcessingSurface ;
// Preview
// Preview
private Surface mPreviewStreamSurface ;
private Surface mPreviewStreamSurface ;
// Video recording
// Video recording
private VideoResult . Stub mFullVideoPendingStub ; // When takeVideo is called, we have to reset the session.
// When takeVideo is called, we restart the session.
private VideoResult . Stub mFullVideoPendingStub ;
// Picture capturing
// Picture capturing
private ImageReader mPictureReader ;
private ImageReader mPictureReader ;
private final boolean mPictureCaptureStopsPreview = false ; // can mak e configurable at some point
private final boolean mPictureCaptureStopsPreview = false ; // can b e configurable at some point
// Actions
// Actions
private final List < Action > mActions = new ArrayList < > ( ) ;
private final List < Action > mActions = new ArrayList < > ( ) ;
@ -135,32 +138,46 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
return value = = null ? fallback : value ;
return value = = null ? fallback : value ;
}
}
@SuppressWarnings ( "DuplicateBranchesInSwitch" )
@NonNull
@NonNull
private CameraException createCameraException ( @NonNull CameraAccessException exception ) {
private CameraException createCameraException ( @NonNull CameraAccessException exception ) {
int reason ;
int reason ;
switch ( exception . getReason ( ) ) {
switch ( exception . getReason ( ) ) {
case CameraAccessException . CAMERA_DISABLED : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ;
case CameraAccessException . CAMERA_DISABLED :
case CameraAccessException . CAMERA_ERROR : reason = CameraException . REASON_DISCONNECTED ; break ;
case CameraAccessException . CAMERA_IN_USE :
case CameraAccessException . CAMERA_DISCONNECTED : reason = CameraException . REASON_DISCONNECTED ; break ;
case CameraAccessException . MAX_CAMERAS_IN_USE : {
case CameraAccessException . CAMERA_IN_USE : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ;
reason = CameraException . REASON_FAILED_TO_CONNECT ;
case CameraAccessException . MAX_CAMERAS_IN_USE : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ;
break ;
default : reason = CameraException . REASON_UNKNOWN ; break ;
}
case CameraAccessException . CAMERA_ERROR :
case CameraAccessException . CAMERA_DISCONNECTED : {
reason = CameraException . REASON_DISCONNECTED ;
break ;
}
default : {
reason = CameraException . REASON_UNKNOWN ;
break ;
}
}
}
return new CameraException ( exception , reason ) ;
return new CameraException ( exception , reason ) ;
}
}
@SuppressWarnings ( "DuplicateBranchesInSwitch" )
@NonNull
@NonNull
private CameraException createCameraException ( int stateCallbackError ) {
private CameraException createCameraException ( int stateCallbackError ) {
int reason ;
int reason ;
switch ( stateCallbackError ) {
switch ( stateCallbackError ) {
case CameraDevice . StateCallback . ERROR_CAMERA_DISABLED : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ; // Device policy
case CameraDevice . StateCallback . ERROR_CAMERA_DISABLED : // Device policy
case CameraDevice . StateCallback . ERROR_CAMERA_DEVICE : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ; // Fatal error
case CameraDevice . StateCallback . ERROR_CAMERA_DEVICE : // Fatal error
case CameraDevice . StateCallback . ERROR_CAMERA_SERVICE : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ; // Fatal error, device might have to be restarted
case CameraDevice . StateCallback . ERROR_CAMERA_SERVICE : // Fatal error, might have to
case CameraDevice . StateCallback . ERROR_CAMERA_IN_USE : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ;
// restart the device
case CameraDevice . StateCallback . ERROR_MAX_CAMERAS_IN_USE : reason = CameraException . REASON_FAILED_TO_CONNECT ; break ;
case CameraDevice . StateCallback . ERROR_CAMERA_IN_USE :
default : reason = CameraException . REASON_UNKNOWN ; break ;
case CameraDevice . StateCallback . ERROR_MAX_CAMERAS_IN_USE : {
reason = CameraException . REASON_FAILED_TO_CONNECT ;
break ;
}
default : {
reason = CameraException . REASON_UNKNOWN ;
break ;
}
}
}
return new CameraException ( reason ) ;
return new CameraException ( reason ) ;
}
}
@ -173,7 +190,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
* /
* /
@SuppressWarnings ( "UnusedReturnValue" )
@SuppressWarnings ( "UnusedReturnValue" )
@NonNull
@NonNull
private CaptureRequest . Builder createRepeatingRequestBuilder ( int template ) throws CameraAccessException {
private CaptureRequest . Builder createRepeatingRequestBuilder ( int template )
throws CameraAccessException {
CaptureRequest . Builder oldBuilder = mRepeatingRequestBuilder ;
CaptureRequest . Builder oldBuilder = mRepeatingRequestBuilder ;
mRepeatingRequestBuilder = mCamera . createCaptureRequest ( template ) ;
mRepeatingRequestBuilder = mCamera . createCaptureRequest ( template ) ;
mRepeatingRequestBuilder . setTag ( template ) ;
mRepeatingRequestBuilder . setTag ( template ) ;
@ -199,8 +217,7 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
}
}
/ * *
/ * *
* Sets up the repeating request builder with default surfaces and extra ones
* Removes default surfaces from the repeating request builder .
* if needed ( like a video recording surface ) .
* /
* /
private void removeRepeatingRequestBuilderSurfaces ( ) {
private void removeRepeatingRequestBuilderSurfaces ( ) {
mRepeatingRequestBuilder . removeTarget ( mPreviewStreamSurface ) ;
mRepeatingRequestBuilder . removeTarget ( mPreviewStreamSurface ) ;
@ -209,17 +226,6 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
}
}
}
}
private void applyRepeatingRequestBuilderAsSingle ( ) {
if ( getPreviewState ( ) = = STATE_STARTED ) {
try {
mSession . capture ( mRepeatingRequestBuilder . build ( ) ,
mRepeatingRequestCallback , null ) ;
} catch ( CameraAccessException e ) {
throw createCameraException ( e ) ;
}
}
}
/ * *
/ * *
* Applies the repeating request builder to the preview , assuming we actually have a preview
* Applies the repeating request builder to the preview , assuming we actually have a preview
* running . Can be called after changing parameters to the builder .
* running . Can be called after changing parameters to the builder .
@ -228,7 +234,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
* it should be set before calling this method , for example by calling
* it should be set before calling this method , for example by calling
* { @link # createRepeatingRequestBuilder ( int ) } .
* { @link # createRepeatingRequestBuilder ( int ) } .
* /
* /
private void applyRepeatingRequestBuilder ( ) {
@SuppressWarnings ( "WeakerAccess" )
protected void applyRepeatingRequestBuilder ( ) {
applyRepeatingRequestBuilder ( true , CameraException . REASON_DISCONNECTED ) ;
applyRepeatingRequestBuilder ( true , CameraException . REASON_DISCONNECTED ) ;
}
}
@ -284,7 +291,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
protected List < Size > getPreviewStreamAvailableSizes ( ) {
protected List < Size > getPreviewStreamAvailableSizes ( ) {
try {
try {
CameraCharacteristics characteristics = mManager . getCameraCharacteristics ( mCameraId ) ;
CameraCharacteristics characteristics = mManager . getCameraCharacteristics ( mCameraId ) ;
StreamConfigurationMap streamMap = characteristics . get ( CameraCharacteristics . SCALER_STREAM_CONFIGURATION_MAP ) ;
StreamConfigurationMap streamMap =
characteristics . get ( CameraCharacteristics . SCALER_STREAM_CONFIGURATION_MAP ) ;
if ( streamMap = = null ) {
if ( streamMap = = null ) {
throw new RuntimeException ( "StreamConfigurationMap is null. Should not happen." ) ;
throw new RuntimeException ( "StreamConfigurationMap is null. Should not happen." ) ;
}
}
@ -309,7 +317,7 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
}
}
@Override
@Override
protected boolean collectCameraInfo ( @NonNull Facing facing ) {
protected final boolean collectCameraInfo ( @NonNull Facing facing ) {
int internalFacing = mMapper . mapFacing ( facing ) ;
int internalFacing = mMapper . mapFacing ( facing ) ;
String [ ] cameraIds = null ;
String [ ] cameraIds = null ;
try {
try {
@ -325,7 +333,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
for ( String cameraId : cameraIds ) {
for ( String cameraId : cameraIds ) {
try {
try {
CameraCharacteristics characteristics = mManager . getCameraCharacteristics ( cameraId ) ;
CameraCharacteristics characteristics = mManager . getCameraCharacteristics ( cameraId ) ;
if ( internalFacing = = readCharacteristic ( characteristics , CameraCharacteristics . LENS_FACING , - 99 ) ) {
if ( internalFacing = = readCharacteristic ( characteristics ,
CameraCharacteristics . LENS_FACING , - 99 ) ) {
mCameraId = cameraId ;
mCameraId = cameraId ;
int sensorOffset = readCharacteristic ( characteristics ,
int sensorOffset = readCharacteristic ( characteristics ,
CameraCharacteristics . SENSOR_ORIENTATION , 0 ) ;
CameraCharacteristics . SENSOR_ORIENTATION , 0 ) ;
@ -372,12 +381,13 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@Override
@Override
public void onDisconnected ( @NonNull CameraDevice camera ) {
public void onDisconnected ( @NonNull CameraDevice camera ) {
// Not sure if this is called INSTEAD of onOpened() or can be called after as well.
// Not sure if this is called INSTEAD of onOpened() or can be called after
// However, using trySetException should address this problem - it will only trigger
// as well. However, using trySetException should address this problem -
// if the task has no result.
// it will only trigger i f the task has no result.
//
//
// Docs say to release this camera instance, however, since we throw an unrecoverable
// Docs say to release this camera instance, however, since we throw an
// CameraException, this will trigger a stop() through the exception handler.
// unrecoverable CameraException, this will trigger a stop() through the
// exception handler.
task . trySetException ( new CameraException ( CameraException . REASON_DISCONNECTED ) ) ;
task . trySetException ( new CameraException ( CameraException . REASON_DISCONNECTED ) ) ;
}
}
@ -463,8 +473,11 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
// 4. FRAME PROCESSING
// 4. FRAME PROCESSING
if ( hasFrameProcessors ( ) ) {
if ( hasFrameProcessors ( ) ) {
// Choose the size.
// Choose the size.
StreamConfigurationMap streamMap = mCameraCharacteristics . get ( CameraCharacteristics . SCALER_STREAM_CONFIGURATION_MAP ) ;
StreamConfigurationMap streamMap = mCameraCharacteristics
if ( streamMap = = null ) throw new RuntimeException ( "StreamConfigurationMap is null. Should not happen." ) ;
. get ( CameraCharacteristics . SCALER_STREAM_CONFIGURATION_MAP ) ;
if ( streamMap = = null ) {
throw new RuntimeException ( "StreamConfigurationMap is null. Should not happen." ) ;
}
android . util . Size [ ] aSizes = streamMap . getOutputSizes ( FRAME_PROCESSING_INPUT_FORMAT ) ;
android . util . Size [ ] aSizes = streamMap . getOutputSizes ( FRAME_PROCESSING_INPUT_FORMAT ) ;
List < Size > sizes = new ArrayList < > ( ) ;
List < Size > sizes = new ArrayList < > ( ) ;
for ( android . util . Size aSize : aSizes ) {
for ( android . util . Size aSize : aSizes ) {
@ -479,7 +492,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
mFrameProcessingSize . getHeight ( ) ,
mFrameProcessingSize . getHeight ( ) ,
FRAME_PROCESSING_INPUT_FORMAT ,
FRAME_PROCESSING_INPUT_FORMAT ,
2 ) ;
2 ) ;
mFrameProcessingReader . setOnImageAvailableListener ( this , mFrameConversionHandler . getHandler ( ) ) ;
mFrameProcessingReader . setOnImageAvailableListener ( this ,
mFrameConversionHandler . getHandler ( ) ) ;
mFrameProcessingSurface = mFrameProcessingReader . getSurface ( ) ;
mFrameProcessingSurface = mFrameProcessingReader . getSurface ( ) ;
outputSurfaces . add ( mFrameProcessingSurface ) ;
outputSurfaces . add ( mFrameProcessingSurface ) ;
} else {
} else {
@ -500,7 +514,7 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@Override
@Override
public void onConfigureFailed ( @NonNull CameraCaptureSession session ) {
public void onConfigureFailed ( @NonNull CameraCaptureSession session ) {
// I would say this should be a library error and as such we throw a Runtime Exception.
// This SHOULD be a library error so we throw a Runtime Exception.
String message = LOG . e ( "onConfigureFailed! Session" , session ) ;
String message = LOG . e ( "onConfigureFailed! Session" , session ) ;
throw new RuntimeException ( message ) ;
throw new RuntimeException ( message ) ;
}
}
@ -529,13 +543,14 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
LOG . i ( "onStartPreview" , "Starting preview." ) ;
LOG . i ( "onStartPreview" , "Starting preview." ) ;
addRepeatingRequestBuilderSurfaces ( ) ;
addRepeatingRequestBuilderSurfaces ( ) ;
applyRepeatingRequestBuilder ( false , CameraException . REASON_FAILED_TO_START_PREVIEW ) ;
applyRepeatingRequestBuilder ( false ,
CameraException . REASON_FAILED_TO_START_PREVIEW ) ;
LOG . i ( "onStartPreview" , "Started preview." ) ;
LOG . i ( "onStartPreview" , "Started preview." ) ;
// Start delayed video if needed.
// Start delayed video if needed.
if ( mFullVideoPendingStub ! = null ) {
if ( mFullVideoPendingStub ! = null ) {
// Do not call takeVideo/onTakeVideo. It will reset some stub parameters that the recorder sets.
// Do not call takeVideo/onTakeVideo. It will reset some stub parameters that
// Also we are posting this so that doTakeVideo sees a started preview.
// the recorder sets. Also we are posting so that doTakeVideo sees a started preview.
LOG . i ( "onStartPreview" , "Posting doTakeVideo call." ) ;
LOG . i ( "onStartPreview" , "Posting doTakeVideo call." ) ;
final VideoResult . Stub stub = mFullVideoPendingStub ;
final VideoResult . Stub stub = mFullVideoPendingStub ;
mFullVideoPendingStub = null ;
mFullVideoPendingStub = null ;
@ -594,7 +609,12 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
mCaptureSize = null ;
mCaptureSize = null ;
mFrameProcessingSize = null ;
mFrameProcessingSize = null ;
if ( mFrameProcessingReader ! = null ) {
if ( mFrameProcessingReader ! = null ) {
mFrameProcessingReader . close ( ) ;
synchronized ( mFrameProcessingImageLock ) {
// This call synchronously releases all Images and their underlying properties.
// This can cause a segmentation fault while converting the Image to NV21.
// So we use this lock for the two operations.
mFrameProcessingReader . close ( ) ;
}
mFrameProcessingReader = null ;
mFrameProcessingReader = null ;
}
}
if ( mPictureReader ! = null ) {
if ( mPictureReader ! = null ) {
@ -611,7 +631,6 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@NonNull
@NonNull
@Override
@Override
protected Task < Void > onStopEngine ( ) {
protected Task < Void > onStopEngine ( ) {
LOG . i ( "onStopEngine:" , "About to clean up." ) ;
try {
try {
LOG . i ( "onStopEngine:" , "Clean up." , "Releasing camera." ) ;
LOG . i ( "onStopEngine:" , "Clean up." , "Releasing camera." ) ;
mCamera . close ( ) ;
mCamera . close ( ) ;
@ -620,6 +639,16 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
LOG . w ( "onStopEngine:" , "Clean up." , "Exception while releasing camera." , e ) ;
LOG . w ( "onStopEngine:" , "Clean up." , "Exception while releasing camera." , e ) ;
}
}
mCamera = null ;
mCamera = null ;
// After engine is stopping, the repeating request builder will be null,
// so the ActionHolder.getBuilder() contract would be broken. Same for characteristics.
// This can cause crashes if some ongoing Action queries the holder. So we abort them.
LOG . i ( "onStopEngine:" , "Aborting actions." ) ;
for ( Action action : mActions ) {
action . abort ( this ) ;
}
mCameraCharacteristics = null ;
mCameraOptions = null ;
mCameraOptions = null ;
mVideoRecorder = null ;
mVideoRecorder = null ;
mRepeatingRequestBuilder = null ;
mRepeatingRequestBuilder = null ;
@ -633,7 +662,9 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@WorkerThread
@WorkerThread
@Override
@Override
protected void onTakePictureSnapshot ( @NonNull final PictureResult . Stub stub , @NonNull final AspectRatio outputRatio , boolean doMetering ) {
protected void onTakePictureSnapshot ( @NonNull final PictureResult . Stub stub ,
@NonNull final AspectRatio outputRatio ,
boolean doMetering ) {
if ( doMetering ) {
if ( doMetering ) {
LOG . i ( "onTakePictureSnapshot:" , "doMetering is true. Delaying." ) ;
LOG . i ( "onTakePictureSnapshot:" , "doMetering is true. Delaying." ) ;
Action action = Actions . timeout ( METER_TIMEOUT , createMeterAction ( null ) ) ;
Action action = Actions . timeout ( METER_TIMEOUT , createMeterAction ( null ) ) ;
@ -653,7 +684,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
// stub.size is not the real size: it will be cropped to the given ratio
// stub.size is not the real size: it will be cropped to the given ratio
// stub.rotation will be set to 0 - we rotate the texture instead.
// stub.rotation will be set to 0 - we rotate the texture instead.
stub . size = getUncroppedSnapshotSize ( Reference . OUTPUT ) ;
stub . size = getUncroppedSnapshotSize ( Reference . OUTPUT ) ;
stub . rotation = getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT , Axis . RELATIVE_TO_SENSOR ) ;
stub . rotation = getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT ,
Axis . RELATIVE_TO_SENSOR ) ;
mPictureRecorder = new Snapshot2PictureRecorder ( stub , this ,
mPictureRecorder = new Snapshot2PictureRecorder ( stub , this ,
( GlCameraPreview ) mPreview , outputRatio ) ;
( GlCameraPreview ) mPreview , outputRatio ) ;
mPictureRecorder . take ( ) ;
mPictureRecorder . take ( ) ;
@ -674,21 +706,24 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
action . start ( this ) ;
action . start ( this ) ;
} else {
} else {
LOG . i ( "onTakePicture:" , "doMetering is false. Performing." ) ;
LOG . i ( "onTakePicture:" , "doMetering is false. Performing." ) ;
stub . rotation = getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT , Axis . RELATIVE_TO_SENSOR ) ;
stub . rotation = getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT ,
Axis . RELATIVE_TO_SENSOR ) ;
stub . size = getPictureSize ( Reference . OUTPUT ) ;
stub . size = getPictureSize ( Reference . OUTPUT ) ;
try {
try {
if ( mPictureCaptureStopsPreview ) {
if ( mPictureCaptureStopsPreview ) {
// These two are present in official samples and are probably meant to speed things up?
// These two are present in official samples and are probably meant to
// But from my tests, they actually make everything slower. So this is disabled by default
// speed things up? But from my tests, they actually make everything slower.
// with a boolean flag. Maybe in the future we can make this configurable as som e
// So this is disabled by default with a boolean flag. Maybe in the future
// people might want to stop the preview while picture is being taken even if it
// we can make this configurable as some people might want to stop the preview
// increases the latency.
// while picture is being taken even if it increases the latency.
mSession . stopRepeating ( ) ;
mSession . stopRepeating ( ) ;
mSession . abortCaptures ( ) ;
mSession . abortCaptures ( ) ;
}
}
CaptureRequest . Builder builder = mCamera . createCaptureRequest ( CameraDevice . TEMPLATE_STILL_CAPTURE ) ;
CaptureRequest . Builder builder
= mCamera . createCaptureRequest ( CameraDevice . TEMPLATE_STILL_CAPTURE ) ;
applyAllParameters ( builder , mRepeatingRequestBuilder ) ;
applyAllParameters ( builder , mRepeatingRequestBuilder ) ;
mPictureRecorder = new Full2PictureRecorder ( stub , this , builder , mPictureReader ) ;
mPictureRecorder = new Full2PictureRecorder ( stub , this , builder ,
mPictureReader ) ;
mPictureRecorder . take ( ) ;
mPictureRecorder . take ( ) ;
} catch ( CameraAccessException e ) {
} catch ( CameraAccessException e ) {
throw createCameraException ( e ) ;
throw createCameraException ( e ) ;
@ -721,8 +756,10 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@Override
@Override
protected void onTakeVideo ( @NonNull VideoResult . Stub stub ) {
protected void onTakeVideo ( @NonNull VideoResult . Stub stub ) {
LOG . i ( "onTakeVideo" , "called." ) ;
LOG . i ( "onTakeVideo" , "called." ) ;
stub . rotation = getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT , Axis . RELATIVE_TO_SENSOR ) ;
stub . rotation = getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT ,
stub . size = getAngles ( ) . flip ( Reference . SENSOR , Reference . OUTPUT ) ? mCaptureSize . flip ( ) : mCaptureSize ;
Axis . RELATIVE_TO_SENSOR ) ;
stub . size = getAngles ( ) . flip ( Reference . SENSOR , Reference . OUTPUT ) ?
mCaptureSize . flip ( ) : mCaptureSize ;
// We must restart the session at each time.
// We must restart the session at each time.
// Save the pending data and restart the session.
// Save the pending data and restart the session.
LOG . w ( "onTakeVideo" , "calling restartBind." ) ;
LOG . w ( "onTakeVideo" , "calling restartBind." ) ;
@ -752,9 +789,10 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@WorkerThread
@WorkerThread
@Override
@Override
protected void onTakeVideoSnapshot ( @NonNull VideoResult . Stub stub , @NonNull AspectRatio outputRatio ) {
protected void onTakeVideoSnapshot ( @NonNull VideoResult . Stub stub ,
@NonNull AspectRatio outputRatio ) {
if ( ! ( mPreview instanceof GlCameraPreview ) ) {
if ( ! ( mPreview instanceof GlCameraPreview ) ) {
throw new IllegalStateException ( "Video snapshots are only supported with GlCameraPreview ." ) ;
throw new IllegalStateException ( "Video snapshots are only supported with GL_SURFACE ." ) ;
}
}
GlCameraPreview glPreview = ( GlCameraPreview ) mPreview ;
GlCameraPreview glPreview = ( GlCameraPreview ) mPreview ;
Size outputSize = getUncroppedSnapshotSize ( Reference . OUTPUT ) ;
Size outputSize = getUncroppedSnapshotSize ( Reference . OUTPUT ) ;
@ -779,18 +817,21 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
// Start.
// Start.
// The overlay rotation should alway be VIEW-OUTPUT, just liek Camera1Engine.
// The overlay rotation should alway be VIEW-OUTPUT, just liek Camera1Engine.
int overlayRotation = getAngles ( ) . offset ( Reference . VIEW , Reference . OUTPUT , Axis . ABSOLUTE ) ;
int overlayRotation = getAngles ( ) . offset ( Reference . VIEW , Reference . OUTPUT , Axis . ABSOLUTE ) ;
mVideoRecorder = new SnapshotVideoRecorder ( this , glPreview , getOverlay ( ) , overlayRotation ) ;
mVideoRecorder = new SnapshotVideoRecorder ( this , glPreview , getOverlay ( ) ,
overlayRotation ) ;
mVideoRecorder . start ( stub ) ;
mVideoRecorder . start ( stub ) ;
}
}
/ * *
* When video ends we must stop the recorder and remove the recorder surface from
* camera outputs . This is done in onVideoResult . However , on some devices , order matters .
* If we stop the recorder and AFTER send camera frames to it , the camera will try to fill
* the recorder "abandoned" Surface and on some devices with a poor internal implementation
* ( HW_LEVEL_LEGACY ) this crashes . So if the conditions are met , we restore here . Issue # 549 .
* /
@Override
@Override
public void onVideoRecordingEnd ( ) {
public void onVideoRecordingEnd ( ) {
super . onVideoRecordingEnd ( ) ;
super . onVideoRecordingEnd ( ) ;
// When video ends we must stop the recorder and remove the recorder surface from camera outputs.
// This is done in onVideoResult. However, on some devices, order matters. If we stop the recorder
// and AFTER send camera frames to it, the camera will try to fill the recorder "abandoned"
// Surface and on some devices with a poor internal implementation (HW_LEVEL_LEGACY) this crashes.
// So if the conditions are met, we restore here. Issue #549.
boolean needsIssue549Workaround = ( mVideoRecorder instanceof Full2VideoRecorder ) | |
boolean needsIssue549Workaround = ( mVideoRecorder instanceof Full2VideoRecorder ) | |
( readCharacteristic ( CameraCharacteristics . INFO_SUPPORTED_HARDWARE_LEVEL , - 1 )
( readCharacteristic ( CameraCharacteristics . INFO_SUPPORTED_HARDWARE_LEVEL , - 1 )
= = CameraCharacteristics . INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY ) ;
= = CameraCharacteristics . INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY ) ;
@ -806,7 +847,7 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
}
}
/ * *
/ * *
* Some v ideo recorders might change the camera template to { @link CameraDevice # TEMPLATE_RECORD } .
* V ideo recorders might change the camera template to { @link CameraDevice # TEMPLATE_RECORD } .
* After the video is taken , we should restore the template preview , which also means that
* After the video is taken , we should restore the template preview , which also means that
* we ' ll remove any extra surface target that was added by the video recorder .
* we ' ll remove any extra surface target that was added by the video recorder .
*
*
@ -846,26 +887,34 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
// We might be in a metering operation, or the old builder might have some special
// We might be in a metering operation, or the old builder might have some special
// metering parameters. Copy these special keys over to the new builder.
// metering parameters. Copy these special keys over to the new builder.
// These are the keys changed by metering.Parameters, or by us in applyFocusForMetering.
// These are the keys changed by metering.Parameters, or by us in applyFocusForMetering.
builder . set ( CaptureRequest . CONTROL_AF_REGIONS , oldBuilder . get ( CaptureRequest . CONTROL_AF_REGIONS ) ) ;
builder . set ( CaptureRequest . CONTROL_AF_REGIONS ,
builder . set ( CaptureRequest . CONTROL_AE_REGIONS , oldBuilder . get ( CaptureRequest . CONTROL_AE_REGIONS ) ) ;
oldBuilder . get ( CaptureRequest . CONTROL_AF_REGIONS ) ) ;
builder . set ( CaptureRequest . CONTROL_AWB_REGIONS , oldBuilder . get ( CaptureRequest . CONTROL_AWB_REGIONS ) ) ;
builder . set ( CaptureRequest . CONTROL_AE_REGIONS ,
builder . set ( CaptureRequest . CONTROL_AF_MODE , oldBuilder . get ( CaptureRequest . CONTROL_AF_MODE ) ) ;
oldBuilder . get ( CaptureRequest . CONTROL_AE_REGIONS ) ) ;
builder . set ( CaptureRequest . CONTROL_AWB_REGIONS ,
oldBuilder . get ( CaptureRequest . CONTROL_AWB_REGIONS ) ) ;
builder . set ( CaptureRequest . CONTROL_AF_MODE ,
oldBuilder . get ( CaptureRequest . CONTROL_AF_MODE ) ) ;
// Do NOT copy exposure or focus triggers!
// Do NOT copy exposure or focus triggers!
}
}
}
}
private void applyDefaultFocus ( @NonNull CaptureRequest . Builder builder ) {
@SuppressWarnings ( "WeakerAccess" )
int [ ] modesArray = readCharacteristic ( CameraCharacteristics . CONTROL_AF_AVAILABLE_MODES , new int [ ] { } ) ;
protected void applyDefaultFocus ( @NonNull CaptureRequest . Builder builder ) {
int [ ] modesArray = readCharacteristic ( CameraCharacteristics . CONTROL_AF_AVAILABLE_MODES ,
new int [ ] { } ) ;
List < Integer > modes = new ArrayList < > ( ) ;
List < Integer > modes = new ArrayList < > ( ) ;
for ( int mode : modesArray ) { modes . add ( mode ) ; }
for ( int mode : modesArray ) { modes . add ( mode ) ; }
if ( getMode ( ) = = Mode . VIDEO & &
if ( getMode ( ) = = Mode . VIDEO & &
modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ) {
modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ) {
builder . set ( CaptureRequest . CONTROL_AF_MODE , CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ;
builder . set ( CaptureRequest . CONTROL_AF_MODE ,
CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ;
return ;
return ;
}
}
if ( modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ) {
if ( modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ) {
builder . set ( CaptureRequest . CONTROL_AF_MODE , CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ;
builder . set ( CaptureRequest . CONTROL_AF_MODE ,
CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ;
return ;
return ;
}
}
@ -882,10 +931,18 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
}
}
}
}
private void applyFocusForMetering ( @NonNull CaptureRequest . Builder builder ) {
/ * *
// All focus modes support the AF trigger, except OFF and EDOF.
* All focus modes support the AF trigger , except OFF and EDOF .
// However, unlike the preview, we'd prefer AUTO to any CONTINUOUS value.
* However , unlike the preview , we ' d prefer AUTO to any CONTINUOUS value .
int [ ] modesArray = readCharacteristic ( CameraCharacteristics . CONTROL_AF_AVAILABLE_MODES , new int [ ] { } ) ;
* An AUTO value means that focus is locked unless we run the focus trigger ,
* which is what metering does .
*
* @param builder builder
* /
@SuppressWarnings ( "WeakerAccess" )
protected void applyFocusForMetering ( @NonNull CaptureRequest . Builder builder ) {
int [ ] modesArray = readCharacteristic ( CameraCharacteristics . CONTROL_AF_AVAILABLE_MODES ,
new int [ ] { } ) ;
List < Integer > modes = new ArrayList < > ( ) ;
List < Integer > modes = new ArrayList < > ( ) ;
for ( int mode : modesArray ) { modes . add ( mode ) ; }
for ( int mode : modesArray ) { modes . add ( mode ) ; }
if ( modes . contains ( CaptureRequest . CONTROL_AF_MODE_AUTO ) ) {
if ( modes . contains ( CaptureRequest . CONTROL_AF_MODE_AUTO ) ) {
@ -894,12 +951,14 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
}
}
if ( getMode ( ) = = Mode . VIDEO & &
if ( getMode ( ) = = Mode . VIDEO & &
modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ) {
modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ) {
builder . set ( CaptureRequest . CONTROL_AF_MODE , CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ;
builder . set ( CaptureRequest . CONTROL_AF_MODE ,
CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_VIDEO ) ;
return ;
return ;
}
}
if ( modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ) {
if ( modes . contains ( CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ) {
builder . set ( CaptureRequest . CONTROL_AF_MODE , CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ;
builder . set ( CaptureRequest . CONTROL_AF_MODE ,
CaptureRequest . CONTROL_AF_MODE_CONTINUOUS_PICTURE ) ;
//noinspection UnnecessaryReturnStatement
//noinspection UnnecessaryReturnStatement
return ;
return ;
}
}
@ -916,13 +975,14 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
boolean shouldApply = applyFlash ( mRepeatingRequestBuilder , old ) ;
boolean shouldApply = applyFlash ( mRepeatingRequestBuilder , old ) ;
boolean needsWorkaround = getPreviewState ( ) = = STATE_STARTED ;
boolean needsWorkaround = getPreviewState ( ) = = STATE_STARTED ;
if ( needsWorkaround ) {
if ( needsWorkaround ) {
// Runtime changes to the flash value are not correctly handled by the driver.
// Runtime changes to the flash value are not correctly handled by the
// See https://stackoverflow.com/q/53003383/4288782 for example.
// driver. See https://stackoverflow.com/q/53003383/4288782 for example.
// For this reason, we go back to OFF, capture once, then go to the new one.
// For this reason, we go back to OFF, capture once, then go to the new one.
mFlash = Flash . OFF ;
mFlash = Flash . OFF ;
applyFlash ( mRepeatingRequestBuilder , old ) ;
applyFlash ( mRepeatingRequestBuilder , old ) ;
try {
try {
mSession . capture ( mRepeatingRequestBuilder . build ( ) , null , null ) ;
mSession . capture ( mRepeatingRequestBuilder . build ( ) , null ,
null ) ;
} catch ( CameraAccessException e ) {
} catch ( CameraAccessException e ) {
throw createCameraException ( e ) ;
throw createCameraException ( e ) ;
}
}
@ -946,18 +1006,19 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
* - { @link CaptureRequest # CONTROL_AE_MODE_ON_ALWAYS_FLASH }
* - { @link CaptureRequest # CONTROL_AE_MODE_ON_ALWAYS_FLASH }
*
*
* The API offers a high level control through { @link CaptureRequest # CONTROL_AE_MODE } ,
* The API offers a high level control through { @link CaptureRequest # CONTROL_AE_MODE } ,
* which is what the mapper looks at . It will trigger ( if specified ) flash only for still captures
* which is what the mapper looks at . It will trigger ( if specified ) flash only for
* which is exactly what we want .
* still captures which is exactly what we want .
*
*
* However , we set CONTROL_AE_MODE to ON / OFF ( depending
* However , we set CONTROL_AE_MODE to ON / OFF ( depending
* on which is available ) with both { @link Flash # OFF } and { @link Flash # TORCH } .
* on which is available ) with both { @link Flash # OFF } and { @link Flash # TORCH } .
*
*
* When CONTROL_AE_MODE is ON or OFF , the low level control , called { @link CaptureRequest # FLASH_MODE } ,
* When CONTROL_AE_MODE is ON or OFF , the low level control , called
* becomes effective , and that ' s where we can actually distinguish between a turned off flash
* { @link CaptureRequest # FLASH_MODE } , becomes effective , and that ' s where we can actually
* and a torch flash .
* distinguish between a turned off flash and a torch flash .
* /
* /
private boolean applyFlash ( @NonNull CaptureRequest . Builder builder ,
@SuppressWarnings ( "WeakerAccess" )
@NonNull Flash oldFlash ) {
protected boolean applyFlash ( @NonNull CaptureRequest . Builder builder ,
@NonNull Flash oldFlash ) {
if ( mCameraOptions . supports ( mFlash ) ) {
if ( mCameraOptions . supports ( mFlash ) ) {
int [ ] availableAeModesArray = readCharacteristic (
int [ ] availableAeModesArray = readCharacteristic (
CameraCharacteristics . CONTROL_AE_AVAILABLE_MODES , new int [ ] { } ) ;
CameraCharacteristics . CONTROL_AE_AVAILABLE_MODES , new int [ ] { } ) ;
@ -996,8 +1057,9 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
} ) ;
} ) ;
}
}
private boolean applyLocation ( @NonNull CaptureRequest . Builder builder ,
@SuppressWarnings ( "WeakerAccess" )
@SuppressWarnings ( "unused" ) @Nullable Location oldLocation ) {
protected boolean applyLocation ( @NonNull CaptureRequest . Builder builder ,
@SuppressWarnings ( "unused" ) @Nullable Location oldLocation ) {
if ( mLocation ! = null ) {
if ( mLocation ! = null ) {
builder . set ( CaptureRequest . JPEG_GPS_LOCATION , mLocation ) ;
builder . set ( CaptureRequest . JPEG_GPS_LOCATION , mLocation ) ;
}
}
@ -1021,8 +1083,9 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
} ) ;
} ) ;
}
}
private boolean applyWhiteBalance ( @NonNull CaptureRequest . Builder builder ,
@SuppressWarnings ( "WeakerAccess" )
@NonNull WhiteBalance oldWhiteBalance ) {
protected boolean applyWhiteBalance ( @NonNull CaptureRequest . Builder builder ,
@NonNull WhiteBalance oldWhiteBalance ) {
if ( mCameraOptions . supports ( mWhiteBalance ) ) {
if ( mCameraOptions . supports ( mWhiteBalance ) ) {
int whiteBalance = mMapper . mapWhiteBalance ( mWhiteBalance ) ;
int whiteBalance = mMapper . mapWhiteBalance ( mWhiteBalance ) ;
builder . set ( CaptureRequest . CONTROL_AWB_MODE , whiteBalance ) ;
builder . set ( CaptureRequest . CONTROL_AWB_MODE , whiteBalance ) ;
@ -1049,8 +1112,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
} ) ;
} ) ;
}
}
@SuppressWarnings ( "WeakerAccess" )
private boolean applyHdr ( @NonNull CaptureRequest . Builder builder , @NonNull Hdr oldHdr ) {
protected boolean applyHdr ( @NonNull CaptureRequest . Builder builder , @NonNull Hdr oldHdr ) {
if ( mCameraOptions . supports ( mHdr ) ) {
if ( mCameraOptions . supports ( mHdr ) ) {
int hdr = mMapper . mapHdr ( mHdr ) ;
int hdr = mMapper . mapHdr ( mHdr ) ;
builder . set ( CaptureRequest . CONTROL_SCENE_MODE , hdr ) ;
builder . set ( CaptureRequest . CONTROL_SCENE_MODE , hdr ) ;
@ -1080,9 +1143,11 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
} ) ;
} ) ;
}
}
private boolean applyZoom ( @NonNull CaptureRequest . Builder builder , float oldZoom ) {
@SuppressWarnings ( "WeakerAccess" )
protected boolean applyZoom ( @NonNull CaptureRequest . Builder builder , float oldZoom ) {
if ( mCameraOptions . isZoomSupported ( ) ) {
if ( mCameraOptions . isZoomSupported ( ) ) {
float maxZoom = readCharacteristic ( CameraCharacteristics . SCALER_AVAILABLE_MAX_DIGITAL_ZOOM , 1F ) ;
float maxZoom = readCharacteristic (
CameraCharacteristics . SCALER_AVAILABLE_MAX_DIGITAL_ZOOM , 1F ) ;
// converting 0.0f-1.0f zoom scale to the actual camera digital zoom scale
// converting 0.0f-1.0f zoom scale to the actual camera digital zoom scale
// (which will be for example, 1.0-10.0)
// (which will be for example, 1.0-10.0)
float calculatedZoom = ( mZoomValue * ( maxZoom - 1 . 0f ) ) + 1 . 0f ;
float calculatedZoom = ( mZoomValue * ( maxZoom - 1 . 0f ) ) + 1 . 0f ;
@ -1096,8 +1161,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@NonNull
@NonNull
private Rect getZoomRect ( float zoomLevel , float maxDigitalZoom ) {
private Rect getZoomRect ( float zoomLevel , float maxDigitalZoom ) {
Rect activeRect = readCharacteristic ( CameraCharacteristics . SENSOR_INFO_ACTIVE_ARRAY_SIZE , new Rect ( ) ) ;
Rect activeRect = readCharacteristic ( CameraCharacteristics . SENSOR_INFO_ACTIVE_ARRAY_SIZE ,
new Rect ( ) ) ;
int minW = ( int ) ( activeRect . width ( ) / maxDigitalZoom ) ;
int minW = ( int ) ( activeRect . width ( ) / maxDigitalZoom ) ;
int minH = ( int ) ( activeRect . height ( ) / maxDigitalZoom ) ;
int minH = ( int ) ( activeRect . height ( ) / maxDigitalZoom ) ;
int difW = activeRect . width ( ) - minW ;
int difW = activeRect . width ( ) - minW ;
@ -1107,11 +1172,15 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
// When zoom is maxZoom, we want to return a centered rect with minW and minH
// When zoom is maxZoom, we want to return a centered rect with minW and minH
int cropW = ( int ) ( difW * ( zoomLevel - 1 ) / ( maxDigitalZoom - 1 ) / 2F ) ;
int cropW = ( int ) ( difW * ( zoomLevel - 1 ) / ( maxDigitalZoom - 1 ) / 2F ) ;
int cropH = ( int ) ( difH * ( zoomLevel - 1 ) / ( maxDigitalZoom - 1 ) / 2F ) ;
int cropH = ( int ) ( difH * ( zoomLevel - 1 ) / ( maxDigitalZoom - 1 ) / 2F ) ;
return new Rect ( cropW , cropH , activeRect . width ( ) - cropW , activeRect . height ( ) - cropH ) ;
return new Rect ( cropW , cropH , activeRect . width ( ) - cropW ,
activeRect . height ( ) - cropH ) ;
}
}
@Override
@Override
public void setExposureCorrection ( final float EVvalue , @NonNull final float [ ] bounds , @Nullable final PointF [ ] points , final boolean notify ) {
public void setExposureCorrection ( final float EVvalue ,
@NonNull final float [ ] bounds ,
@Nullable final PointF [ ] points ,
final boolean notify ) {
final float old = mExposureCorrectionValue ;
final float old = mExposureCorrectionValue ;
mExposureCorrectionValue = EVvalue ;
mExposureCorrectionValue = EVvalue ;
mHandler . run ( new Runnable ( ) {
mHandler . run ( new Runnable ( ) {
@ -1130,11 +1199,15 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
} ) ;
} ) ;
}
}
private boolean applyExposureCorrection ( @NonNull CaptureRequest . Builder builder , float oldEVvalue ) {
@SuppressWarnings ( "WeakerAccess" )
protected boolean applyExposureCorrection ( @NonNull CaptureRequest . Builder builder ,
float oldEVvalue ) {
if ( mCameraOptions . isExposureCorrectionSupported ( ) ) {
if ( mCameraOptions . isExposureCorrectionSupported ( ) ) {
Rational exposureCorrectionStep = readCharacteristic ( CameraCharacteristics . CONTROL_AE_COMPENSATION_STEP ,
Rational exposureCorrectionStep = readCharacteristic (
CameraCharacteristics . CONTROL_AE_COMPENSATION_STEP ,
new Rational ( 1 , 1 ) ) ;
new Rational ( 1 , 1 ) ) ;
int exposureCorrectionSteps = Math . round ( mExposureCorrectionValue * exposureCorrectionStep . floatValue ( ) ) ;
int exposureCorrectionSteps = Math . round ( mExposureCorrectionValue
* exposureCorrectionStep . floatValue ( ) ) ;
builder . set ( CaptureRequest . CONTROL_AE_EXPOSURE_COMPENSATION , exposureCorrectionSteps ) ;
builder . set ( CaptureRequest . CONTROL_AE_EXPOSURE_COMPENSATION , exposureCorrectionSteps ) ;
return true ;
return true ;
}
}
@ -1165,6 +1238,7 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
LOG . w ( "onImageAvailable" , "no byte buffer!" ) ;
LOG . w ( "onImageAvailable" , "no byte buffer!" ) ;
return ;
return ;
}
}
LOG . v ( "onImageAvailable" , "trying to acquire Image." ) ;
Image image = null ;
Image image = null ;
try {
try {
image = reader . acquireLatestImage ( ) ;
image = reader . acquireLatestImage ( ) ;
@ -1174,9 +1248,11 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
getFrameManager ( ) . onBufferUnused ( data ) ;
getFrameManager ( ) . onBufferUnused ( data ) ;
return ;
return ;
}
}
LOG . i ( "onImageAvailable" , "we have both a byte buffer and an Image." ) ;
LOG . v ( "onImageAvailable" , "we have both a byte buffer and an Image." ) ;
try {
try {
ImageHelper . convertToNV21 ( image , data ) ;
synchronized ( mFrameProcessingImageLock ) {
ImageHelper . convertToNV21 ( image , data ) ;
}
} catch ( Exception e ) {
} catch ( Exception e ) {
LOG . w ( "onImageAvailable" , "error while converting." ) ;
LOG . w ( "onImageAvailable" , "error while converting." ) ;
getFrameManager ( ) . onBufferUnused ( data ) ;
getFrameManager ( ) . onBufferUnused ( data ) ;
@ -1188,7 +1264,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
// After preview, the frame manager is correctly set up
// After preview, the frame manager is correctly set up
Frame frame = getFrameManager ( ) . getFrame ( data ,
Frame frame = getFrameManager ( ) . getFrame ( data ,
System . currentTimeMillis ( ) ,
System . currentTimeMillis ( ) ,
getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT , Axis . RELATIVE_TO_SENSOR ) ) ;
getAngles ( ) . offset ( Reference . SENSOR , Reference . OUTPUT ,
Axis . RELATIVE_TO_SENSOR ) ) ;
mCallback . dispatchFrame ( frame ) ;
mCallback . dispatchFrame ( frame ) ;
} else {
} else {
getFrameManager ( ) . onBufferUnused ( data ) ;
getFrameManager ( ) . onBufferUnused ( data ) ;
@ -1197,18 +1274,35 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@Override
@Override
public void setHasFrameProcessors ( final boolean hasFrameProcessors ) {
public void setHasFrameProcessors ( final boolean hasFrameProcessors ) {
super . setHasFrameProcessors ( hasFrameProcessors ) ;
LOG . i ( "setHasFrameProcessors" , "changing to" , hasFrameProcessors , "posting." ) ;
LOG . i ( "setHasFrameProcessors" , "changed to" , hasFrameProcessors , "posting." ) ;
Camera2Engine . super . setHasFrameProcessors ( hasFrameProcessors ) ;
mHandler . run ( new Runnable ( ) {
mHandler . run ( new Runnable ( ) {
@Override
@Override
public void run ( ) {
public void run ( ) {
LOG . i ( "setHasFrameProcessors" , "changed to" , hasFrameProcessors , "executing. BindState:" , getBindState ( ) ) ;
LOG . i ( "setHasFrameProcessors" , "changing to" , hasFrameProcessors ,
if ( getBindState ( ) = = STATE_STARTED ) {
"executing. BindState:" , getBindState ( ) ,
LOG . i ( "setHasFrameProcessors" , "triggering a restart." ) ;
"PreviewState:" , getPreviewState ( ) ) ;
// TODO if taking video, this stops it.
// Frame processing is set up partially when binding and partially when starting
// the preview. We don't want to only check bind state or startPreview can fail.
if ( getBindState ( ) = = STATE_STOPPED ) {
LOG . i ( "setHasFrameProcessors" , "not bound so won't restart." ) ;
} else if ( getPreviewState ( ) = = STATE_STARTED ) {
// This needs a restartBind(). NOTE: if taking video, this stops it.
LOG . i ( "setHasFrameProcessors" , "bound with preview." ,
"Calling restartBind()." ) ;
restartBind ( ) ;
restartBind ( ) ;
} else {
} else {
LOG . i ( "setHasFrameProcessors" , "not bound so won't restart." ) ;
// Bind+Preview is not completely started yet not completely stopped.
// This can happen if the user adds a frame processor in onCameraOpened().
// Supporting this would add lot of complexity to this class, and
// this should be discouraged anyway since changing the frame processor number
// at this time requires restarting the camera when it was just opened.
// For these reasons, let's throw.
throw new IllegalStateException ( "Added/removed a FrameProcessor at illegal " +
"time. These operations should be done before opening the camera, or " +
"before closing it - NOT when it just opened, for example during the " +
"onCameraOpened() callback." ) ;
}
}
}
}
} ) ;
} ) ;
@ -1225,8 +1319,9 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
@Override
@Override
public void run ( ) {
public void run ( ) {
LOG . i ( "startAutoFocus" , "executing. Preview state:" , getPreviewState ( ) ) ;
LOG . i ( "startAutoFocus" , "executing. Preview state:" , getPreviewState ( ) ) ;
// This will only work when we have a preview, since it launches the preview in the end.
// This will only work when we have a preview, since it launches the preview
// Even without this it would need the bind state at least, since we need the preview size.
// in the end. Even without this it would need the bind state at least,
// since we need the preview size.
if ( getPreviewState ( ) < STATE_STARTED ) return ;
if ( getPreviewState ( ) < STATE_STARTED ) return ;
// The camera options API still has the auto focus API but it really
// The camera options API still has the auto focus API but it really
@ -1244,7 +1339,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
mCallback . dispatchOnFocusEnd ( gesture , action . isSuccessful ( ) , point ) ;
mCallback . dispatchOnFocusEnd ( gesture , action . isSuccessful ( ) , point ) ;
mHandler . remove ( mUnlockAndResetMeteringRunnable ) ;
mHandler . remove ( mUnlockAndResetMeteringRunnable ) ;
if ( shouldResetAutoFocus ( ) ) {
if ( shouldResetAutoFocus ( ) ) {
mHandler . post ( getAutoFocusResetDelay ( ) , mUnlockAndResetMeteringRunnable ) ;
mHandler . post ( getAutoFocusResetDelay ( ) ,
mUnlockAndResetMeteringRunnable ) ;
}
}
}
}
} ) ;
} ) ;
@ -1263,7 +1359,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
// The last one is under our control because the library has no focus API.
// The last one is under our control because the library has no focus API.
// So let's set a good af mode here. This operation is reverted during onMeteringReset().
// So let's set a good af mode here. This operation is reverted during onMeteringReset().
applyFocusForMetering ( mRepeatingRequestBuilder ) ;
applyFocusForMetering ( mRepeatingRequestBuilder ) ;
mMeterAction = new MeterAction ( Camera2Engine . this , point , point = = null ) ;
mMeterAction = new MeterAction ( Camera2Engine . this , point ,
point = = null ) ;
return mMeterAction ;
return mMeterAction ;
}
}
@ -1282,8 +1379,10 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
protected void onStart ( @NonNull ActionHolder holder ) {
protected void onStart ( @NonNull ActionHolder holder ) {
super . onStart ( holder ) ;
super . onStart ( holder ) ;
applyDefaultFocus ( holder . getBuilder ( this ) ) ;
applyDefaultFocus ( holder . getBuilder ( this ) ) ;
holder . getBuilder ( this ) . set ( CaptureRequest . CONTROL_AE_LOCK , false ) ;
holder . getBuilder ( this )
holder . getBuilder ( this ) . set ( CaptureRequest . CONTROL_AWB_LOCK , false ) ;
. set ( CaptureRequest . CONTROL_AE_LOCK , false ) ;
holder . getBuilder ( this )
. set ( CaptureRequest . CONTROL_AWB_LOCK , false ) ;
holder . applyBuilder ( this ) ;
holder . applyBuilder ( this ) ;
setState ( STATE_COMPLETED ) ;
setState ( STATE_COMPLETED ) ;
// TODO should wait results?
// TODO should wait results?
@ -1348,7 +1447,8 @@ public class Camera2Engine extends CameraEngine implements ImageReader.OnImageAv
}
}
@Override
@Override
public void applyBuilder ( @NonNull Action source , @NonNull CaptureRequest . Builder builder ) throws CameraAccessException {
public void applyBuilder ( @NonNull Action source , @NonNull CaptureRequest . Builder builder )
throws CameraAccessException {
mSession . capture ( builder . build ( ) , mRepeatingRequestCallback , null ) ;
mSession . capture ( builder . build ( ) , mRepeatingRequestCallback , null ) ;
}
}