『壹』 V4L2的編程
v4L2是針對uvc免驅usb設備的編程框架 ,主要用於採集usb攝像頭等,編程模式如下: 打開視頻設備後,可以設置該視頻設備的屬性,例如裁剪、縮放等。這一步是可選的。在Linux編程中,一般使用ioctl函數來對設備的I/O通道進行管理:
extern int ioctl (int __fd, unsigned long int __request, …) __THROW;
__fd:設備的ID,例如剛才用open函數打開視頻通道後返回的cameraFd;
__request:具體的命令標志符。
在進行V4L2開發中,一般會用到以下的命令標志符:
VIDIOC_REQBUFS:分配內存
VIDIOC_QUERYBUF:把VIDIOC_REQBUFS中分配的數據緩存轉換成物理地址
VIDIOC_QUERYCAP:查詢驅動功能
VIDIOC_ENUM_FMT:獲取當前驅動支持的視頻格式
VIDIOC_S_FMT:設置當前驅動的頻捕獲格式
VIDIOC_G_FMT:讀取當前驅動的頻捕獲格式
VIDIOC_TRY_FMT:驗證當前驅動的顯示格式
VIDIOC_CROPCAP:查詢驅動的修剪能力
VIDIOC_S_CROP:設置視頻信號的邊框
VIDIOC_G_CROP:讀取視頻信號的邊框
VIDIOC_QBUF:把數據放回緩存隊列
VIDIOC_DQBUF:把數據從緩存中讀取出來
VIDIOC_STREAMON:開始視頻顯示函數
VIDIOC_STREAMOFF:結束視頻顯示函數
VIDIOC_QUERYSTD:檢查當前視頻設備支持的標准,例如PAL或NTSC。
這些IO調用,有些是必須的,有些是可選擇的。 1. 打開設備文件。
int fd=open(」/dev/video0″,O_RDWR);
2. 取得設備的capability,看看設備具有什麼功能,比如是否具有視頻輸入,或者音頻輸入輸出等。VIDIOC_QUERYCAP,struct v4l2_capability
v4l2_std_id std;
do {
ret= ioctl(fd, VIDIOC_QUERYSTD, &std);
} while (ret == -1 && errno == EAGAIN);
switch (std) {
case V4L2_STD_NTSC:
//……
case V4L2_STD_PAL:
//……
}
3. 選擇視頻輸入,一個視頻設備可以有多個視頻輸入。VIDIOC_S_INPUT,struct v4l2_input(可不要)
4. 設置視頻的制式和幀格式,制式包括PAL,NTSC,幀的格式個包括寬度和高度等。
VIDIOC_S_STD,VIDIOC_S_FMT,struct v4l2_std_id,struct v4l2_format
struct v4l2_format fmt;
/*
v4l2_format 結構如下:
struct v4l2_format
{
enum v4l2_buf_type type; // 數據流類型,必須永遠是V4L2_BUF_TYPE_VIDEO_CAPTURE
union
{
struct v4l2_pix_format pix;
struct v4l2_window win;
struct v4l2_vbi_format vbi;
__u8 raw_data[200];
} fmt;
};
struct v4l2_pix_format
{
__u32 width; // 寬,必須是16 的倍數
__u32 height; // 高,必須是16 的倍數
__u32 pixelformat; // 視頻數據存儲類型,例如是YUV 4 :2 :2 還是RGB
enum v4l2_field field;
__u32 bytesperline;
__u32 sizeimage;
enum v4l2_colorspace colorspace;
__u32 priv;
};
*/
樣例:
memset ( &fmt, 0, sizeof(fmt) );
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = 320;
fmt.fmt.pix.height = 240;
fmt.fmt.pix.pixelformat = V4L2_PIX_FMT_JPEG;
if (ioctl(fd, VIDIOC_S_FMT, &fmt) < 0)
{
printf(set format failed
);
//return 0;
}
5. 向驅動申請幀緩沖,一般不超過5個。struct v4l2_requestbuffers
struct v4l2_requestbuffers
{
__u32 count; // 緩存數量,也就是說在緩存隊列里保持多少張照片
enum v4l2_buf_type type; // 數據流類型,必須永遠是V4L2_BUF_TYPE_VIDEO_CAPTURE
enum v4l2_memory memory; // V4L2_MEMORY_MMAP 或 V4L2_MEMORY_USERPTR
__u32 reserved[2];
};
樣例:
struct v4l2_requestbuffers req;
memset(&req, 0, sizeof (req));
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if (ioctl(fd,VIDIOC_REQBUFS,&req) == -1)
{
perror(VIDIOC_REQBUFS error
);
//return -1;
}
6.申請物理內存
將申請到的幀緩沖映射到用戶空間,這樣就可以直接操作採集到的幀了,而不必去復制。將申請到的幀緩沖全部入隊列,以便存放採集到的數據.VIDIOC_QBUF,struct v4l2_buffer
VideoBuffer* buffers = calloc( req.count, sizeof(VideoBuffer) );
printf(sizeof(VideoBuffer) is %d
,sizeof(VideoBuffer));
struct v4l2_buffer buf;
for (numBufs = 0; numBufs < req.count; numBufs++)
{
memset( &buf, 0, sizeof(buf) );
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = numBufs;
if (ioctl(fd, VIDIOC_QUERYBUF, &buf) < 0)
{
printf(VIDIOC_QUERYBUF error
);
//return -1;
}
printf(buf len is %d
,sizeof(buf));
//內存映射
buffers[numBufs].length = buf.length;
buffers[numBufs].offset = (size_t) buf.m.offset;
buffers[numBufs].start = mmap (NULL, buf.length,PROT_READ | PROT_WRITE, MAP_SHARED, fd, buf.m.offset);
printf(buffers.length = %d,buffers.offset = %d ,buffers.start[0] = %d
,buffers[numBufs].length,buffers[numBufs].offset,buffers[numBufs].start[0]);
printf(buf2 len is %d
,sizeof(buffers[numBufs].start));
if (buffers[numBufs].start == MAP_FAILED)
{
perror(buffers error
);
//return -1;
}
if (ioctl (fd, VIDIOC_QBUF, &buf) < 0)
{
printf(VIDIOC_QBUF error
);
//return -1;
}
}
7. 開始視頻的採集。
enum v4l2_buf_type type;
type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (ioctl (fd, VIDIOC_STREAMON, &type) < 0)
{
printf(VIDIOC_STREAMON error
);
// return -1;
}
8. 出隊列以取得已採集數據的幀緩沖,取得原始採集數據。VIDIOC_DQBUF, 將緩沖重新入隊列尾,這樣可以循環採集。VIDIOC_QBUF
if (ioctl(fd, VIDIOC_DQBUF, &buf) < 0)
{
perror(VIDIOC_DQBUF failed.
);
//return -1;
}
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
unsigned char *ptcur = buffers[numBufs].start;
DEBUG(buf.bytesused = %d
,buf.bytesused);
int i1;
for(i1=0; i1<buf.bytesused; i1++)
{
if((buffers[numBufs].start[i1] == 0x000000FF) && (buffers[numBufs].start[i1+1] == 0x000000C4))
{
DEBUG(huffman table finded!
buf.bytesused = %d
FFC4 = %d
,buf.bytesused,i1);
break;
}
}
if(i1 == buf.bytesused)printf(huffman table don't exist!
);
int i;
for(i=0; i<buf.bytesused; i++)
{
if((buffers[numBufs].start[i] == 0x000000FF) && (buffers[numBufs].start[i+1] == 0x000000D8)) break;
ptcur++;
}
DEBUG(i=%d,FF=%02x,D8=%02x
,i,buffers[numBufs].start[i],buffers[numBufs].start[i+1]);
int imagesize =buf.bytesused - i;
DEBUG(buf.bytesused = %d
,buf.bytesused);
DEBUG (imagesize = %d
,imagesize);
9. 停止視頻的採集。VIDIOC_STREAMOFF
10. 關閉視頻設備。close(fd);
『貳』 android app 如何與uvc攝像頭通訊
來看看是怎麼操作UVC攝像頭的吧.我們實現了一個專門檢測UVC攝像頭的服務:UVCCameraService類,主要代碼如下:
監聽
mUSBMonitor = new USBMonitor(this, new USBMonitor.OnDeviceConnectListener() { @Override
public void onAttach(final UsbDevice device) {
Log.v(TAG, "onAttach:" + device);
mUSBMonitor.requestPermission(device);
} @Override
public void onConnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock, final boolean createNew) {
releaseCamera(); if (BuildConfig.DEBUG) Log.v(TAG, "onConnect:"); try { final UVCCamera camera = new MyUVCCamera();
camera.open(ctrlBlock);
camera.setStatusCallback(new IStatusCallback() { // ... uvc 攝像頭鏈接成功
Toast.makeText(UVCCameraService.this, "UVCCamera connected!", Toast.LENGTH_SHORT).show(); if (device != null)
cameras.append(device.getDeviceId(), camera);
}catch (Exception ex){
ex.printStackTrace();
}
} @Override
public void onDisconnect(final UsbDevice device, final USBMonitor.UsbControlBlock ctrlBlock) { // ... uvc 攝像頭斷開鏈接
if (device != null) {
UVCCamera camera = cameras.get(device.getDeviceId()); if (mUVCCamera == camera) {
mUVCCamera = null;
Toast.makeText(UVCCameraService.this, "UVCCamera disconnected!", Toast.LENGTH_SHORT).show();
liveData.postValue(null);
}
cameras.remove(device.getDeviceId());
}else {
Toast.makeText(UVCCameraService.this, "UVCCamera disconnected!", Toast.LENGTH_SHORT).show();
mUVCCamera = null;
liveData.postValue(null);
}
} @Override
public void onCancel(UsbDevice usbDevice) {
releaseCamera();
} @Override
public void onDettach(final UsbDevice device) {
Log.v(TAG, "onDettach:");
releaseCamera();// AppContext.getInstance().bus.post(new UVCCameraDisconnect());
}
});
這個類主要實現UVC攝像頭的監聽\鏈接\銷毀\反監聽.當有UVC攝像頭鏈接成功後,會創建一個mUVCCamera對象.
然後在MediaStream里, 我們改造了switchCamera,當參數傳2時,表示要切換到UVCCamera(0,1分別表示切換到後置\前置攝像頭).
創建
在創建攝像頭時,如果是要創建uvc攝像頭,那直接從服務裡面獲取之前創建的mUVCCamera實例:
if (mCameraId == 2) {
UVCCamera value = UVCCameraService.liveData.getValue(); if (value != null) { // uvc camera.
uvcCamera = value;
value.setPreviewSize(width, height,1, 30, UVCCamera.PIXEL_FORMAT_YUV420SP,1.0f); return; // value.startPreview();
}else{
Log.i(TAG, "NO UVCCamera");
uvcError = new Exception("no uvccamera connected!"); return;
} // mCameraId = 0;
}123456789101112131415
預覽
在預覽時,如果uvc攝像頭已經創建了,那執行uvc攝像頭的預覽操作:
UVCCamera value = uvcCamera;if (value != null) {
SurfaceTexture holder = mSurfaceHolderRef.get(); if (holder != null) {
value.setPreviewTexture(holder);
} try {
value.setFrameCallback(uvcFrameCallback, UVCCamera.PIXEL_FORMAT_YUV420SP/*UVCCamera.PIXEL_FORMAT_NV21*/);
value.startPreview();
cameraPreviewResolution.postValue(new int[]{width, height});
}catch (Throwable e){
uvcError = e;
}
}1234567891011121314
這里我們選的colorFormat為PIXEL_FORMAT_YUV420SP 相當於標准攝像頭的NV21格式.
關閉預覽
同理,關閉時,調用的是uvc攝像頭的關閉.
UVCCamera value = uvcCamera; if (value != null) {
value.stopPreview();
}1234
銷毀
因為我們這里並沒有實質性的創建,所以銷毀時也僅將實例置為null就可以了.
UVCCamera value = uvcCamera;if (value != null) { // value.destroy();
uvcCamera = null;
}12345
有了這些操作,我們看看上層怎麼調用,
首先需要在Manifest裡面增加若干代碼,具體詳見UVCCamera工程說明.如下:
<activity android:name=".UVCActivity" android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</activity>
然後,的代碼在UVCActivity里,這個類可以在library分支的myapplication工程里找到.即這里.
啟動或者停止UVC攝像頭推送:
public void onPush(View view) { // 非同步獲取到MediaStream對象.
getMediaStream().subscribe(new Consumer<MediaStream>() { @Override
public void accept(final MediaStream mediaStream) throws Exception { // 判斷當前的推送狀態.
MediaStream.PushingState state = mediaStream.getPushingState(); if (state != null && state.state > 0) { // 當前正在推送,那終止推送和預覽
mediaStream.stopStream();
mediaStream.closeCameraPreview();
}else{ // switch 0表示後置,1表示前置,2表示UVC攝像頭
// 非同步開啟UVC攝像頭
RxHelper.single(mediaStream.switchCamera(2), null).subscribe(new Consumer<Object>() { @Override
public void accept(Object o) throws Exception { // 開啟成功,進行推送.
// ...
mediaStream.startStream("cloud.easydarwin.org", "554", id);
}
}, new Consumer<Throwable>() { @Override
public void accept(final Throwable t) throws Exception { // ooop...開啟失敗,提示下...
t.printStackTrace();
runOnUiThread(new Runnable() { @Override
public void run() {
Toast.makeText(UVCActivity.this, "UVC攝像頭啟動失敗.." + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
});
}
這樣,整個推送就完成了.如果一切順利,應當能在VLC播放出來UVC攝像頭的視頻了~~
我們再看看如何錄像.也非常簡單…
public void onRecord(View view) { // 開始或結束錄像.
final TextView txt = (TextView) view;
getMediaStream().subscribe(new Consumer<MediaStream>() { @Override
public void accept(MediaStream mediaStream) throws Exception { if (mediaStream.isRecording()){ // 如果正在錄像,那停止.
mediaStream.stopRecord();
txt.setText("錄像");
}else { // 沒在錄像,開始錄像...
// 表示最大錄像時長為30秒,30秒後如果沒有停止,會生成一個新文件.依次類推...
// 文件格式為test_uvc_0.mp4,test_uvc_1.mp4,test_uvc_2.mp4,test_uvc_3.mp4
String path = getExternalFilesDir(Environment.DIRECTORY_MOVIES) + "/test_uvc.mp4";
mediaStream.startRecord(path, 30000); final TextView pushingStateText = findViewById(R.id.pushing_state);
pushingStateText.append("\n錄像地址:" + path);
txt.setText("停止");
}
}
});
}21
UVC攝像頭還支持後台推送,即不預覽的情況下進行推送,同時再切換到前台繼續預覽.只需要調用一個介面即可實現,如下:
@Overridepublic void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int i, int i1) {
ms.setSurfaceTexture(surfaceTexture); // 設置預覽的surfaceTexture}@Overridepublic boolean onSurfaceTextureDestroyed(SurfaceTexture surfaceTexture) {
ms.setSurfaceTexture(null); // 設置預覽窗口為null,表示關閉預覽功能
return true;
}123456789
如果要徹底退出uvc攝像頭的預覽\推送,那隻需要同時退出服務即可.
public void onQuit(View view) { // 退出
finish(); // 終止服務...
Intent intent = new Intent(this, MediaStream.class);
stopService(intent);
}1234567
## 獲取更多信息 ##