android.hardware.camera2.CameraDevice Java Examples

The following examples show how to use android.hardware.camera2.CameraDevice. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Camera2BasicFragment.java    From Android-Camera2-Front-with-Face-Detection with Apache License 2.0 6 votes vote down vote up
/**
 * Capture a still picture. This method should be called when we get a response in
 * {@link #mCaptureCallback} from both {@link #lockFocus()}.
 */
private void captureStillPicture() {
    try {
        final Activity activity = getActivity();
        if (null == activity || null == mCameraDevice) {
            return;
        }
        // This is the CaptureRequest.Builder that we use to take a picture.
        final CaptureRequest.Builder captureBuilder =
                mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(mImageReader.getSurface());

        // Use the same AE and AF modes as the preview.
        captureBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
        setAutoFlash(captureBuilder);

        // Orientation
        int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(rotation));

        CameraCaptureSession.CaptureCallback CaptureCallback
                = new CameraCaptureSession.CaptureCallback() {

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                           @NonNull CaptureRequest request,
                                           @NonNull TotalCaptureResult result) {
                showToast("Saved: " + mFile);
                Log.d(TAG, mFile.toString());
                unlockFocus();
            }
        };

        mCaptureSession.stopRepeating();
        mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
 
Example #2
Source File: Camera2Session.java    From webrtc_android with MIT License 6 votes vote down vote up
@Override
public void onOpened(CameraDevice camera) {
    checkIsOnCameraThread();

    Logging.d(TAG, "Camera opened.");
    cameraDevice = camera;

    surfaceTextureHelper.setTextureSize(captureFormat.width, captureFormat.height);
    surface = new Surface(surfaceTextureHelper.getSurfaceTexture());
    try {
        camera.createCaptureSession(
                Arrays.asList(surface), new CaptureSessionCallback(), cameraThreadHandler);
    } catch (CameraAccessException e) {
        reportError("Failed to create capture session. " + e);
        return;
    }
}
 
Example #3
Source File: Camera2.java    From TikTok with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Starts a capture session for camera preview.</p>
 * <p>This rewrites {@link #mPreviewRequestBuilder}.</p>
 * <p>The result will be continuously processed in {@link #mSessionCallback}.</p>
 */
void startCaptureSession() {
    if (!isCameraOpened() || !mPreview.isReady() || mImageReader == null) {
        return;
    }
    Size previewSize = chooseOptimalSize();
    mPreview.setBufferSize(previewSize.getWidth(), previewSize.getHeight());
    Surface surface = mPreview.getSurface();
    try {
        mPreviewRequestBuilder = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);
        mCamera.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                mSessionCallback, null);
    } catch (CameraAccessException e) {
        throw new RuntimeException("Failed to start camera session");
    }
}
 
Example #4
Source File: BlockingCameraManager.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
@Override
public void onOpened(CameraDevice camera) {
    if (VERBOSE) {
        Log.v(TAG, "onOpened: camera " + ((camera != null) ? camera.getId() : "null"));
    }

    synchronized (mLock) {
        assertInitialState();
        mNoReply = false;
        mSuccess = true;
        mDevice = camera;
        mDeviceReady.open();

        if (mTimedOut && camera != null) {
            camera.close();
            return;
        }
    }

    if (mProxy != null) mProxy.onOpened(camera);
}
 
Example #5
Source File: Camera2.java    From LockDemo with Apache License 2.0 6 votes vote down vote up
/**
 * <p>Starts a capture session for camera preview.</p>
 * <p>This rewrites {@link #mPreviewRequestBuilder}.</p>
 * <p>The result will be continuously processed in {@link #mSessionCallback}.</p>
 */
void startCaptureSession() {
    if (!isCameraOpened() || !mPreview.isReady() || mImageReader == null) {
        return;
    }
    Size previewSize = chooseOptimalSize();
    mPreview.setBufferSize(previewSize.getWidth(), previewSize.getHeight());
    Surface surface = mPreview.getSurface();
    try {
        mPreviewRequestBuilder = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewRequestBuilder.addTarget(surface);
        mCamera.createCaptureSession(Arrays.asList(surface, mImageReader.getSurface()),
                mSessionCallback, null);
    } catch (CameraAccessException e) {
        throw new RuntimeException("Failed to start camera session");
    }
}
 
