Search in sources :

Example 61 with CameraAccessException

use of android.hardware.camera2.CameraAccessException in project cameraview by google.

the class Camera2 method chooseCameraIdByFacing.

/**
     * <p>Chooses a camera ID by the specified camera facing ({@link #mFacing}).</p>
     * <p>This rewrites {@link #mCameraId}, {@link #mCameraCharacteristics}, and optionally
     * {@link #mFacing}.</p>
     */
private boolean chooseCameraIdByFacing() {
    try {
        int internalFacing = INTERNAL_FACINGS.get(mFacing);
        final String[] ids = mCameraManager.getCameraIdList();
        if (ids.length == 0) {
            // No camera
            throw new RuntimeException("No camera available.");
        }
        for (String id : ids) {
            CameraCharacteristics characteristics = mCameraManager.getCameraCharacteristics(id);
            Integer level = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
            if (level == null || level == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
                continue;
            }
            Integer internal = characteristics.get(CameraCharacteristics.LENS_FACING);
            if (internal == null) {
                throw new NullPointerException("Unexpected state: LENS_FACING null");
            }
            if (internal == internalFacing) {
                mCameraId = id;
                mCameraCharacteristics = characteristics;
                return true;
            }
        }
        // Not found
        mCameraId = ids[0];
        mCameraCharacteristics = mCameraManager.getCameraCharacteristics(mCameraId);
        Integer level = mCameraCharacteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
        if (level == null || level == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
            return false;
        }
        Integer internal = mCameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
        if (internal == null) {
            throw new NullPointerException("Unexpected state: LENS_FACING null");
        }
        for (int i = 0, count = INTERNAL_FACINGS.size(); i < count; i++) {
            if (INTERNAL_FACINGS.valueAt(i) == internal) {
                mFacing = INTERNAL_FACINGS.keyAt(i);
                return true;
            }
        }
        // The operation can reach here when the only camera device is an external one.
        // We treat it as facing back.
        mFacing = Constants.FACING_BACK;
        return true;
    } catch (CameraAccessException e) {
        throw new RuntimeException("Failed to get a list of camera devices", e);
    }
}
Also used : CameraAccessException(android.hardware.camera2.CameraAccessException) CameraCharacteristics(android.hardware.camera2.CameraCharacteristics)

Example 62 with CameraAccessException

use of android.hardware.camera2.CameraAccessException in project material-camera by afollestad.

the class Camera2Fragment method captureStillPicture.

/**
     * Capture a still picture. This method should be called when we get a response in
     * {@link #mCaptureCallback} from both {@link #takeStillshot()}.
     */
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);
        setFlashMode(captureBuilder);
        // Orientation
        CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
        //noinspection ConstantConditions,ResourceType
        @Degrees.DegreeUnits final int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        // default camera orientation used to be 90 degrees, for Nexus 5X, 6P it is 270 degrees
        if (sensorOrientation == Degrees.DEGREES_270) {
            displayRotation += 2 % 3;
        }
        captureBuilder.set(CaptureRequest.JPEG_ORIENTATION, ORIENTATIONS.get(displayRotation));
        CameraCaptureSession.CaptureCallback CaptureCallback = new CameraCaptureSession.CaptureCallback() {

            @Override
            public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
                Log.d("stillshot", "onCaptureCompleted");
                unlockFocus();
            }
        };
        mPreviewSession.stopRepeating();
        mPreviewSession.capture(captureBuilder.build(), CaptureCallback, null);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}
Also used : Activity(android.app.Activity) CameraManager(android.hardware.camera2.CameraManager) TotalCaptureResult(android.hardware.camera2.TotalCaptureResult) CameraCaptureSession(android.hardware.camera2.CameraCaptureSession) Point(android.graphics.Point) CameraAccessException(android.hardware.camera2.CameraAccessException) NonNull(android.support.annotation.NonNull) CameraCharacteristics(android.hardware.camera2.CameraCharacteristics) CaptureRequest(android.hardware.camera2.CaptureRequest)

Example 63 with CameraAccessException

use of android.hardware.camera2.CameraAccessException in project material-camera by afollestad.

the class Camera2Fragment method openCamera.

