Camera2 API 采集视频并SurfaceView、TextureView 预览详解手机开发

如今Android推荐使用Camera2采集视频,之前也学习并写了视频预览的demo,但是一直理不清里面的勾勾绕绕,借着写这篇记录的过程,重新熟悉和理解Camera2流程。

名词

YUV

一种颜色编码的方法,在旧Camera API 常用的是NV21和YV12,可以转成RGB编码。

//获取Camera2 支持的颜色编码 
StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); 
map.getOutputFormats(); 

参考:图文详解 YUV420 数据格式

CameraManager

Camera2中负责管理、查询摄像头信息、打开可用的摄像头;

  1. cameraId 通过 getCameraIdList() 枚举得到,代表选择使用哪个摄像头;
  2. 设备信息通过 CameraCharacteristics getCameraCharacteristics(String cameraId) 可拿到;
  3. 打开摄像头 openCamera(String cameraId, CameraManager.StateCallback callback, Handler handler),StateCallback是接收设备状态的更新的回调,比如后面的cameraDevice就是通过stateCallback的onOpen()回调中拿到,Handler 表示打开摄像头的工作在具体哪个handler的looper中,也就是在哪个线程中执行,若为null则在当前线程;
CameraDevice

具体的摄像头,提供一组属性信息,描述硬件设备以及设备的可用设置和参数。

  1. CameraDevice是在CameraManager打开摄像头后,通过CameraDevice.StateCallback的回调中拿到的,是个异步的过程。
  2. createCaptureRequest() 创建CaptureRequest.Builder,CaptureRequest.Builder负责创建各种捕获图像的请求 CaptureRequest
  3. createCaptureSession() 负责创建捕获图像的会话
    CameraCaptureSession
CaptureRequest

一次捕获请求,通过CaptureRequest.Builder的build()创建,其实请求参数也是通过Buider来设置:
CaptureRequest.Builder常用的方法:

  1. addTarget(Surface outputTarget) 将surface添加到输出列表中,才可以显示在SurfaceView、TextureView或者输出到ImageReader中;
  2. set(Key< T> key, T value) 设置其他属性,参考CaptureRequest
CameraCaptureSession

捕获的会话Session,预览、拍照,都由该它进行控制的

  1. cameraCaptureSession是通过CameraDevice的 createCaptureSession(List< Surface>, CameraCaptureSession.StateCallback, Handler) 创建
  2. 拍照 capture(CaptureRequest, CameraCaptureSession.CaptureCallback, Handler);
  3. 预览 setRepeatingRequest(CaptureRequest, CameraCaptureSession.CaptureCallback, Handler);
在写代码的时候发现上面几个callback弄不清楚
  1. openCamera中的CameraManager.StateCallback 是 camra 创建过程中状态回调
  2. createCaptureSession中的CameraCaptureSession.StateCallback 是session创建过程中的状态回调
  3. capture 或 setRepeatingRequest的CameraCaptureSession.CaptureCallback 是在预览或者拍照request请求之后的回调

camera结构

camera结构

流程

1.初始化并打开Camera
// 初始化执行camera动作的线程和handler 
mCameraThread = new HandlerThread("texturePreviewThread"); 
mCameraThread.start(); 
mCameraHandler = new Handler(mCameraThread.getLooper()); 
 
CameraManager cameraManager = (CameraManager)getSystemService(CAMERA_SERVICE); 
for (String cameraId : cameraManager.getCameraIdList()) {
    
	// 查询摄像头属性 
	CameraCharacteristics characteristics = cameraManager.getCameraCharacteristics(cameraId);  
	if (characteristics.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_BACK) {
    // 选择后置摄像头 
		mCameraId = cameraId; 
		StreamConfigurationMap map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); 
		// 将最合适的预览尺寸设置给surfaceView或者textureView 
        mPreviewSize = getOptimalSize(map.getOutputSizes(SurfaceTexture.class), width, height); 
    } 
} 
 
