一个简单的 UVC 应用程序的示例代码
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <libuvc/libuvc.h>
void frame_callback(uvc_frame_t *frame, void *user_data) {
// 处理视频帧数据的回调函数
// 在这里可以对视频帧进行进一步处理或展示
// 这里只简单打印帧的大小和时间戳
printf("Frame Size: %u bytes\n", frame->data_bytes);
printf("Timestamp: %ld.%ld\n", frame->capture_time.tv_sec, frame->capture_time.tv_usec);
}
int main() {
uvc_context_t *ctx;
uvc_device_t *dev;
uvc_device_handle_t *devh;
uvc_stream_ctrl_t ctrl;
// 初始化 UVC 上下文
uvc_error_t res = uvc_init(&ctx, NULL);
if (res < 0) {
fprintf(stderr, "Failed to initialize UVC: %s\n", uvc_strerror(res));
return res;
}
// 查找并打开第一个 UVC 设备
res = uvc_find_device(ctx, &dev, 0, 0, NULL);
if (res < 0) {
fprintf(stderr, "Failed to find UVC device: %s\n", uvc_strerror(res));
uvc_exit(ctx);
return res;
}
// 打开设备
res = uvc_open(dev, &devh);
if (res < 0) {
fprintf(stderr, "Failed to open UVC device: %s\n", uvc_strerror(res));
uvc_unref_device(dev);
uvc_exit(ctx);
return res;
}
// 获取默认的视频流控制参数
res = uvc_get_stream_ctrl_format_size(devh, &ctrl, UVC_FRAME_FORMAT_YUYV, 640, 480, 30);
if (res < 0) {
fprintf(stderr, "Failed to get stream control: %s\n", uvc_strerror(res));
uvc_close(devh);
uvc_unref_device(dev);
uvc_exit(ctx);
return res;
}
// 启动视频流
res = uvc_start_streaming(devh, &ctrl, frame_callback, NULL, 0);
if (res < 0) {
fprintf(stderr, "Failed to start streaming: %s\n", uvc_strerror(res));
uvc_close(devh);
uvc_unref_device(dev);
uvc_exit(ctx);
return res;
}
// 等待一段时间,让应用程序继续运行
sleep(10);
// 停止视频流
uvc_stop_streaming(devh);
// 关闭设备和 UVC 上下文
uvc_close(devh);
uvc_unref_device(dev);
uvc_exit(ctx);
return 0;
}
以下是UVC示例代码的拓扑图:
+-----------------------+
| |
| 应用程序 |
| |
+-----------------------+
|
|(1)初始化UVC上下文
|
v
+-----------------------+
| |
| UVC上下文 |
| |
+-----------------------+
|
|(2)查找并打开UVC设备
|
v
+-----------------------+
| |
| UVC设备 |
| |
+-----------------------+
|
|(3)获取视频流控制参数
|
v
+-----------------------+
| |
| 视频流控制参数 |
| |
+-----------------------+
|
|(4)启动视频流
|
v
+-----------------------+
| |
| 视频流处理 |
| |
+-----------------------+
|
|(5)停止视频流
|
v
+-----------------------+
| |
| 关闭设备 |
| |
+-----------------------+
|
|(6)关闭UVC上下文
|
v
+-----------------------+
| |
| 结束程序 |
| |
+-----------------------+
这个拓扑图显示了UVC示例代码的整体结构。首先,应用程序初始化UVC上下文(1),然后通过UVC上下文查找并打开UVC设备(2)。接下来,应用程序获取视频流控制参数(3),然后启动视频流(4)进行视频流处理。在处理完视频流后,应用程序停止视频流(5),然后关闭设备(6)。最后,应用程序关闭UVC上下文,结束程序。