@Override
public void openCamera() {
    final int width = mTextureView.getWidth();
    final int height = mTextureView.getHeight();
    final Activity activity = getActivity();
    if (null == activity || activity.isFinishing())
        return;
    final CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);
    try {
        if (!mCameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) {
            throwError(new Exception("Time out waiting to lock camera opening."));
            return;
        }
        if (mInterface.getFrontCamera() == null || mInterface.getBackCamera() == null) {
            for (String cameraId : manager.getCameraIdList()) {
                if (cameraId == null)
                    continue;
                if (mInterface.getFrontCamera() != null && mInterface.getBackCamera() != null)
                    break;
                CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);
                //noinspection ConstantConditions
                int facing = characteristics.get(CameraCharacteristics.LENS_FACING);
                if (facing == CameraCharacteristics.LENS_FACING_FRONT)
                    mInterface.setFrontCamera(cameraId);
                else if (facing == CameraCharacteristics.LENS_FACING_BACK)
                    mInterface.setBackCamera(cameraId);
            }
        }
        switch(mInterface.getCurrentCameraPosition()) {
            case CAMERA_POSITION_FRONT:
                setImageRes(mButtonFacing, mInterface.iconRearCamera());
                break;
            case CAMERA_POSITION_BACK:
                setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                break;
            case CAMERA_POSITION_UNKNOWN:
            default:
                if (getArguments().getBoolean(CameraIntentKey.DEFAULT_TO_FRONT_FACING, false)) {
                    // Check front facing first
                    if (mInterface.getFrontCamera() != null) {
                        setImageRes(mButtonFacing, mInterface.iconRearCamera());
                        mInterface.setCameraPosition(CAMERA_POSITION_FRONT);
                    } else {
                        setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                        if (mInterface.getBackCamera() != null)
                            mInterface.setCameraPosition(CAMERA_POSITION_BACK);
                        else
                            mInterface.setCameraPosition(CAMERA_POSITION_UNKNOWN);
                    }
                } else {
                    // Check back facing first
                    if (mInterface.getBackCamera() != null) {
                        setImageRes(mButtonFacing, mInterface.iconFrontCamera());
                        mInterface.setCameraPosition(CAMERA_POSITION_BACK);
                    } else {
                        setImageRes(mButtonFacing, mInterface.iconRearCamera());
                        if (mInterface.getFrontCamera() != null)
                            mInterface.setCameraPosition(CAMERA_POSITION_FRONT);
                        else
                            mInterface.setCameraPosition(CAMERA_POSITION_UNKNOWN);
                    }
                }
                break;
        }
        // Choose the sizes for camera preview and video recording
        CameraCharacteristics characteristics = manager.getCameraCharacteristics((String) mInterface.getCurrentCameraId());
        StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        assert map != null;
        // For still image captures, we use the largest available size.
        Size largest = Collections.max(Arrays.asList(map.getOutputSizes(ImageFormat.JPEG)), new CompareSizesByArea());
        // Find out if we need to swap dimension to get the preview size relative to sensor
        // coordinate.
        int displayRotation = activity.getWindowManager().getDefaultDisplay().getRotation();
        //noinspection ConstantConditions,ResourceType
        @Degrees.DegreeUnits final int sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        @Degrees.DegreeUnits int deviceRotation = Degrees.getDisplayRotation(getActivity());
        mDisplayOrientation = Degrees.getDisplayOrientation(sensorOrientation, deviceRotation, getCurrentCameraPosition() == CAMERA_POSITION_FRONT);
        Log.d("Camera2Fragment", String.format("Orientations: Sensor = %d˚, Device = %d˚, Display = %d˚", sensorOrientation, deviceRotation, mDisplayOrientation));
        if (mInterface.useStillshot()) {
            boolean swappedDimensions = false;
            switch(displayRotation) {
                case Surface.ROTATION_0:
                case Surface.ROTATION_180:
                    if (sensorOrientation == Degrees.DEGREES_90 || sensorOrientation == Degrees.DEGREES_270) {
                        swappedDimensions = true;
                    }
                    break;
                case Surface.ROTATION_90:
                case Surface.ROTATION_270:
                    if (sensorOrientation == Degrees.DEGREES_0 || sensorOrientation == Degrees.DEGREES_180) {
                        swappedDimensions = true;
                    }
                    break;
                default:
                    Log.e("stillshot", "Display rotation is invalid: " + displayRotation);
            }
            Point displaySize = new Point();
            activity.getWindowManager().getDefaultDisplay().getSize(displaySize);
            int rotatedPreviewWidth = width;
            int rotatedPreviewHeight = height;
            int maxPreviewWidth = displaySize.x;
            int maxPreviewHeight = displaySize.y;
            if (swappedDimensions) {
                rotatedPreviewWidth = height;
                rotatedPreviewHeight = width;
                maxPreviewWidth = displaySize.y;
                maxPreviewHeight = displaySize.x;
            }
            if (maxPreviewWidth > MAX_PREVIEW_WIDTH) {
                maxPreviewWidth = MAX_PREVIEW_WIDTH;
            }
            if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) {
                maxPreviewHeight = MAX_PREVIEW_HEIGHT;
            }
            // Danger, W.R.! Attempting to use too large a preview size could  exceed the camera
            // bus' bandwidth limitation, resulting in gorgeous previews but the storage of
            // garbage capture data.
            mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest);
            mImageReader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG, 2);
            mImageReader.setOnImageAvailableListener(new ImageReader.OnImageAvailableListener() {

                @Override
                public void onImageAvailable(ImageReader reader) {
                    Image image = reader.acquireNextImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    final byte[] bytes = new byte[buffer.remaining()];
                    buffer.get(bytes);
                    final File outputPic = getOutputPictureFile();
                    FileOutputStream output = null;
                    try {
                        output = new FileOutputStream(outputPic);
                        output.write(bytes);
                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {
                        image.close();
                        if (null != output) {
                            try {
                                output.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    Log.d("stillshot", "picture saved to disk - jpeg, size: " + bytes.length);
                    mOutputUri = Uri.fromFile(outputPic).toString();
                    mInterface.onShowStillshot(mOutputUri);
                }
            }, mBackgroundHandler);
        } else {
            mMediaRecorder = new MediaRecorder();
            mVideoSize = chooseVideoSize((BaseCaptureInterface) activity, map.getOutputSizes(MediaRecorder.class));
            mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height, mVideoSize);
        }
        int orientation = VideoStreamView.getScreenOrientation(activity);
        if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE || orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());
        } else {
            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());
        }
        mAfAvailable = false;
        int[] afModes = characteristics.get(CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES);
        if (afModes != null) {
            for (int i : afModes) {
                if (i != 0) {
                    mAfAvailable = true;
                    break;
                }
            }
        }
        configureTransform(width, height);
        mInterface.setFlashModes(CameraUtil.getSupportedFlashModes(getActivity(), characteristics));
        onFlashModesLoaded();
        // noinspection ResourceType
        manager.openCamera((String) mInterface.getCurrentCameraId(), mStateCallback, null);
    } catch (CameraAccessException e) {
        throwError(new Exception("Cannot access the camera.", e));
    } catch (NullPointerException e) {
        // Currently an NPE is thrown when the Camera2API is used but not supported on the
        // device this code runs.
        new ErrorDialog().show(getFragmentManager(), "dialog");
    } catch (InterruptedException e) {
        throwError(new Exception("Interrupted while trying to lock camera opening.", e));
    }
}
Also used : Size(android.util.Size) Activity(android.app.Activity) Image(android.media.Image) CameraAccessException(android.hardware.camera2.CameraAccessException) ImageReader(android.media.ImageReader) CameraManager(android.hardware.camera2.CameraManager) StreamConfigurationMap(android.hardware.camera2.params.StreamConfigurationMap) Point(android.graphics.Point) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) Point(android.graphics.Point) IOException(java.io.IOException) CameraAccessException(android.hardware.camera2.CameraAccessException) FileOutputStream(java.io.FileOutputStream) CameraCharacteristics(android.hardware.camera2.CameraCharacteristics) MediaRecorder(android.media.MediaRecorder) File(java.io.File)