Example #6
Source File: CameraHelp2.java    From WeiXinRecordedDemo with MIT License 6 votes vote down vote up
public void shotPhoto(){

        try {
            CaptureRequest.Builder captureRequestBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
            captureRequestBuilder.addTarget(mImageReader.getSurface());
            // 自动对焦
            captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
            // 自动曝光
            captureRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH);
            captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION, mOrientation);
            CaptureRequest captureRequest = captureRequestBuilder.build();
            mCameraCaptureSession.capture(captureRequest, null, mHandler);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
 
Example #7
Source File: DeviceCallback.java    From android-robocar with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
  switch (error) {
    case CameraDevice.StateCallback.ERROR_CAMERA_IN_USE:
      Timber.e("Camera error: ERROR_CAMERA_IN_USE");
      break;
    case CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE:
      Timber.e("Camera error: ERROR_MAX_CAMERAS_IN_USE");
      break;
    case CameraDevice.StateCallback.ERROR_CAMERA_DISABLED:
      Timber.e("Camera error: ERROR_CAMERA_DISABLED");
      break;
    case CameraDevice.StateCallback.ERROR_CAMERA_DEVICE:
      Timber.e("Camera error: ERROR_CAMERA_DEVICE");
      break;
    case CameraDevice.StateCallback.ERROR_CAMERA_SERVICE:
      Timber.e("Camera error: ERROR_CAMERA_SERVICE");
      break;
    default:
      Timber.e("Camera error: UNKNOWN");
      break;
  }

  this.cameraDevice = cameraDevice;
  closeDevice();
}
 
Example #8
Source File: AndroidCamera2AgentImpl.java    From Camera2 with Apache License 2.0 6 votes vote down vote up
/**
 * Simply propagates settings from provided {@link CameraSettings}
 * object to our {@link CaptureRequest.Builder} for use in captures.
 * <p>Most conversions to match the API 2 formats are performed by
 * {@link AndroidCamera2Capabilities.IntegralStringifier}; otherwise
 * any final adjustments are done here before updating the builder.</p>
 *
 * @param settings The new/updated settings
 */
private void applyToRequest(AndroidCamera2Settings settings) {
    // TODO: If invoked when in PREVIEW_READY state, a new preview size will not take effect

    mPersistentSettings.union(settings.getRequestSettings());
    mPreviewSize = settings.getCurrentPreviewSize();
    mPhotoSize = settings.getCurrentPhotoSize();

    if (mCameraState.getState() >= AndroidCamera2StateHolder.CAMERA_PREVIEW_ACTIVE) {
        // If we're already previewing, reflect most settings immediately
        try {
            mSession.setRepeatingRequest(
                    mPersistentSettings.createRequest(mCamera,
                            CameraDevice.TEMPLATE_PREVIEW, mPreviewSurface),
                    /*listener*/mCameraResultStateCallback, /*handler*/this);
        } catch (CameraAccessException ex) {
            Log.e(TAG, "Failed to apply updated request settings", ex);
        }
    } else if (mCameraState.getState() < AndroidCamera2StateHolder.CAMERA_PREVIEW_READY) {
        // If we're already ready to preview, this doesn't regress our state
        changeState(AndroidCamera2StateHolder.CAMERA_CONFIGURED);
    }
}
 
Example #9
Source File: JavaCamera2View.java    From pasm-yolov3-Android with GNU General Public License v3.0 6 votes vote down vote up
@Override
protected void disconnectCamera() {
    Log.i(LOGTAG, "closeCamera");
    try {
        CameraDevice c = mCameraDevice;
        mCameraDevice = null;
        if (null != mCaptureSession) {
            mCaptureSession.close();
            mCaptureSession = null;
        }
        if (null != c) {
            c.close();
        }
        if (null != mImageReader) {
            mImageReader.close();
            mImageReader = null;
        }
    } finally {
        stopBackgroundThread();
    }
}
 
