Search in sources :

Example 31 with CameraCharacteristics

use of android.hardware.camera2.CameraCharacteristics in project android_frameworks_base by AOSPA.

the class LegacyFaceDetectMapper method mapResultFaces.

/**
     * Update the {@code result} camera metadata map with the new value for the
     * {@code statistics.faces} and {@code statistics.faceDetectMode}.
     *
     * <p>Face detect callbacks are processed in the background, and each call to
     * {@link #mapResultFaces} will have the latest faces as reflected by the camera1 callbacks.</p>
     *
     * <p>If the scene mode was set to {@code FACE_PRIORITY} but face detection is disabled,
     * the camera will still run face detection in the background, but no faces will be reported
     * in the capture result.</p>
     *
     * @param result a non-{@code null} result
     * @param legacyRequest a non-{@code null} request (read-only)
     */
public void mapResultFaces(CameraMetadataNative result, LegacyRequest legacyRequest) {
    checkNotNull(result, "result must not be null");
    checkNotNull(legacyRequest, "legacyRequest must not be null");
    Camera.Face[] faces, previousFaces;
    int fdMode;
    boolean fdScenePriority;
    synchronized (mLock) {
        fdMode = mFaceDetectReporting ? STATISTICS_FACE_DETECT_MODE_SIMPLE : STATISTICS_FACE_DETECT_MODE_OFF;
        if (mFaceDetectReporting) {
            faces = mFaces;
        } else {
            faces = null;
        }
        fdScenePriority = mFaceDetectScenePriority;
        previousFaces = mFacesPrev;
        mFacesPrev = faces;
    }
    CameraCharacteristics characteristics = legacyRequest.characteristics;
    CaptureRequest request = legacyRequest.captureRequest;
    Size previewSize = legacyRequest.previewSize;
    Camera.Parameters params = legacyRequest.parameters;
    Rect activeArray = characteristics.get(CameraCharacteristics.SENSOR_INFO_ACTIVE_ARRAY_SIZE);
    ZoomData zoomData = ParameterUtils.convertScalerCropRegion(activeArray, request.get(CaptureRequest.SCALER_CROP_REGION), previewSize, params);
    List<Face> convertedFaces = new ArrayList<>();
    if (faces != null) {
        for (Camera.Face face : faces) {
            if (face != null) {
                convertedFaces.add(ParameterUtils.convertFaceFromLegacy(face, activeArray, zoomData));
            } else {
                Log.w(TAG, "mapResultFaces - read NULL face from camera1 device");
            }
        }
    }
    if (DEBUG && previousFaces != faces) {
        // Log only in verbose and IF the faces changed
        Log.v(TAG, "mapResultFaces - changed to " + ListUtils.listToString(convertedFaces));
    }
    result.set(CaptureResult.STATISTICS_FACES, convertedFaces.toArray(new Face[0]));
    result.set(CaptureResult.STATISTICS_FACE_DETECT_MODE, fdMode);
    // Override scene mode with FACE_PRIORITY if the request was using FACE_PRIORITY
    if (fdScenePriority) {
        result.set(CaptureResult.CONTROL_SCENE_MODE, CONTROL_SCENE_MODE_FACE_PRIORITY);
    }
}
Also used : Rect(android.graphics.Rect) Size(android.util.Size) ArrayList(java.util.ArrayList) CameraCharacteristics(android.hardware.camera2.CameraCharacteristics) ZoomData(android.hardware.camera2.legacy.ParameterUtils.ZoomData) CaptureRequest(android.hardware.camera2.CaptureRequest) Camera(android.hardware.Camera) Face(android.hardware.camera2.params.Face)

Example 32 with CameraCharacteristics

use of android.hardware.camera2.CameraCharacteristics in project streaming-android by red5pro.