Example 64 with CameraAccessException

use of android.hardware.camera2.CameraAccessException in project platform_frameworks_base by android.

the class CameraTestUtils method configureCameraSession.

/**
     * Configure a new camera session with output surfaces and type.
     *
     * @param camera The CameraDevice to be configured.
     * @param outputSurfaces The surface list that used for camera output.
     * @param listener The callback CameraDevice will notify when capture results are available.
     */
public static CameraCaptureSession configureCameraSession(CameraDevice camera, List<Surface> outputSurfaces, boolean isHighSpeed, CameraCaptureSession.StateCallback listener, Handler handler) throws CameraAccessException {
    BlockingSessionCallback sessionListener = new BlockingSessionCallback(listener);
    if (isHighSpeed) {
        camera.createConstrainedHighSpeedCaptureSession(outputSurfaces, sessionListener, handler);
    } else {
        camera.createCaptureSession(outputSurfaces, sessionListener, handler);
    }
    CameraCaptureSession session = sessionListener.waitAndGetSession(SESSION_CONFIGURE_TIMEOUT_MS);
    assertFalse("Camera session should not be a reprocessable session", session.isReprocessable());
    String sessionType = isHighSpeed ? "High Speed" : "Normal";
    assertTrue("Capture session type must be " + sessionType, isHighSpeed == CameraConstrainedHighSpeedCaptureSession.class.isAssignableFrom(session.getClass()));
    return session;
}
Also used : BlockingSessionCallback(com.android.ex.camera2.blocking.BlockingSessionCallback) CameraCaptureSession(android.hardware.camera2.CameraCaptureSession)