Example #10
Source File: JavaCamera2View.java    From VIA-AI with MIT License 6 votes vote down vote up
@Override
protected void disconnectCamera() {
    Log.i(LOGTAG, "closeCamera");
    try {
        CameraDevice c = mCameraDevice;
        mCameraDevice = null;
        if (null != mCaptureSession) {
            mCaptureSession.close();
            mCaptureSession = null;
        }
        if (null != c) {
            c.close();
        }
        if (null != mImageReader) {
            mImageReader.close();
            mImageReader = null;
        }
    } finally {
        stopBackgroundThread();
    }
}
 
Example #11
Source File: Camera2FilterActivity.java    From EZFilter with MIT License 6 votes vote down vote up
@Override
public void onOpened(CameraDevice camera) { // 打开摄像头
    mCameraDevice = camera;
    mRenderPipeline = EZFilter.input(mCameraDevice, mPreviewSize)
            .addFilter(mCurrentRender)
            .enableRecord("/sdcard/recordCamera2.mp4", true, true) // 支持录制为视频
            .into(mRenderView);

    FBORender startRender = mRenderPipeline.getStartPointRender();
    if (startRender instanceof ISupportTakePhoto) {
        mSupportTakePhoto = (ISupportTakePhoto) startRender;
    }
    for (GLRender render : mRenderPipeline.getEndPointRenders()) {
        if (render instanceof ISupportRecord) {
            mSupportRecord = (ISupportRecord) render;
        }
    }
}
 
Example #12
Source File: Camera2.java    From SimpleVideoEditor with Apache License 2.0 5 votes vote down vote up
/**
 * Captures a still picture.
 */
void captureStillPicture() {
    try {
        CaptureRequest.Builder captureRequestBuilder = mCamera.createCaptureRequest(
                CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureRequestBuilder.addTarget(mImageReader.getSurface());
        captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE,
                mCaptureRequestBuilder.get(CaptureRequest.CONTROL_AF_MODE));
        updateFlashLightState();
        // Calculate JPEG orientation.
        @SuppressWarnings("ConstantConditions")
        int sensorOrientation = mCameraCharacteristics.get(
                CameraCharacteristics.SENSOR_ORIENTATION);
        captureRequestBuilder.set(CaptureRequest.JPEG_ORIENTATION,
                (sensorOrientation +
                        mDisplayOrientation * (mConfig.getCurrentFacing() == Constants.CAMERA_FACING_FRONT ? 1 : -1) +
                        360) % 360);
        // Stop preview and capture a still picture.
        mCaptureSession.stopRepeating();
        mCaptureSession.capture(captureRequestBuilder.build(),
                new CameraCaptureSession.CaptureCallback() {
                    @Override
                    public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                                   @NonNull CaptureRequest request,
                                                   @NonNull TotalCaptureResult result) {
                        unlockFocus();
                    }
                }, null);
    } catch (CameraAccessException e) {
        Log.e(TAG, "Cannot capture a still picture.", e);
    }
}
 
Example #13
Source File: Camera2Source.java    From Camera2Vision with Apache License 2.0 5 votes vote down vote up
/**
 * Capture a still picture. This method should be called when we get a response in
 * {@link #mCaptureCallback} from both {@link #lockFocus()}.
 */