// 打开camera创建cameraDevice的callback 
mDeviceCallback = new CameraDevice.StateCallback() {
    
	@Override 
    public void onOpened(@NonNull CameraDevice cameraDevice) {
    
		mCameraDevice = cameraDevice; 
        startPreview(); 
    } 
	@Override 
	public void onDisconnected(@NonNull CameraDevice cameraDevice) {
    
		if (mCameraDevice != null) {
    
			mCameraDevice.close(); 
			mCameraDevice = null; 
		} 
	} 
	@Override 
	public void onError(@NonNull CameraDevice cameraDevice, int i) {
    
		if (mCameraDevice != null) {
    
				mCameraDevice.close(); 
				mCameraDevice = null; 
		} 
	} 
}; 
// 打开摄像头 
cameraManager.openCamera(mCameraId, mDeviceCallback, mCameraHandler); 
/** 
* 获取预览的最适宜的长宽比例 
**/ 
private Size getOptimalSize(Size[] sizeMap, int width, int height) { 
	List<Size> sizeList = new ArrayList<>(); 
    for (Size option : sizeMap) { 
		if (width > height) { 
			if (option.getWidth() > width && option.getHeight() > height) { 
				sizeList.add(option); 
			} 
        } else { 
			if (option.getWidth() > height && option.getHeight() > width) { 
				sizeList.add(option); 
			} 
		} 
	} 
	if (sizeList.size() > 0) { 
		return Collections.min(sizeList, new Comparator<Size>() { 
			@Override 
			public int compare(Size lhs, Size rhs) { 
	            return Long.signum(lhs.getWidth() * lhs.getHeight() - rhs.getWidth() * rhs.getHeight()); 
			} 
	    }); 
    } 
	return sizeMap[0]; 
} 

什么时机开始调用initCamera()方法呢?

(1) SurfaceView,在SurfaceHolder.Callback的surfaceCreated()回调中调用
(2) TextureView,在TextureView.SurfaceTextureListener的onSurfaceTextureAvailable()调用初始化

2.开始预览

其实texureview和surfaceView基本上都差不多。

TextureView 预览

private void startPreview() {
    
	// 设置预览尺寸 
	mTextureView.getSurfaceTexture().setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight()); 
    try {
    
	    mCapterBuider = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); 
        Surface surface = new Surface(mTextureView.getSurfaceTexture()); 
		// 添加输出的surface 
		mCapterBuider.addTarget(surface); 
		// 创建CameraCaptureSession 
		mCameraDevice.createCaptureSession(Arrays.asList(surface), new CameraCaptureSession.StateCallback() {
    
			@Override 
            public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {
    
				try {
    
					mCapterSeesion = cameraCaptureSession; 
					// 设置为自动对焦 
					mCaptureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);mCapterSeesion.setRepeatingRequest(mCapterBuider.build(), null, mCameraHandler);// 设置成预览 
                } catch (CameraAccessException e) {
    
	                e.printStackTrace(); 
                } 
            } 
			@Override 
            public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
    
	            stopPreview(); 
            } 
		 }, mCameraHandler); 
	} catch (CameraAccessException e) {
    
		e.printStackTrace(); 
	} 
} 

SurfaceView预览

private void startPreview() { 
	try { 
		Surface mSurface = mSurfaceView.getHolder().getSurface(); 
        mCaptureBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW); 
        mCaptureBuilder.addTarget(mSurface); 
		mCameraDevice.createCaptureSession(Arrays.asList(mSurface), new CameraCaptureSession.StateCallback() { 
			@Override 
			public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) { 
	            try { 
                    mCaptureSession = cameraCaptureSession; 
                    // 自动对焦 
                    mCaptureBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE); 
                    CaptureRequest captureRequest = mCaptureBuilder.build(); 
                    mCaptureSession.setRepeatingRequest(captureRequest, mCaptureCallback, mCameraHandler); 
                } catch (CameraAccessException e) { 
	                e.printStackTrace(); 
                } 
            } 
 
            @Override 
            public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) { 
 
            } 
        }, mCameraHandler); 
        mState = STATE_PREVIEW; 
    } catch (CameraAccessException e) { 
        e.printStackTrace(); 
    } 
} 
3.停止预览
 
private void stopPreview() { 
    if (mCapterSeesion != null) { 
        mCapterSeesion.close(); 
        mCapterSeesion = null;  
    } 
    if (mCameraDevice != null) { 
        mCameraDevice.close(); 
        mCameraDevice = null;  
    }  
} 

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/tech/app/6278.html

(0)
上一篇 2021年7月17日 00:45
下一篇 2021年7月17日 00:45

相关推荐

发表回复

登录后才能评论