Example 65 with CameraAccessException

use of android.hardware.camera2.CameraAccessException in project platform_frameworks_base by android.

the class CameraTestUtils method getSupportedSizeForClass.

/**
     * Get the available output sizes for the given class.
     *
     */
public static Size[] getSupportedSizeForClass(Class klass, String cameraId, CameraManager cameraManager) throws CameraAccessException {
    CameraCharacteristics properties = cameraManager.getCameraCharacteristics(cameraId);
    assertNotNull("Can't get camera characteristics!", properties);
    if (VERBOSE) {
        Log.v(TAG, "get camera characteristics for camera: " + cameraId);
    }
    StreamConfigurationMap configMap = properties.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
    Size[] availableSizes = configMap.getOutputSizes(klass);
    assertArrayNotEmpty(availableSizes, "availableSizes should not be empty for class: " + klass);
    Size[] highResAvailableSizes = configMap.getHighResolutionOutputSizes(ImageFormat.PRIVATE);
    if (highResAvailableSizes != null && highResAvailableSizes.length > 0) {
        Size[] allSizes = new Size[availableSizes.length + highResAvailableSizes.length];
        System.arraycopy(availableSizes, 0, allSizes, 0, availableSizes.length);
        System.arraycopy(highResAvailableSizes, 0, allSizes, availableSizes.length, highResAvailableSizes.length);
        availableSizes = allSizes;
    }
    if (VERBOSE)
        Log.v(TAG, "Supported sizes are: " + Arrays.deepToString(availableSizes));
    return availableSizes;
}
Also used : Size(android.util.Size) CameraCharacteristics(android.hardware.camera2.CameraCharacteristics) StreamConfigurationMap(android.hardware.camera2.params.StreamConfigurationMap)

Aggregations

ArrayList (java.util.ArrayList)50 Surface (android.view.Surface)42 OutputConfiguration (android.hardware.camera2.params.OutputConfiguration)40 CameraAccessException (android.hardware.camera2.CameraAccessException)35 CaptureRequest (android.hardware.camera2.CaptureRequest)35 CameraCharacteristics (android.hardware.camera2.CameraCharacteristics)25 StreamConfigurationMap (android.hardware.camera2.params.StreamConfigurationMap)21 RemoteException (android.os.RemoteException)15 BlockingSessionCallback (com.android.ex.camera2.blocking.BlockingSessionCallback)14 CameraCaptureSession (android.hardware.camera2.CameraCaptureSession)12 Size (android.util.Size)11 ICameraService (android.hardware.ICameraService)10 CaptureCallback (android.hardware.camera2.CameraCaptureSession.CaptureCallback)10 CameraMetadataNative (android.hardware.camera2.impl.CameraMetadataNative)10 ServiceSpecificException (android.os.ServiceSpecificException)10 CameraManager (android.hardware.camera2.CameraManager)6 NonNull (android.annotation.NonNull)5 CameraInfo (android.hardware.CameraInfo)5 InputConfiguration (android.hardware.camera2.params.InputConfiguration)5 SubmitInfo (android.hardware.camera2.utils.SubmitInfo)5