private void captureStillPicture() {
    try {
        if (null == mCameraDevice) {
            return;
        }
        if(mShutterCallback != null) {
            mShutterCallback.onShutter();
        }
        // This is the CaptureRequest.Builder that we use to take a picture.
        final CaptureRequest.Builder captureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(mImageReaderStill.getSurface());

        // Use the same AE and AF modes as the preview.
        captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, mFocusMode);
        if(mFlashSupported) {
            captureBuilder.set(CaptureRequest.CONTROL_AE_MODE, mFlashMode);
        }

        // Orientation
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getOrientation(mDisplayOrientation));

        CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                unlockFocus();
            }
        };

        mCaptureSession.stopRepeating();
        mCaptureSession.capture(captureBuilder.build(), CaptureCallback, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
 
Example #14
Source File: VideoCaptureCamera2.java    From 365browser with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpened(CameraDevice cameraDevice) {
    mCameraDevice = cameraDevice;
    changeCameraStateAndNotify(CameraState.CONFIGURING);
    if (createPreviewObjectsAndStartPreview()) return;

    changeCameraStateAndNotify(CameraState.STOPPED);
    nativeOnError(mNativeVideoCaptureDeviceAndroid, "Error configuring camera");
}
 
Example #15
Source File: CameraFragment.java    From io2015-codelabs with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpened(CameraDevice cameraDevice) {
    Log.d(TAG, "onOpened: ");
    // This method is called when the camera is opened.  We start camera preview here.
    mCameraOpenCloseLock.release();
    mCameraDevice = cameraDevice;
    createCameraPreviewSession();
}
 
Example #16
Source File: CameraH264Activity.java    From AndroidDemo with MIT License 5 votes vote down vote up
CameraConfig(String cameraId, CameraCharacteristics characteristics, @NonNull CameraDevice.StateCallback deviceStateCallback, @NonNull Handler handler) {
    this.cameraId = cameraId;
    Integer orientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
    this.orientation = orientation == null ? 0 : orientation;
    Integer level = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
    fullSupport = level != null && level == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL;
    this.deviceStateCallback = deviceStateCallback;
    this.handler = handler;
}
 
Example #17
Source File: CameraWrapper.java    From DeviceConnect-Android with MIT License 5 votes vote down vote up
/**
 * カメラのライトをONにする.
 *
 * @param listener 実際にライトがONになったタイミングで実行されるリスナー
 * @param handler リスナーを実行するハンドラー. リスナーを指定する場合は必須
 * @throws CameraWrapperException カメラに何らかの致命的なエラーが発生した場合
 */
public synchronized void turnOnTorch(final @Nullable TorchOnListener listener,
                                     final @Nullable Handler handler) throws CameraWrapperException {
    if (listener != null && handler == null) {
        throw new IllegalArgumentException("handler is mandatory if listener is specified.");
    }
    if (mIsTouchOn) {
        notifyTorchOnEvent(listener, handler);
        return;
    }
    try {
        CameraDevice cameraDevice = openCamera();
        mCaptureSession = createCaptureSession(cameraDevice);
        final CaptureRequest.Builder requestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        if (mIsPreview) {
            if (mPreviewSurface != null) {
                requestBuilder.addTarget(mPreviewSurface);
            }
            if (mTargetSurface != null) {
                requestBuilder.addTarget(mTargetSurface);
            }
        }
        if (mIsRecording) {
            requestBuilder.addTarget(mRecordingSurface);
        }

        if (!mIsPreview && !mIsRecording) {
            requestBuilder.addTarget(mDummyPreviewReader.getSurface());
        }
        requestBuilder.set(CaptureRequest.FLASH_MODE, CameraMetadata.FLASH_MODE_TORCH);
        mCaptureSession.setRepeatingRequest(requestBuilder.build(), null, mBackgroundHandler);
        mUseTouch = true;
        mIsTouchOn = true;
        notifyTorchOnEvent(listener, handler);
    } catch (CameraAccessException e) {
        throw new CameraWrapperException(e);
    }
}
 
Example #18
Source File: CaptureHighSpeedVideoMode.java    From Android-Slow-Motion-Camera2 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
    mCameraDevice = cameraDevice;
    startPreview();
    mCameraOpenCloseLock.release();
    if (null != mTextureView) {
        configureTransform(mTextureView.getWidth(), mTextureView.getHeight());
    }
}
 
Example #19
Source File: Camera2.java    From SimpleVideoEditor with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpened(@NonNull CameraDevice camera) {
    mCamera = camera;
    mConfig.setCameraOpened(true);
    mCallback.onCameraOpened();
    startPreviewSession();
}
 
Example #20
Source File: CameraActivity.java    From Chinese-number-gestures-recognition with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
public void onDisconnected(CameraDevice camera) {//关闭摄像头
    if (null != mCameraDevice) {
        mCameraDevice.close();
        CameraActivity.this.mCameraDevice = null;
    }
}
 
Example #21
Source File: Camera2Session.java    From webrtc_android with MIT License 5 votes vote down vote up
@Override
public void onClosed(CameraDevice camera) {
    checkIsOnCameraThread();

    Logging.d(TAG, "Camera device closed.");
    events.onCameraClosed(Camera2Session.this);
}
 
