use of android.hardware.camera2.CameraManager in project android_frameworks_base by AOSPA.
the class CameraTestUtils method getSupportedSizeForFormat.
/**
* Get the available output sizes for the user-defined {@code format}.
*
* <p>Note that implementation-defined/hidden formats are not supported.</p>
*/
public static Size[] getSupportedSizeForFormat(int format, 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(format);
assertArrayNotEmpty(availableSizes, "availableSizes should not be empty for format: " + format);
Size[] highResAvailableSizes = configMap.getHighResolutionOutputSizes(format);
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;
}
use of android.hardware.camera2.CameraManager 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;
}
use of android.hardware.camera2.CameraManager 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();
}
}
use of android.hardware.camera2.CameraManager 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));
}
}
use of android.hardware.camera2.CameraManager in project material-camera by afollestad.
the class CameraUtil method hasCamera2.
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static boolean hasCamera2(Context context, boolean stillShot) {
if (context == null)
return false;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)
return false;
if (stillShot && ManufacturerUtil.isSamsungDevice())
return false;
try {
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String[] idList = manager.getCameraIdList();
boolean notNull = true;
if (idList.length == 0) {
notNull = false;
} else {
for (final String str : idList) {
if (str == null || str.trim().isEmpty()) {
notNull = false;
break;
}
final CameraCharacteristics characteristics = manager.getCameraCharacteristics(str);
//noinspection ConstantConditions
final int supportLevel = characteristics.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL);
if (supportLevel == CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY) {
notNull = false;
break;
}
}
}
return notNull;
} catch (Throwable t) {
t.printStackTrace();
return false;
}
}
Aggregations