the class PublishCamera2Test method onCreateView.

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.publish_test, container, false);
    preview = (R5VideoView) rootView.findViewById(R.id.videoPreview);
    String b = getActivity().getPackageName();
    // Create the configuration from the values.xml
    R5Configuration config = new R5Configuration(R5StreamProtocol.RTSP, TestContent.GetPropertyString("host"), TestContent.GetPropertyInt("port"), TestContent.GetPropertyString("context"), TestContent.GetPropertyFloat("publish_buffer_time"));
    config.setLicenseKey(TestContent.GetPropertyString("license_key"));
    config.setBundleID(b);
    R5Connection connection = new R5Connection(config);
    // setup a new stream using the connection
    publish = new R5Stream(connection);
    publish.audioController.sampleRate = TestContent.GetPropertyInt("sample_rate");
    // show all logging
    publish.setLogLevel(R5Stream.LOG_LEVEL_DEBUG);
    if (TestContent.GetPropertyBool("audio_on")) {
        // attach a microphone
        R5Microphone mic = new R5Microphone();
        publish.attachMic(mic);
    }
    preview.attachStream(publish);
    CameraManager manager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
    try {
        String[] camList = manager.getCameraIdList();
        for (String id : camList) {
            CameraCharacteristics info = manager.getCameraCharacteristics(id);
            if (info.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT) {
                camOrientation = info.get(CameraCharacteristics.SENSOR_ORIENTATION);
                camInfo = info;
                manager.openCamera(id, new CameraDevice.StateCallback() {

                    @Override
                    public void onOpened(@NonNull CameraDevice camera) {
                        if (preview == null)
                            return;
                        startPublish(camera);
                    }

                    @Override
                    public void onDisconnected(@NonNull CameraDevice camera) {
                    }

                    @Override
                    public void onError(@NonNull CameraDevice camera, int error) {
                    }
                }, null);
                break;
            }
        }
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
    return rootView;
}
Also used : R5Microphone(com.red5pro.streaming.source.R5Microphone) CameraDevice(android.hardware.camera2.CameraDevice) R5Stream(com.red5pro.streaming.R5Stream) CameraManager(android.hardware.camera2.CameraManager) ImageView(android.widget.ImageView) R5VideoView(com.red5pro.streaming.view.R5VideoView) View(android.view.View) CameraAccessException(android.hardware.camera2.CameraAccessException) R5Configuration(com.red5pro.streaming.config.R5Configuration) R5Connection(com.red5pro.streaming.R5Connection) CameraCharacteristics(android.hardware.camera2.CameraCharacteristics)

Example 33 with CameraCharacteristics

use of android.hardware.camera2.CameraCharacteristics 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 34 with CameraCharacteristics

use of android.hardware.camera2.CameraCharacteristics 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 35 with CameraCharacteristics

use of android.hardware.camera2.CameraCharacteristics 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)

Aggregations

CameraCharacteristics (android.hardware.camera2.CameraCharacteristics)61 Size (android.util.Size)31 Camera (android.hardware.Camera)25 Rect (android.graphics.Rect)20 CameraMetadataNative (android.hardware.camera2.impl.CameraMetadataNative)20 CaptureRequest (android.hardware.camera2.CaptureRequest)16 StreamConfigurationMap (android.hardware.camera2.params.StreamConfigurationMap)16 Parameters (android.hardware.Camera.Parameters)15 CameraManager (android.hardware.camera2.CameraManager)12 ZoomData (android.hardware.camera2.legacy.ParameterUtils.ZoomData)10 MeteringRectangle (android.hardware.camera2.params.MeteringRectangle)10 ServiceSpecificException (android.os.ServiceSpecificException)10 Range (android.util.Range)10 ArrayList (java.util.ArrayList)10 CameraAccessException (android.hardware.camera2.CameraAccessException)8 NonNull (android.annotation.NonNull)5 CameraInfo (android.hardware.Camera.CameraInfo)5 CameraInfo (android.hardware.CameraInfo)5 ICameraService (android.hardware.ICameraService)5 Face (android.hardware.camera2.params.Face)5