Example #22
Source File: CameraTexture2.java    From PHONK with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void onDisconnected(@NonNull CameraDevice cameraDevice) {
    MLog.d("onDisconnected");
    mCameraOpenCloseLock.release();
    cameraDevice.close();
    mCameraDevice = null;
}
 
Example #23
Source File: CameraConnectionFragment.java    From fritz-examples with MIT License 5 votes vote down vote up
@Override
public void onError(final CameraDevice cd, final int error) {
    cameraOpenCloseLock.release();
    cd.close();
    cameraDevice = null;
    final Activity activity = getActivity();
    if (null != activity) {
        activity.finish();
    }
}
 
Example #24
Source File: CameraOps.java    From android-HdrViewfinder with Apache License 2.0 5 votes vote down vote up
/**
 * Get a request builder for the current camera.
 */
public CaptureRequest.Builder createCaptureRequest(int template) throws CameraAccessException {
    CameraDevice device = mCameraDevice;
    if (device == null) {
        throw new IllegalStateException("Can't get requests when no camera is open");
    }
    return device.createCaptureRequest(template);
}
 
Example #25
Source File: Camera2Controller.java    From pixelvisualcorecamera with Apache License 2.0 5 votes vote down vote up
@Override
public void onError(@NonNull CameraDevice cameraDevice, int error) {
  Log.w(TAG, "CameraDevice onError() id: " + cameraDevice.getId() + " error: " + error);
  openCloseLock.release();
  cameraDevice.close();
  Camera2Controller.this.cameraDevice = null;
}
 
Example #26
Source File: Camera2Manager.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpened(@NonNull CameraDevice cameraDevice) {
    Camera2Manager.this.mCameraDevice = cameraDevice;
    if (mCameraOpenListener != null) {
        mUiiHandler.post(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(mCameraId) && mPreviewSize != null)
                    mCameraOpenListener.onCameraOpened(mCameraId, mPreviewSize, Camera2Manager.this);
            }
        });
    }
}
 
Example #27
Source File: Camera2RawFragment.java    From android-Camera2Raw with Apache License 2.0 5 votes vote down vote up
@Override
public void onError(CameraDevice cameraDevice, int error) {
    Log.e(TAG, "Received camera device error: " + error);
    synchronized (mCameraStateLock) {
        mState = STATE_CLOSED;
        mCameraOpenCloseLock.release();
        cameraDevice.close();
        mCameraDevice = null;
    }
    Activity activity = getActivity();
    if (null != activity) {
        activity.finish();
    }
}
 
Example #28
Source File: CameraConnectionFragment.java    From next18-ai-in-motion with Apache License 2.0 5 votes vote down vote up
@Override
public void onOpened(final CameraDevice cd) {
  // This method is called when the camera is opened.  We start camera preview here.
  cameraOpenCloseLock.release();
  cameraDevice = cd;
  createCameraPreviewSession();
}
 
Example #29
Source File: CameraPluginActivity.java    From unity-android-native-camera with MIT License 5 votes vote down vote up
private CaptureRequest createCaptureRequest() {
    try {
        CaptureRequest.Builder builder =
                _cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);

        builder.set(CaptureRequest.CONTROL_AF_MODE, CameraMetadata.CONTROL_AF_MODE_CONTINUOUS_PICTURE);

        builder.addTarget(_previewSurface);
        return builder.build();
    } catch (CameraAccessException e) {
        e.printStackTrace();
        return null;
    }
}
 
Example #30
Source File: Camera2Manager.java    From sandriosCamera with MIT License 5 votes vote down vote up
private void captureStillPicture() {
    try {
        if (null == cameraDevice) {
            return;
        }
        final CaptureRequest.Builder captureBuilder =
                cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(imageReader.getSurface());

        captureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, getPhotoOrientation(configurationProvider.getSensorPosition()));

        CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session,
                                           @NonNull CaptureRequest request,
                                           @NonNull TotalCaptureResult result) {
                Log.d(TAG, "onCaptureCompleted: ");
            }
        };

        captureSession.stopRepeating();
        captureSession.capture(captureBuilder.build(), CaptureCallback, null);

    } catch (CameraAccessException e) {
        Log.e(TAG, "Error during capturing picture");
    }
}