V4L2学习记录【转】

转自:http://blog.chinaunix.net/uid-30254565-id-5637600.html

  1. V4L2学习记录
  2.                                                                                                                                    这个还没有分析完,先在这放着,防止电脑坏掉丢了,以后再完善
  3. V4L2的全称是video for linux two。

  4. V4L2 驱动核心
  5. V4L2 驱动源码在 drivers/media/video目录下,主要核心代码有:
  6. v4l2-dev.c //linux版本2视频捕捉接口,主要结构体 video_device 的注册
  7. v4l2-common.c //在Linux操作系统体系采用低级别的操作一套设备structures/vectors的通用视频设备接口。
  8. v4l2-device.c //V4L2的设备支持。注册v4l2_device。
  9. v4l22-ioctl.c //处理V4L2的ioctl命令的一个通用的框架。
  10. v4l2-subdev.c //v4l2子设备
  11. v4l2-mem2mem.c //内存到内存为Linux和videobuf视频设备的框架。设备的辅助函数,使用其源和目的地videobuf缓冲区。

  12. 直接来看驱动源码的话,还是对驱动的框架没有一个感性的认识,尤其这个V4L2的框架非常复杂,我们先从内核源码中提供的虚拟视频驱动程序vivi.c来分析。内核版本3.4.2。

  13. 虚拟视频驱动程序vivi.c源码分析
  14. 16年1月18日09:35:42
  15. (1)分析一个程序从它的init入口函数开始分析:
  16. static int __init vivi_init(void)
  17. {
  18.     const struct font_desc *font = find_font("VGA8x16");
  19.     int ret = 0, i;

  20.     if (font == NULL) {
  21.         printk(KERN_ERR "vivi: could not find font ");
  22.         return -ENODEV;
  23.     }
  24.     font8x16 = font->data;

  25.     if (n_devs <= 0)
  26.         n_devs = 1;

  27.     for (i = 0; i < n_devs; i++) {
  28.         ret = vivi_create_instance(i);
  29.         if (ret) {
  30.             /* If some instantiations succeeded, keep driver */
  31.             if (i)
  32.                 ret = 0;
  33.             break;
  34.         }
  35.     }

  36.     if (ret < 0) {
  37.         printk(KERN_ERR "vivi: error %d while loading driver ", ret);
  38.         return ret;
  39.     }

  40.     printk(KERN_INFO "Video Technology Magazine Virtual Video "
  41.             "Capture Board ver %s successfully loaded. ",
  42.             VIVI_VERSION);
  43.  
  44.     /* n_devs will reflect the actual number of allocated devices */
  45.     n_devs = i;

  46.     return ret;
  47. }

  48. static void __exit vivi_exit(void)
  49. {
  50.     vivi_release();
  51. }

  52. module_init(vivi_init);
  53. module_exit(vivi_exit);

  54. 其中n_devs的定义在前面,如下所示:
  55. static unsigned n_devs = 1;
  56. module_param(n_devs, uint, 0644);
  57. MODULE_PARM_DESC(n_devs, "number of video devices to create");
  58. 写的很清楚了, n_devs表示想要创建的 video devices个数。
  59. 去掉其他的判断语句,发现重要的函数只有一个vivi_create_instance(i)函数,我们下面就来分析这个函数。
  60. (2)vivi_create_instance(i)函数:
  61. static int __init vivi_create_instance(int inst)
  62. {
  63.     struct vivi_dev *dev;
  64.     struct video_device *vfd;
  65.     struct v4l2_ctrl_handler *hdl;
  66.     struct vb2_queue *q;
  67.     int ret;

  68.     dev = kzalloc(sizeof(*dev), GFP_KERNEL);
  69.     if (!dev)
  70.         return -ENOMEM;

  71.     snprintf(dev->v4l2_dev.name, sizeof(dev->v4l2_dev.name),
  72.             "%s-%03d", VIVI_MODULE_NAME, inst);
  73.     ret = v4l2_device_register(NULL, &dev->v4l2_dev);
  74.     if (ret)
  75.         goto free_dev;

  76.     dev->fmt = &formats[0];
  77.     dev->width = 640;
  78.     dev->height = 480;
  79.     hdl = &dev->ctrl_handler;
  80.     v4l2_ctrl_handler_init(hdl, 11);
  81.     dev->volume = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
  82.             V4L2_CID_AUDIO_VOLUME, 0, 255, 1, 200);
  83.     dev->brightness = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
  84.             V4L2_CID_BRIGHTNESS, 0, 255, 1, 127);
  85.     dev->contrast = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
  86.             V4L2_CID_CONTRAST, 0, 255, 1, 16);
  87.     dev->saturation = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
  88.             V4L2_CID_SATURATION, 0, 255, 1, 127);
  89.     dev->hue = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
  90.             V4L2_CID_HUE, -128, 127, 1, 0);
  91.     dev->autogain = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
  92.             V4L2_CID_AUTOGAIN, 0, 1, 1, 1);
  93.     dev->gain = v4l2_ctrl_new_std(hdl, &vivi_ctrl_ops,
  94.             V4L2_CID_GAIN, 0, 255, 1, 100);
  95.     dev->button = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_button, NULL);
  96.     dev->int32 = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_int32, NULL);
  97.     dev->int64 = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_int64, NULL);
  98.     dev->boolean = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_boolean, NULL);
  99.     dev->menu = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_menu, NULL);
  100.     dev->string = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_string, NULL);
  101.     dev->bitmask = v4l2_ctrl_new_custom(hdl, &vivi_ctrl_bitmask, NULL);
  102.     if (hdl->error) {
  103.         ret = hdl->error;
  104.         goto unreg_dev;
  105.     }
  106.     v4l2_ctrl_auto_cluster(2, &dev->autogain, 0, true);
  107.     dev->v4l2_dev.ctrl_handler = hdl;

  108.     /* initialize locks */
  109.     spin_lock_init(&dev->slock);

  110.     /* initialize queue */
  111.     q = &dev->vb_vidq;
  112.     memset(q, 0, sizeof(dev->vb_vidq));
  113.     q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  114.     q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
  115.     q->drv_priv = dev;
  116.     q->buf_struct_size = sizeof(struct vivi_buffer);
  117.     q->ops = &vivi_video_qops;
  118.     q->mem_ops = &vb2_vmalloc_memops;

  119.     vb2_queue_init(q);

  120.     mutex_init(&dev->mutex);

  121.     /* init video dma queues */
  122.     INIT_LIST_HEAD(&dev->vidq.active);
  123.     init_waitqueue_head(&dev->vidq.wq);

  124.     ret = -ENOMEM;
  125.     vfd = video_device_alloc();
  126.     if (!vfd)
  127.         goto unreg_dev;

  128.     *vfd = vivi_template;
  129.     vfd->debug = debug;
  130.     vfd->v4l2_dev = &dev->v4l2_dev;
  131.     set_bit(V4L2_FL_USE_FH_PRIO, &vfd->flags);

  132.     /*
  133.      * Provide a mutex to v4l2 core. It will be used to protect
  134.      * all fops and v4l2 ioctls.
  135.      */
  136.     vfd->lock = &dev->mutex;

  137.     ret = video_register_device(vfd, VFL_TYPE_GRABBER, video_nr);
  138.     if (ret < 0)
  139.         goto rel_vdev;

  140.     video_set_drvdata(vfd, dev);

  141.     /* Now that everything is fine, let's add it to device list */
  142.     list_add_tail(&dev->vivi_devlist, &vivi_devlist);

  143.     if (video_nr != -1)
  144.         video_nr++;

  145.     dev->vfd = vfd;
  146.     v4l2_info(&dev->v4l2_dev, "V4L2 device registered as %s ",
  147.          video_device_node_name(vfd));
  148.     return 0;

  149. rel_vdev:
  150.     video_device_release(vfd);
  151. unreg_dev:
  152.     v4l2_ctrl_handler_free(hdl);
  153.     v4l2_device_unregister(&dev->v4l2_dev);
  154. free_dev:
  155.     kfree(dev);
  156.     return ret;
  157. }

  158. 1. 函数首先为struct vivi_dev *dev;分配内存,然后将dev->v4l2_dev.name的名字设置为“vivi-i”的形式,然后调用 v4l2_device_register这个函数来注册dev->v4l2_dev这个结构体,结构体v4l2_device如下所示,看它的名字就叫V4L2设备,它肯定就是V4L2设备的核心结构体:
  159. struct v4l2_device {
  160.     /* dev->driver_data points to this struct.
  161.      Note: dev might be NULL if there is no parent device
  162.      as is the case with e.g. ISA devices. */
  163.     struct device *dev;
  164. #if defined(CONFIG_MEDIA_CONTROLLER)
  165.     struct media_device *mdev;
  166. #endif
  167.     /* used to keep track of the registered subdevs */
  168.     struct list_head subdevs;
  169.     /* lock this struct; can be used by the driver as well if this
  170.      struct is embedded into a larger struct. */
  171.     spinlock_t lock;
  172.     /* unique device name, by default the driver name + bus ID */
  173.     char name[V4L2_DEVICE_NAME_SIZE];
  174.     /* notify callback called by some sub-devices. */
  175.     void (*notify)(struct v4l2_subdev *sd,
  176.             unsigned int notification, void *arg);
  177.     /* The control handler. May be NULL. */
  178.     struct v4l2_ctrl_handler *ctrl_handler;
  179.     /* Device's priority state */
  180.     struct v4l2_prio_state prio;
  181.     /* BKL replacement mutex. Temporary solution only. */
  182.     struct mutex ioctl_lock;
  183.     /* Keep track of the references to this struct. */
  184.     struct kref ref;
  185.     /* Release function that is called when the ref count goes to 0. */
  186.     void (*release)(struct v4l2_device *v4l2_dev);
  187. };

  188. 可以看到这个结构体里面包含一个device父设备成员,一个subdevs子设备链表头,一个自旋锁,一个notify函数指针,v4l2_ctrl_handler控制句柄,prio优先级,ref引用计数,还有一个release函数指针。暂时先不对这个结构体进行具体的分析,在以后分析V4L2框架的时候再分析。
  189. 2. 它通过v4l2_device_register(NULL, &dev->v4l2_dev);函数来完成对结构体的注册,可以看出在”vivi.c”中,它的父设备为NULL, v4l2_device_register这个函数在v4l2-device.c中:
  190. int v4l2_device_register(struct device *dev, struct v4l2_device *v4l2_dev)
  191. {
  192.     if (v4l2_dev == NULL)
  193.         return -EINVAL;

  194.     INIT_LIST_HEAD(&v4l2_dev->subdevs);
  195.     spin_lock_init(&v4l2_dev->lock);
  196.     mutex_init(&v4l2_dev->ioctl_lock);
  197.     v4l2_prio_init(&v4l2_dev->prio);
  198.     kref_init(&v4l2_dev->ref);
  199.     get_device(dev);
  200.     v4l2_dev->dev = dev;
  201.     if (dev == NULL) {
  202.         /* If dev == NULL, then name must be filled in by the caller */
  203.         WARN_ON(!v4l2_dev->name[0]);
  204.         return 0;
  205.     }

  206.     /* Set name to driver name + device name if it is empty. */
  207.     if (!v4l2_dev->name[0])
  208.         snprintf(v4l2_dev->name, sizeof(v4l2_dev->name), "%s %s",
  209.             dev->driver->name, dev_name(dev));
  210.     if (!dev_get_drvdata(dev))
  211.         dev_set_drvdata(dev, v4l2_dev);
  212.     return 0;
  213. }
  214. EXPORT_SYMBOL_GPL(v4l2_device_register);

  215. 这个函数完成了子设备链表的初始化,自旋锁,互斥量,优先级,引用计数的初始化,其他并没有做太多工作。

  216. 3. 继续回到vivi_create_instance(i)函数中进行分析,下一句话:dev->fmt = &formats[0]
  217. 通过向前搜索发现,vivi.c维持着一个 formats数组,它表示vivi.c支持的数据格式。关于视频的格式我们在V4L2框架中介绍,通过这行代码,我们知道了vivi.c所支持的格式为 V4L2_PIX_FMT_YUYV。
  218. struct vivi_fmt {
  219.     char *name;
  220.     u32 fourcc; /* v4l2 format id */
  221.     int depth;
  222. };

  223. static struct vivi_fmt formats[] = {
  224.     {
  225.         .name = "4:2:2, packed, YUYV",
  226.         .fourcc = V4L2_PIX_FMT_YUYV,
  227.         .depth = 16,
  228.     },
  229.     {
  230.         .name = "4:2:2, packed, UYVY",
  231.         .fourcc = V4L2_PIX_FMT_UYVY,
  232.         .depth = 16,
  233.     },
  234.     {
  235.         .name = "RGB565 (LE)",
  236.         .fourcc = V4L2_PIX_FMT_RGB565, /* gggbbbbb rrrrrggg */
  237.         .depth = 16,
  238.     },
  239.     {
  240.         .name = "RGB565 (BE)",
  241.         .fourcc = V4L2_PIX_FMT_RGB565X, /* rrrrrggg gggbbbbb */
  242.         .depth = 16,
  243.     },
  244.     {
  245.         .name = "RGB555 (LE)",
  246.         .fourcc = V4L2_PIX_FMT_RGB555, /* gggbbbbb arrrrrgg */
  247.         .depth = 16,
  248.     },
  249.     {
  250.         .name = "RGB555 (BE)",
  251.         .fourcc = V4L2_PIX_FMT_RGB555X, /* arrrrrgg gggbbbbb */
  252.         .depth = 16,
  253.     },
  254. };

  255. 4.继续在vivi_create_instance(i)函数中分析 :
  256.     hdl = &dev->ctrl_handler;
  257.     v4l2_ctrl_handler_init(hdl, 11);
  258. v4l2_ctrl_handler结构体在v4l2-ctrls.h中定义,如下所示:
  259. struct v4l2_ctrl_handler {
  260.     struct mutex lock;
  261.     struct list_head ctrls;
  262.     struct list_head ctrl_refs;
  263.     struct v4l2_ctrl_ref *cached;
  264.     struct v4l2_ctrl_ref **buckets;
  265.     u16 nr_of_buckets;
  266.     int error;
  267. };
  268. v4l2_ctrl_handler是用于保存子设备控制方法集的结构体,对于视频设备这些ctrls包括设置亮度、饱和度、对比度和 清晰度等,用链表的方式来保存ctrls,可以通过v4l2_ctrl_new_std函数向链表添加ctrls。在下面的代码中用到了这个函数。
  269. /* Initialize the handler */
  270. int v4l2_ctrl_handler_init(struct v4l2_ctrl_handler *hdl,
  271.              unsigned nr_of_controls_hint)
  272. {
  273.     mutex_init(&hdl->lock);
  274.     INIT_LIST_HEAD(&hdl->ctrls);
  275.     INIT_LIST_HEAD(&hdl->ctrl_refs);
  276.     hdl->nr_of_buckets = 1 + nr_of_controls_hint / 8;
  277.     hdl->buckets = kcalloc(hdl->nr_of_buckets, sizeof(hdl->buckets[0]),
  278.              GFP_KERNEL);
  279.     hdl->error = hdl->buckets ? 0 : -ENOMEM;
  280.     return hdl->error;
  281. }
  282. EXPORT_SYMBOL(v4l2_ctrl_handler_init);

  283. 通过nr_of_controls_hint变量的大小,计算出nr_of_buckets,并为 buckets申请空间,并将申请结果保存在error变量中。

  284. 5. 继续在vivi_create_instance(i)函数中分析,继续设置dev结构体中的其他一些参数,对volume,brightness,contrast, saturation等参数设置的时候,调用了 v4l2_ctrl_new_std这个函数,以及对button, int32, menu,bitmask等参数的设置,调用了v4l2_ctrl_new_custom这个函数,一看就知道这两个函数是V4L2框架所提供的接口函数。
  285. struct v4l2_ctrl *v4l2_ctrl_new_std(structv4l2_ctrl_handler *hdl, conststruct v4l2_ctrl_ops *ops, u32id, s32 min, s32 max, u32 step, s32 def)
  286. hdl是初始化好的v4l2_ctrl_handler结构体;
  287. ops是v4l2_ctrl_ops结构体,包含ctrls的具体实现;
  288. id是通过IOCTL的arg参数传过来的指令,定义在v4l2-controls.h文件;
  289. min、max用来定义某操作对象的范围。如:
  290. v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BRIGHTNESS,-208, 127, 1, 0);
  291. 用户空间可以通过ioctl的VIDIOC_S_CTRL指令调用到v4l2_ctrl_handler,id透过arg参数传递。
  292. 通过几个函数来完成对视频中亮度,饱和度等的设置。

  293. 6. 然后是缓冲区队列的操作,设置vb2_queue队列q的一些参数,最主要的是下面两个参数:
  294.     q->ops = &vivi_video_qops;
  295.     q->mem_ops = &vb2_vmalloc_memops;
  296. 可以看到:q->ops = &vivi_video_qops;中vivi_video_qops是需要vivi.c实现的一个操作函数集,它在vivi.c中定义如下:
  297. static struct vb2_ops vivi_video_qops = {
  298.     .queue_setup        = queue_setup,
  299.     .buf_init        = buffer_init,
  300.     .buf_prepare        = buffer_prepare,
  301.     .buf_finish        = buffer_finish,
  302.     .buf_cleanup        = buffer_cleanup,
  303.     .buf_queue        = buffer_queue,
  304.     .start_streaming    = start_streaming,
  305.     .stop_streaming        = stop_streaming,
  306.     .wait_prepare        = vivi_unlock,
  307.     .wait_finish        = vivi_lock,
  308. };

  309. 这几个函数是需要我们写驱动程序的时候自己实现的函数。
  310. 其中 vb2_ops结构体在videobuf2-core.h中定义,如下所示:
  311. struct vb2_ops {
  312.     int (*queue_setup)(struct vb2_queue *q, const struct v4l2_format *fmt,
  313.              unsigned int *num_buffers, unsigned int *num_planes,
  314.              unsigned int sizes[], void *alloc_ctxs[]);

  315.     void (*wait_prepare)(struct vb2_queue *q);
  316.     void (*wait_finish)(struct vb2_queue *q);

  317.     int (*buf_init)(struct vb2_buffer *vb);
  318.     int (*buf_prepare)(struct vb2_buffer *vb);
  319.     int (*buf_finish)(struct vb2_buffer *vb);
  320.     void (*buf_cleanup)(struct vb2_buffer *vb);

  321.     int (*start_streaming)(struct vb2_queue *q, unsigned int count);
  322.     int (*stop_streaming)(struct vb2_queue *q);

  323.     void (*buf_queue)(struct vb2_buffer *vb);
  324. };

  325. 对于 vb2_vmalloc_memops结构体,它在videobuf2-vmalloc.c中定义,如下所示:
  326. const struct vb2_mem_ops vb2_vmalloc_memops = {
  327.     .alloc        = vb2_vmalloc_alloc,
  328.     .put        = vb2_vmalloc_put,
  329.     .get_userptr    = vb2_vmalloc_get_userptr,
  330.     .put_userptr    = vb2_vmalloc_put_userptr,
  331.     .vaddr        = vb2_vmalloc_vaddr,
  332.     .mmap        = vb2_vmalloc_mmap,
  333.     .num_users    = vb2_vmalloc_num_users,
  334. };
  335. EXPORT_SYMBOL_GPL(vb2_vmalloc_memops);

  336. 看它的名字是vb2开头的,这几个函数应该都是系统为我们提供好的函数,通过查看源码发现,它确实存在于videobuf2-vmalloc.c中。
  337. 然后调用vb2_queue_init(q);函数来初始化它,vb2_queue_init(q)函数如下所示:
  338. /**
  339.  * vb2_queue_init() - initialize a videobuf2 queue
  340.  * @q:        videobuf2 queue; this structure should be allocated in driver
  341.  *
  342.  * The vb2_queue structure should be allocated by the driver. The driver is
  343.  * responsible of clearing it's content and setting initial values for some
  344.  * required entries before calling this function.
  345.  * q->ops, q->mem_ops, q->type and q->io_modes are mandatory. Please refer
  346.  * to the struct vb2_queue description in include/media/videobuf2-core.h
  347.  * for more information.
  348.  */
  349. int vb2_queue_init(struct vb2_queue *q)
  350. {
  351.     BUG_ON(!q);
  352.     BUG_ON(!q->ops);
  353.     BUG_ON(!q->mem_ops);
  354.     BUG_ON(!q->type);
  355.     BUG_ON(!q->io_modes);

  356.     BUG_ON(!q->ops->queue_setup);
  357.     BUG_ON(!q->ops->buf_queue);

  358.     INIT_LIST_HEAD(&q->queued_list);
  359.     INIT_LIST_HEAD(&q->done_list);
  360.     spin_lock_init(&q->done_lock);
  361.     init_waitqueue_head(&q->done_wq);

  362.     if (q->buf_struct_size == 0)
  363.         q->buf_struct_size = sizeof(struct vb2_buffer);

  364.     return 0;
  365. }
  366. EXPORT_SYMBOL_GPL(vb2_queue_init);

  367. 它只是完成了一些检查判断的语句,进行了一些链表,自旋锁等的初始化。

  368. 7. /* init video dma queues */
  369.     INIT_LIST_HEAD(&dev->vidq.active);
  370.     init_waitqueue_head(&dev->vidq.wq);

  371. 8.下面是对video_device的操作,它算是这个函数中核心的操作:
  372. struct video_device *vfd;
  373. vfd = video_device_alloc();
  374. *vfd = vivi_template;
  375. ret = video_register_device(vfd, VFL_TYPE_GRABBER, video_nr);
  376. video_set_drvdata(vfd, dev);

  377. 8.1先来看这个video_device结构体,它在v4l2-dev.h中定义,显示如下:
  378. struct video_device
  379. {
  380.     /* device ops */
  381.     const struct v4l2_file_operations *fops;
  382.     /* sysfs */
  383.     struct device dev;        /* v4l device */
  384.     struct cdev *cdev;        /* character device */
  385.     /* Set either parent or v4l2_dev if your driver uses v4l2_device */
  386.     struct device *parent;        /* device parent */
  387.     struct v4l2_device *v4l2_dev;    /* v4l2_device parent */
  388.     /* Control handler associated with this device node. May be NULL. */
  389.     struct v4l2_ctrl_handler *ctrl_handler;
  390.     /* Priority state. If NULL, then v4l2_dev->prio will be used. */
  391.     struct v4l2_prio_state *prio;
  392.     /* device info */
  393.     char name[32];
  394.     int vfl_type;
  395.     /* 'minor' is set to -1 if the registration failed */
  396.     int minor;
  397.     u16 num;
  398.     /* use bitops to set/clear/test flags */
  399.     unsigned long flags;
  400.     /* attribute to differentiate multiple indices on one physical device */
  401.     int index;
  402.     /* V4L2 file handles */
  403.     spinlock_t        fh_lock; /* Lock for all v4l2_fhs */
  404.     struct list_head    fh_list; /* List of struct v4l2_fh */
  405.     int debug;            /* Activates debug level*/
  406.     /* Video standard vars */
  407.     v4l2_std_id tvnorms;        /* Supported tv norms */
  408.     v4l2_std_id current_norm;    /* Current tvnorm */
  409.     /* callbacks */
  410.     void (*release)(struct video_device *vdev);
  411.     /* ioctl callbacks */
  412.     const struct v4l2_ioctl_ops *ioctl_ops;
  413.     /* serialization lock */
  414.     struct mutex *lock;
  415. };

  416. 根据注释应该能大致了解各个成员的意义。后面有这个函数的一些初始化和注册函数,里面肯定有对这个结构体成员的设置初始化等,所以我们在后面再具体分析这些成员。

  417. 8.2 下面来看video_device_alloc函数。它在v4l2-dev.c中定义:
  418. struct video_device *video_device_alloc(void)
  419. {
  420.     return kzalloc(sizeof(struct video_device), GFP_KERNEL);
  421. }
  422. EXPORT_SYMBOL(video_device_alloc);

  423. 只是分配了一段内存,然后将它置为0,并没有对video_device结构体里面的成员进行设置。

  424. 8.3 然后vivi.c中下一句是*vfd = vivi_template;在vivi.c中搜索发现,它在前面定义:
  425. static struct video_device vivi_template = {
  426.     .name        = "vivi",
  427.     .fops = &vivi_fops,
  428.     .ioctl_ops     = &vivi_ioctl_ops,
  429.     .release    = video_device_release,

  430.     .tvnorms = V4L2_STD_525_60,
  431.     .current_norm = V4L2_STD_NTSC_M,
  432. };

  433. 对比video_device结构体中的成员,可以确定就是在这进行赋值的。它只是对其中某些成员进行了赋。

  434. 8.3.1 video_device结构体中首先是.fops = &vivi_fops,在vivi.c中搜索如下所示:
  435. static const struct v4l2_file_operations vivi_fops = {
  436.     .owner        = THIS_MODULE,
  437.     .open = v4l2_fh_open,
  438.     .release = vivi_close,
  439.     .read = vivi_read,
  440.     .poll        = vivi_poll,
  441.     .unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
  442.     .mmap = vivi_mmap,
  443. };

  444. 先来看这几个函数的名字,其中open函数和unlocked_ioctl函数的名字与其他的不同,直觉告诉我,他俩是系统提供的,其他的函数名字都是vivi开头的,应该是这个文件里面实现的函数,我们在vivi.c中搜索就可以找到,但是我们暂时先不具体分析这几个函数。

  445. 8.3.2 video_device结构体中第二个是.ioctl_ops = &vivi_ioctl_ops,看名字也是在vivi.c中定义的:
  446. static const struct v4l2_ioctl_ops vivi_ioctl_ops = {
  447.     .vidioc_querycap = vidioc_querycap,
  448.     .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
  449.     .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
  450.     .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
  451.     .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
  452.     .vidioc_reqbufs = vidioc_reqbufs,
  453.     .vidioc_querybuf = vidioc_querybuf,
  454.     .vidioc_qbuf = vidioc_qbuf,
  455.     .vidioc_dqbuf = vidioc_dqbuf,
  456.     .vidioc_s_std = vidioc_s_std,
  457.     .vidioc_enum_input = vidioc_enum_input,
  458.     .vidioc_g_input = vidioc_g_input,
  459.     .vidioc_s_input = vidioc_s_input,
  460.     .vidioc_streamon = vidioc_streamon,
  461.     .vidioc_streamoff = vidioc_streamoff,
  462.     .vidioc_log_status = v4l2_ctrl_log_status,
  463.     .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
  464.     .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
  465. };

  466. 可以看到,这是一大堆的ioctl调用,大致可分为以下几类:
  467. 查询性能query capability的:vidioc_querycap;
  468. 对format的一些操作: vidioc_enum_fmt_vid_cap, vidioc_g_fmt_vid_cap, vidioc_try_fmt_vid_cap, vidioc_s_fmt_vid_cap;
  469. 对缓冲区的一些操作: vidioc_reqbufs, vidioc_querybuf, vidioc_qbuf, vidioc_dqbuf;
  470. 对标准standard的操作: vidioc_s_std;
  471. 对输入input的操作: vidioc_enum_input, vidioc_g_input, vidioc_s_input;
  472. 对流stream的操作: vidioc_streamon, vidioc_streamoff;
  473. 以上几个ioctl调用都是需要我们自己实现的,后面3个ioctl的名字是v4l2开头的,应该是系统里面实现好的函数,搜索可以发现在v4l2-ctrls.c和v4l2-event.c中定义。

  474. 8.3.3 video_device结构体中第三个是.release = video_device_release,它在v4l2-dev.c中定义,如下所示:
  475. void video_device_release(struct video_device *vdev)
  476. {
  477.     kfree(vdev);
  478. }
  479. EXPORT_SYMBOL(video_device_release);

  480. 8.3.4 video_device结构体中第四,五个是:
  481.     .tvnorms = V4L2_STD_525_60,
  482.     .current_norm = V4L2_STD_NTSC_M,
  483. 通过看video_device结构体中的注释,
  484.     /* Video standard vars */
  485.     v4l2_std_id tvnorms;        /* Supported tv norms */
  486.     v4l2_std_id current_norm;    /* Current tvnorm */
  487. 是指支持的tv制式以及当前的tv制式。

  488. 8.3.5 分析完了vivi_template中的成员,也即video_device结构体中的成员,还是有点迷惑的,在
  489. video_device结构体中,有一个struct v4l2_file_operations成员,这个成员又包含一个unlocked_ioctl,同时video_device结构体中还有一个struct v4l2_ioctl_ops成员,怎么有两个ioctl成员函数啊?先大致分析一些,struct v4l2_file_operations vivi_fops中.unlocked_ioctl = video_ioctl2,这个video_ioctl2在v4l2-ioctl.c中:
  490. long video_ioctl2(struct file *file,
  491.      unsigned int cmd, unsigned long arg)
  492. {
  493.     return video_usercopy(file, cmd, arg, __video_do_ioctl);
  494. }
  495. EXPORT_SYMBOL(video_ioctl2);
  496. 它又调用了__video_do_ioctl函数,也在v4l2-ioctl.c中,这个__video_do_ioctl函数是一个大的switch,case语句,根据不同的case,调用不同的函数,以 VIDIOC_QUERYCAP为例:
  497. struct video_device *vfd = video_devdata(file);
  498. const struct v4l2_ioctl_ops *ops = vfd->ioctl_ops;
  499. case VIDIOC_QUERYCAP:
  500. ret = ops->vidioc_querycap(file, fh, cap);
  501. 用在vivi.c这个例子中就是: vfd这个结构体就是vivi_template, ops就是vivi_template中的ioctl_ops成员,也就是vivi_ioctl_ops,对于 VIDIOC_QUERYCAP宏,真正调用的是vivi_ioctl_ops中的.vidioc_querycap成员,也即我们在vivi.c中自己实现的
  502. static int vidioc_querycap(struct file *file, void *priv, struct v4l2_capability *cap)函数。有点绕,我已晕@_@!~~
  503. 咱们在后面再具体分析。

  504. 8.4 继续在vivi_create_instance中分析:
  505.     vfd->debug = debug;
  506.     vfd->v4l2_dev = &dev->v4l2_dev;
  507. 注意这个语句,从这里可以看出在注册video_device之前必须先注册了v4l2_device。
  508.     set_bit(V4L2_FL_USE_FH_PRIO, &vfd->flags);
  509.     vfd->lock = &dev->mutex;
  510. 进行了一些设置,然后就是大boss了:
  511. ret = video_register_device(vfd, VFL_TYPE_GRABBER, video_nr);
  512. 它在v4l2-dev.h中定义,如下所示:
  513. static inline int __must_check video_register_device_no_warn(
  514.         struct video_device *vdev, int type, int nr)
  515. {
  516.     return __video_register_device(vdev, type, nr, 0, vdev->fops->owner);
  517. }
  518. __video_register_device在v4l2-dev.c中定义:(就直接在代码中注释了)
  519. /**
  520.  *    __video_register_device - register video4linux devices
  521.  *    @vdev: video device structure we want to register
  522.  *    @type: type of device to register
  523.  *    @nr: which device node number (0 == /dev/video0, 1 == /dev/video1, ...
  524.  * -1 == first free)
  525.  *    @warn_if_nr_in_use: warn if the desired device node number
  526.  *     was already in use and another number was chosen instead.
  527.  *    @owner: module that owns the video device node
  528.  *
  529.  *    The registration code assigns minor numbers and device node numbers
  530.  *    based on the requested type and registers the new device node with
  531.  *    the kernel.
  532.  *
  533.  *    This function assumes that struct video_device was zeroed when it
  534.  *    was allocated and does not contain any stale date.
  535.  *
  536.  *    An error is returned if no free minor or device node number could be
  537.  *    found, or if the registration of the device node failed.
  538.  *
  539.  *    Zero is returned on success.
  540.  *
  541.  *    Valid types are
  542.  *
  543.  *    %VFL_TYPE_GRABBER - A frame grabber
  544.  *
  545.  *    %VFL_TYPE_VBI - Vertical blank data (undecoded)
  546.  *
  547.  *    %VFL_TYPE_RADIO - A radio card
  548.  *
  549.  *    %VFL_TYPE_SUBDEV - A subdevice
  550.  */
  551. int __video_register_device(struct video_device *vdev, int type, int nr,
  552.         int warn_if_nr_in_use, struct module *owner)
  553. {
  554.     int i = 0;
  555.     int ret;
  556.     int minor_offset = 0;
  557.     int minor_cnt = VIDEO_NUM_DEVICES;
  558.     const char *name_base;

  559.     /* A minor value of -1 marks this video device as never
  560.      having been registered */
  561.     vdev->minor = -1;

  562.     /* the release callback MUST be present */
  563.     if (WARN_ON(!vdev->release))
  564.         return -EINVAL;
  565. /* 如果没有提供这个release函数的话,就直接返回错误,它就在vivi_template中提供了。 */
  566.     /* v4l2_fh support */
  567.     spin_lock_init(&vdev->fh_lock);
  568.     INIT_LIST_HEAD(&vdev->fh_list);

  569.     /* Part 1: check device type */
  570.     switch (type) {
  571.     case VFL_TYPE_GRABBER:
  572.         name_base = "video";
  573.         break;
  574.     case VFL_TYPE_VBI:
  575.         name_base = "vbi";
  576.         break;
  577.     case VFL_TYPE_RADIO:
  578.         name_base = "radio";
  579.         break;
  580.     case VFL_TYPE_SUBDEV:
  581.         name_base = "v4l-subdev";
  582.         break;
  583.     default:
  584.         printk(KERN_ERR "%s called with unknown type: %d ",
  585.          __func__, type);
  586.         return -EINVAL;
  587.     }
  588. /* 根据传进来的type参数,确定设备在/dev目录下看到的名字 */
  589.     vdev->vfl_type = type;
  590.     vdev->cdev = NULL;
  591.     if (vdev->v4l2_dev) {
  592.         if (vdev->v4l2_dev->dev)
  593.             vdev->parent = vdev->v4l2_dev->dev;
  594.         if (vdev->ctrl_handler == NULL)
  595.             vdev->ctrl_handler = vdev->v4l2_dev->ctrl_handler;
  596.         /* If the prio state pointer is NULL, then use the v4l2_device
  597.          prio state. */
  598.         if (vdev->prio == NULL)
  599.             vdev->prio = &vdev->v4l2_dev->prio;
  600.     }
  601. /* 进行vdev中父设备和ctrl处理函数的初始化。*/
  602.     /* Part 2: find a free minor, device node number and device index. */
  603. #ifdef CONFIG_VIDEO_FIXED_MINOR_RANGES
  604.     /* Keep the ranges for the first four types for historical
  605.      * reasons.
  606.      * Newer devices (not yet in place) should use the range
  607.      * of 128-191 and just pick the first free minor there
  608.      * (new style). */
  609.     switch (type) {
  610.     case VFL_TYPE_GRABBER:
  611.         minor_offset = 0;
  612.         minor_cnt = 64;
  613.         break;
  614.     case VFL_TYPE_RADIO:
  615.         minor_offset = 64;
  616.         minor_cnt = 64;
  617.         break;
  618.     case VFL_TYPE_VBI:
  619.         minor_offset = 224;
  620.         minor_cnt = 32;
  621.         break;
  622.     default:
  623.         minor_offset = 128;
  624.         minor_cnt = 64;
  625.         break;
  626.     }
  627. #endif

  628.     /* Pick a device node number */
  629.     mutex_lock(&videodev_lock);
  630.     nr = devnode_find(vdev, nr == -1 ? 0 : nr, minor_cnt);
  631.     if (nr == minor_cnt)
  632.         nr = devnode_find(vdev, 0, minor_cnt);
  633.     if (nr == minor_cnt) {
  634.         printk(KERN_ERR "could not get a free device node number ");
  635.         mutex_unlock(&videodev_lock);
  636.         return -ENFILE;
  637.     }
  638. #ifdef CONFIG_VIDEO_FIXED_MINOR_RANGES
  639.     /* 1-on-1 mapping of device node number to minor number */
  640.     i = nr;
  641. #else
  642.     /* The device node number and minor numbers are independent, so
  643.      we just find the first free minor number. */
  644.     for (i = 0; i < VIDEO_NUM_DEVICES; i++)
  645.         if (video_device[i] == NULL)
  646.             break;
  647.     if (i == VIDEO_NUM_DEVICES) {
  648.         mutex_unlock(&videodev_lock);
  649.         printk(KERN_ERR "could not get a free minor ");
  650.         return -ENFILE;
  651.     }
  652. #endif
  653.     vdev->minor = i + minor_offset;
  654.     vdev->num = nr;
  655.     devnode_set(vdev);

  656.     /* Should not happen since we thought this minor was free */
  657.     WARN_ON(video_device[vdev->minor] != NULL);
  658.     vdev->index = get_index(vdev);
  659.     mutex_unlock(&videodev_lock);
  660. /* 上面的part2就是确定设备的次设备号 */
  661.     /* Part 3: Initialize the character device */
  662.     vdev->cdev = cdev_alloc();
  663.     if (vdev->cdev == NULL) {
  664.         ret = -ENOMEM;
  665.         goto cleanup;
  666.     }
  667. /* 在这进行设备的注册,用cdev_alloc函数,从这我们就可以看出来,它是一个普通的字符设备驱动,然后设置它的一些参数。怎么就是字符设备驱动了???这个在后面的v4l2框架中再说。 */
  668.     vdev->cdev->ops = &v4l2_fops;
  669. /* cdev结构体里面的ops指向了v4l2_fops这个结构体,这个v4l2_fops结构体也是在v4l2-dev.c这个文件中。又一个file_operations操作函数集,在vivi.c中有一个v4l2_file_operations vivi_fops,他俩又是什么关系呢? */
  670.     vdev->cdev->owner = owner;
  671.     ret = cdev_add(vdev->cdev, MKDEV(VIDEO_MAJOR, vdev->minor), 1);
  672.     if (ret < 0) {
  673.         printk(KERN_ERR "%s: cdev_add failed ", __func__);
  674.         kfree(vdev->cdev);
  675.         vdev->cdev = NULL;
  676.         goto cleanup;
  677.     }


  678.     /* Part 4: register the device with sysfs */
  679.     vdev->dev.class = &video_class;
  680.     vdev->dev.devt = MKDEV(VIDEO_MAJOR, vdev->minor);
  681.     if (vdev->parent)
  682.         vdev->dev.parent = vdev->parent;
  683.     dev_set_name(&vdev->dev, "%s%d", name_base, vdev->num);
  684.     ret = device_register(&vdev->dev);
  685.     if (ret < 0) {
  686.         printk(KERN_ERR "%s: device_register failed ", __func__);
  687.         goto cleanup;
  688.     }
  689.     /* Register the release callback that will be called when the last
  690.      reference to the device goes away. */
  691.     vdev->dev.release = v4l2_device_release;

  692.     if (nr != -1 && nr != vdev->num && warn_if_nr_in_use)
  693.         printk(KERN_WARNING "%s: requested %s%d, got %s ", __func__,
  694.             name_base, nr, video_device_node_name(vdev));

  695.     /* Increase v4l2_device refcount */
  696.     if (vdev->v4l2_dev)
  697.         v4l2_device_get(vdev->v4l2_dev);
  698. /* 在sysfs中创建类,在类下创建设备结点 */

  699. #if defined(CONFIG_MEDIA_CONTROLLER)
  700.     /* Part 5: Register the entity. */
  701.     if (vdev->v4l2_dev && vdev->v4l2_dev->mdev &&
  702.      vdev->vfl_type != VFL_TYPE_SUBDEV) {
  703.         vdev->entity.type = MEDIA_ENT_T_DEVNODE_V4L;
  704.         vdev->entity.name = vdev->name;
  705.         vdev->entity.info.v4l.major = VIDEO_MAJOR;
  706.         vdev->entity.info.v4l.minor = vdev->minor;
  707.         ret = media_device_register_entity(vdev->v4l2_dev->mdev,
  708.             &vdev->entity);
  709.         if (ret < 0)
  710.             printk(KERN_WARNING
  711.              "%s: media_device_register_entity failed ",
  712.              __func__);
  713.     }
  714. #endif
  715. /* 创建实体entity,这一步并不是必须的,需要配置了CONFIG_MEDIA_CONTROLLER选项后才会执行这一步,在这一步里面有一个media_entity实体结构体,在后面再分析它。 */
  716.     /* Part 6: Activate this minor. The char device can now be used. */
  717.     set_bit(V4L2_FL_REGISTERED, &vdev->flags);
  718. /* 设置标志位 */
  719.     mutex_lock(&videodev_lock);
  720.     video_device[vdev->minor] = vdev;
  721. /* 将设置好的video_device结构体vdev按照次设备号保存到video_device数组中。这个数组是在前面static struct video_device *video_device[VIDEO_NUM_DEVICES];定义的。 */
  722.     mutex_unlock(&videodev_lock);

  723.     return 0;

  724. cleanup:
  725.     mutex_lock(&videodev_lock);
  726.     if (vdev->cdev)
  727.         cdev_del(vdev->cdev);
  728.     devnode_clear(vdev);
  729.     mutex_unlock(&videodev_lock);
  730.     /* Mark this video device as never having been registered. */
  731.     vdev->minor = -1;
  732.     return ret;
  733. }
  734. EXPORT_SYMBOL(__video_register_device);

  735. 8.5 注册完video_device结构体后继续在vivi_create_instance中执行:
  736. video_set_drvdata(vfd, dev);
  737. /* 将vivi_dev dev添加到video_device vfd中,为什么要这样做呢?是为了以后字符设备驱动接口的使用。*/
  738. list_add_tail(&dev->vivi_devlist, &vivi_devlist);
  739. /* 添加到device list链表中 */
  740. if (video_nr != -1)
  741.     video_nr++;
  742. /* 用于计数 */
  743. dev->vfd = vfd;
  744. /* 关联video_device 和vivi_dev。 */

  745. (三)到这里我们就分析完了vivi_init和vivi_create_instance函数,vivi.c中剩下的代码,基本就是以下3个结构体的具体实现代码我们暂时先不分析。
  746. static struct video_device vivi_template = {
  747.     .name        = "vivi",
  748.     .fops = &vivi_fops,
  749.     .ioctl_ops     = &vivi_ioctl_ops,
  750.     .release    = video_device_release,
  751.     .tvnorms = V4L2_STD_525_60,
  752.     .current_norm = V4L2_STD_NTSC_M,
  753. };

  754. static const struct v4l2_ioctl_ops vivi_ioctl_ops = {
  755.     .vidioc_querycap = vidioc_querycap,
  756.     .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
  757.     .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
  758.     .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
  759.     .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
  760.     .vidioc_reqbufs = vidioc_reqbufs,
  761.     .vidioc_querybuf = vidioc_querybuf,
  762.     .vidioc_qbuf = vidioc_qbuf,
  763.     .vidioc_dqbuf = vidioc_dqbuf,
  764.     .vidioc_s_std = vidioc_s_std,
  765.     .vidioc_enum_input = vidioc_enum_input,
  766.     .vidioc_g_input = vidioc_g_input,
  767.     .vidioc_s_input = vidioc_s_input,
  768.     .vidioc_streamon = vidioc_streamon,
  769.     .vidioc_streamoff = vidioc_streamoff,
  770.     .vidioc_log_status = v4l2_ctrl_log_status,
  771.     .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
  772.     .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
  773. };

  774. static const struct v4l2_file_operations vivi_fops = {
  775.     .owner        = THIS_MODULE,
  776.     .open = v4l2_fh_open,
  777.     .release = vivi_close,
  778.     .read = vivi_read,
  779.     .poll        = vivi_poll,
  780.     .unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
  781.     .mmap = vivi_mmap,
  782. };
  783. 我们首先分析这个vivi.c的目的是为了先大致看一些v4l2驱动的代码,留一些疑问,以后分析v4l2的代码框架及一些概念的时候,还会以这个vivi.c为例子来说明。等到分析完大致的框架以后,我们再来继续仔细分析vivi.c中那些具体代码的实现。

  784. V4L2框架分析
  785. 16年1月18日19:12:43
  786. (一)概述
  787. Video4Linux2是Linux内核中关于视频设备的内核驱动框架,为上层的访问底层的视频设备提供了统一的接口。凡是内核中的子系统都有抽象底层硬件的差异,为上层提供统一的接口和提取出公共代码避免代码冗余等好处。
  788. V4L2支持三类设备:GRABBER视频输入输出设备、VBI设备和RADIO设备(其实还支持更多类型的设备,暂不讨论),分别会在/dev目录下产生videoX、radioX和vbiX设备节点。我们常见的视频输入设备主要是摄像头,也是本文主要分析对象。下图V4L2在Linux系统中的结构图:
  789.  
  790. Linux系统中视频输入设备主要包括以下四个部分:
  791. (1)字符设备驱动程序核心:V4L2本身就是一个字符设备,具有字符设备所有的特性,暴露接口给用户空间;
  792. (2)V4L2驱动核心:主要是构建一个内核中标准视频设备驱动的框架,为视频操作提供统一的接口函数;
  793. (3)平台V4L2设备驱动:在V4L2框架下,根据平台自身的特性实现与平台相关的V4L2驱动部分,包括注册 video_device和v4l2_dev。
  794. (4)具体的sensor驱动:主要上电、提供工作时钟、视频图像裁剪、流IO开启等,实现各种设备控制方法供上层调用并 注册v4l2_subdev 。

  795. V4L2的核心源码位于drivers/media/video中,在4.4版本的内核中位于drivers/media/v4l2-core,源码以实现的功能可以划分为四类:
  796. 核心模块实现:由v4l2-dev.c实现,主要作用申请字符主设备号、注册class和提供video_device注册注销和file_operations等相关函数;
  797. V4L2框架:由v4l2-device.c、v4l2-subdev.c、v4l2-fh.c、v4l2-ctrls.c等文件实现,构建V4L2框架;
  798. Videobuf管理:由videobuf2-core.c、videobuf2-dma-contig.c、videobuf2-dma-sg.c、videobuf2-memops.c、 videobuf2-vmalloc.c、v4l2-mem2mem.c等文件实现,完成videobuffer的分配、管理和注销。
  799. ioctl框架:由v4l2-ioctl.c文件实现,构建V4L2 ioctl的框架。
  800. (二)V4L2框架
  801. 结构体v4l2_device、video_device、v4l2_subdev和v4l2_fh是搭建框架的主要元素。下图是V4L2框架的结构 图:

  802. 从上图可以看出V4L2框架是一个标准的树形结构,v4l2_device充当了父设备,通过链表把所有注册到其下的子设备管理起来,这些设备可以是GRABBER、VBI或RADIO。v4l2_subdev是子设备,v4l2_subdev结构体包含了对设备操作的ops和ctrls,这部分代码和硬件相关,需要驱动工程师根据硬件实现,像摄像头设备需要实现控制上下电、读取ID、饱和度、对比度和视频数据流打开关闭的接口函数。video_device用于创建子设备节点,把操作设备的接口暴露给用户空间。V4l2_fh是每个子设备的文件句柄,在打开设备节点文件时设置,方便上层索引到v4l2_ctrl_handler,v4l2_ctrl_handler管理设备的ctrls,这些ctrls(摄像头设备)包括调节饱和度、对比度和白平衡等。

  803. (三)v4l2_device结构体
  804. v4l2_device在v4l2框架中充当所有v4l2_subdev的父设备,管理着注册在其下的子设备。 它在v4l2-device.h中定义,如下所示:
  805. struct v4l2_device {
  806.     /* dev->driver_data points to this struct.
  807.      Note: dev might be NULL if there is no parent device
  808.      as is the case with e.g. ISA devices. */
  809.     struct device *dev;
  810.     /* used to keep track of the registered subdevs */
  811.     struct list_head subdevs; //它所管理的子设备链表头
  812.     /* lock this struct; can be used by the driver as well if this
  813.      struct is embedded into a larger struct. */
  814.     spinlock_t lock;
  815.     /* unique device name, by default the driver name + bus ID */
  816.     char name[V4L2_DEVICE_NAME_SIZE]; //device名字
  817.     /* notify callback called by some sub-devices. */
  818.     void (*notify)(struct v4l2_subdev *sd,
  819.             unsigned int notification, void *arg);
  820.     /* The control handler. May be NULL. */
  821.     struct v4l2_ctrl_handler *ctrl_handler; //控制接口
  822.     /* Device's priority state */
  823.     struct v4l2_prio_state prio; //设备优先级状态
  824.     /* BKL replacement mutex. Temporary solution only. */
  825.     struct mutex ioctl_lock;
  826.     /* Keep track of the references to this struct. */
  827.     struct kref ref; //引用计数
  828.     /* Release function that is called when the ref count goes to 0. */
  829.     void (*release)(struct v4l2_device *v4l2_dev);
  830. };
  831. 可以看出v4l2_device的主要作用是管理注册在其下的子设备,方便系统查找引用到。
  832. V4l2_device的注册和注销:
  833. int v4l2_device_register(struct device*dev, struct v4l2_device *v4l2_dev)
  834. static void v4l2_device_release(struct kref *ref)
  835. 暂时不对这两个函数进行具体分析,再后面会详细分析这个c文件。

  836. (四)V4l2_subdev
  837. V4l2_subdev代表子设备,包含了子设备的相关属性和操作。先来看下结构体原型,在v4l2-subdev.h中:
  838. struct v4l2_subdev {
  839. #if defined(CONFIG_MEDIA_CONTROLLER)
  840.     struct media_entity entity;
  841. #endif
  842.     struct list_head list;
  843.     struct module *owner;
  844.     u32 flags;
  845.     struct v4l2_device *v4l2_dev; //指向它的父设备
  846.     const struct v4l2_subdev_ops *ops; //提供一些控制v4l2设备的接口
  847.     /* Never call these internal ops from within a */
  848.     const struct v4l2_subdev_internal_ops *internal_ops; //向V4L2框架提供的接口函数
  849.     /* The control handler of this subdev. May be NULL. */
  850.     struct v4l2_ctrl_handler *ctrl_handler; //subdev控制接口
  851.     /* name must be unique */
  852.     char name[V4L2_SUBDEV_NAME_SIZE]; //subdev名字
  853.     /* can be used to group similar subdevs, value is driver-specific */
  854.     u32 grp_id;
  855.     /* pointer to private data */
  856.     void *dev_priv;
  857.     void *host_priv;
  858.     /* subdev device node */
  859.     struct video_device *devnode;
  860. };

  861. 每个子设备驱动都需要实现一个v4l2_subdev结构体,v4l2_subdev可以内嵌到其它结构体中,也可以独立使用。结构体中包含了对子设备操作的成员v4l2_subdev_ops和v4l2_subdev_internal_ops。
  862. v4l2_subdev_ops结构体原型如下:
  863. struct v4l2_subdev_ops {
  864.     const struct v4l2_subdev_core_ops    *core;
  865.     const struct v4l2_subdev_tuner_ops    *tuner;
  866.     const struct v4l2_subdev_audio_ops    *audio;
  867.     const struct v4l2_subdev_video_ops    *video;
  868.     const struct v4l2_subdev_vbi_ops    *vbi;
  869.     const struct v4l2_subdev_ir_ops        *ir;
  870.     const struct v4l2_subdev_sensor_ops    *sensor;
  871.     const struct v4l2_subdev_pad_ops    *pad;
  872. };
  873. 视频设备通常需要实现core和video成员,这两个ops中的操作都是可选的,但是对于视频流设备
  874. video->s_stream(开启或关闭流IO)必须要实现。
  875. v4l2_subdev_internal_ops结构体原型如下:
  876. struct v4l2_subdev_internal_ops {
  877.     int (*registered)(struct v4l2_subdev *sd);
  878.     void (*unregistered)(struct v4l2_subdev *sd);
  879.     int (*open)(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh);
  880.     int (*close)(struct v4l2_subdev *sd, struct v4l2_subdev_fh *fh);
  881. };
  882. v4l2_subdev_internal_ops是向V4L2框架提供的接口,只能被V4L2框架层调用。在注册或打开子设备时,进行一些辅助性操作。

  883. subdev的注册和注销
  884. 当我们把v4l2_subdev需要实现的成员都已经实现,就可以调用以下函数把子设备注册到V4L2核心层:
  885. int v4l2_device_register_subdev(struct v4l2_device*v4l2_dev, struct v4l2_subdev *sd)
  886. 当卸载子设备时,可以调用以下函数进行注销:
  887. void v4l2_device_unregister_subdev(struct v4l2_subdev*sd)


  888. (五)video_device
  889. 1. video_device结构体用于在/dev目录下生成设备节点文件,把操作设备的接口暴露给用户空间。所以这个结构体是我们操作的重点,它直接与用户空间相联系。
  890. struct video_device
  891. {
  892. #if defined(CONFIG_MEDIA_CONTROLLER)
  893.     struct media_entity entity;
  894. #endif
  895.     /* device ops */
  896.     const struct v4l2_file_operations *fops; //V4L2设备操作函数集合
  897.     /* sysfs */
  898.     struct device dev;        /* v4l device */
  899.     struct cdev *cdev;        /* character device */
  900.     /* Set either parent or v4l2_dev if your driver uses v4l2_device */
  901.     struct device *parent;        /* device parent */
  902.     struct v4l2_device *v4l2_dev;    /* v4l2_device parent */
  903.     /* Control handler associated with this device node. May be NULL. */
  904.     struct v4l2_ctrl_handler *ctrl_handler;
  905.     /* Priority state. If NULL, then v4l2_dev->prio will be used. */
  906.     struct v4l2_prio_state *prio;
  907.     /* device info */
  908.     char name[32];
  909.     int vfl_type;
  910.     /* 'minor' is set to -1 if the registration failed */
  911.     int minor;
  912.     u16 num;
  913.     /* use bitops to set/clear/test flags */
  914.     unsigned long flags;
  915.     /* attribute to differentiate multiple indices on one physical device */
  916.     int index;
  917.     /* V4L2 file handles */
  918.     spinlock_t        fh_lock; /* Lock for all v4l2_fhs */
  919.     struct list_head    fh_list; /* List of struct v4l2_fh */
  920.     int debug;            /* Activates debug level*/
  921.     /* Video standard vars */
  922.     v4l2_std_id tvnorms;        /* Supported tv norms */
  923.     v4l2_std_id current_norm;    /* Current tvnorm */
  924.     /* callbacks */
  925.     void (*release)(struct video_device *vdev);
  926.     /* ioctl callbacks */
  927.     const struct v4l2_ioctl_ops *ioctl_ops; /*ioctl回调函数集,提供                                     * file_operations中的ioctl调用 */
  928.     /* serialization lock */
  929.     struct mutex *lock;
  930. };

  931. 2. video_device结构体的name字段是这类设备的名字,它将出现在内核日志和 sysfs中出现。这个名字 通常与驱动名称相同。

  932. 3. vfl_type字段可以是下列5个值之一,他们在v4l2-dev.h中定义:
  933. #define VFL_TYPE_GRABBER    0
  934. #define VFL_TYPE_VBI        1
  935. #define VFL_TYPE_RADIO        2
  936. #define VFL_TYPE_SUBDEV        3
  937. #define VFL_TYPE_MAX        4
  938. 4. V4L2驱动还要初始化的一个字段是 minor,它是你想要的子设备号。通常这个值都设为-1,这样会让video4linux子系统在注册时自动分配一个空的子设备号。

  939. 5. 在video_device结构体中,一共包含三组不同的函数指针集。
  940. 5.1第一个函数指针集只包含一个函数,就是
  941. void (*release)(struct video_device *vdev);
  942. 这个函数通常只包含一个简单的kfree调用,V4L2驱动框架中v4l2-dev.c中帮我们实现了video_device_release,一般让这个函数指向video_device_release即可。
  943. 5.2 第二个函数指针集是const struct v4l2_file_operations *fops; 它与file_operations结构体大致相同,在前面我们就说了,V4L2框架它就是一个字符设备驱动,怎么体现呢?以这个vivi.c为例:
  944. 首先,它作为一个字符设备驱动,肯定有对应的file_operations结构,它就在v4l2-dev.c中定义了:
  945. static const struct file_operations v4l2_fops = {
  946.     .owner = THIS_MODULE,
  947.     .read = v4l2_read,
  948.     .write = v4l2_write,
  949.     .open = v4l2_open,
  950.     .get_unmapped_area = v4l2_get_unmapped_area,
  951.     .mmap = v4l2_mmap,
  952.     .unlocked_ioctl = v4l2_ioctl,
  953.     .release = v4l2_release,
  954.     .poll = v4l2_poll,
  955.     .llseek = no_llseek,
  956. };
  957. 然后,在vivi.c中,我们注册申请video_device vivi_template的时候,需要提供对应的v4l2_file_operations vivi_fops,如下所示:
  958. static struct video_device vivi_template = {
  959.     .name        = "vivi",
  960.     .fops = &vivi_fops,
  961.     .ioctl_ops     = &vivi_ioctl_ops,
  962.     .release    = video_device_release,
  963.     .tvnorms = V4L2_STD_525_60,
  964.     .current_norm = V4L2_STD_NTSC_M,
  965. };

  966. static const struct v4l2_file_operations vivi_fops = {
  967.     .owner        = THIS_MODULE,
  968.     .open = v4l2_fh_open,
  969.     .release = vivi_close,
  970.     .read = vivi_read,
  971.     .poll        = vivi_poll,
  972.     .unlocked_ioctl = video_ioctl2, /* V4L2 ioctl handler */
  973.     .mmap = vivi_mmap,
  974. };
  975. 以read为例,应用程序在调用read的时候,对应到驱动file_operations v4l2_fops中的v4l2_read函数,在函数里面通过ret = vdev->fops->read(filp, buf, sz, off);最后调用到我们在vivi.c中申请注册的video_device vivi_template 结构体里面的fops->read函数,即vivi_read函数。即V4L2框架只是提供了一个中转站的效果。再看vivi_read函数里面,
  976. return vb2_read(&dev->vb_vidq, data, count, ppos, file->f_flags & O_NONBLOCK);
  977. 它又调用了videobuf2-core.c中的vb2_read函数。确实说明了v4l2框架的中转作用。
  978. 这样相似的函数有read, write, poll, mmap, realease等,比较特别的是ioctl函数,在后面分析它。他们都是应用程序调用,通过V4L2框架中转到对应的驱动程序中,然后驱动程序根据不同的调用,选择调用videobuf或ioctl中的函数。
  979. 5.3 第三个函数指针集是const struct v4l2_ioctl_ops *ioctl_ops;在vivi.c中就是
  980. static const struct v4l2_ioctl_ops vivi_ioctl_ops = {
  981.     .vidioc_querycap = vidioc_querycap,
  982.     .vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
  983.     .vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
  984.     .vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
  985.     .vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
  986.     .vidioc_reqbufs = vidioc_reqbufs,
  987.     .vidioc_querybuf = vidioc_querybuf,
  988.     .vidioc_qbuf = vidioc_qbuf,
  989.     .vidioc_dqbuf = vidioc_dqbuf,
  990.     .vidioc_s_std = vidioc_s_std,
  991.     .vidioc_enum_input = vidioc_enum_input,
  992.     .vidioc_g_input = vidioc_g_input,
  993.     .vidioc_s_input = vidioc_s_input,
  994.     .vidioc_streamon = vidioc_streamon,
  995.     .vidioc_streamoff = vidioc_streamoff,
  996.     .vidioc_log_status = v4l2_ctrl_log_status,
  997.     .vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
  998.     .vidioc_unsubscribe_event = v4l2_event_unsubscribe,
  999. };
  1000. 这个ioctl更麻烦,首先作为字符设备驱动,当应用程序调用ioctl的时候,就调用到了file_operations v4l2_fops中的.unlocked_ioctl = v4l2_ioctl,这个v4l2_ioctl同样通过ret = vdev->fops->ioctl(filp, cmd, arg);就调用到了vivi.c中申请注册的video_device vivi_template结构体里面的fops->ioctl函数,即v4l2_file_operations vivi_fops里面的 video_ioctl2函数,这个video_ioctl2函数又调用__video_do_ioctl函数(以上两个函数都在v4l2-ioctl.c中),根据不同的cmd宏,以VIDIOC_QUERYCAP为例,通过
  1001. ret = ops->vidioc_querycap(file, fh, cap);
  1002. 其中struct video_device *vfd = video_devdata(file);
  1003.     const struct v4l2_ioctl_ops *ops = vfd->ioctl_ops;
  1004. 可以看出,__video_do_ioctl函数又调用了video_device vivi_template 结构体里面的.ioctl_ops = &vivi_ioctl_ops,然后根据宏的名字来选择struct v4l2_ioctl_ops vivi_ioctl_ops中对应的函数,即vidioc_querycap函数。
  1005. 这些调用太麻烦了,我决定在后面画一张图表来表示这些调用关系。
  1006. 5.4 video_device分配和释放,用于分配和释放video_device结构体:
  1007. struct video_device *video_device_alloc(void)
  1008. void video_device_release(struct video_device *vdev)
  1009. video_device注册和注销,实现video_device结构体的相关成员后,就可以调用下面的接口进行注册:
  1010. static inline int __must_check video_register_device(struct video_device *vdev,
  1011. inttype, int nr)
  1012. void video_unregister_device(struct video_device*vdev);
  1013. vdev:需要注册和注销的video_device;
  1014. type:设备类型,包括VFL_TYPE_GRABBER、VFL_TYPE_VBI、VFL_TYPE_RADIO和VFL_TYPE_SUBDEV。
  1015. nr:设备节点名编号,/dev/video[nr]

  1016. (六)v4l2_fh
  1017. v4l2_fh是用来保存子设备的特有操作方法,也就是下面要分析到的v4l2_ctrl_handler,内核提供一组v4l2_fh的操作方法,通常在打开设备节点时进行v4l2_fh注册。
  1018. 初始化v4l2_fh,添加v4l2_ctrl_handler到v4l2_fh:
  1019. void v4l2_fh_init(struct v4l2_fh *fh, structvideo_device *vdev)
  1020. 添加v4l2_fh到video_device,方便核心层调用到:
  1021. void v4l2_fh_add(struct v4l2_fh *fh)

  1022. (七)v4l2_ctrl_handler
  1023. v4l2_ctrl_handler是用于保存子设备控制方法集的结构体,对于视频设备这些ctrls包括设置亮度、饱和度、对比度和 清晰度等,用链表的方式来保存ctrls,可以通过v4l2_ctrl_new_std函数向链表添加ctrls。
  1024. struct v4l2_ctrl *v4l2_ctrl_new_std(struct v4l2_ctrl_handler *hdl,
  1025. const struct v4l2_ctrl_ops *ops, u32 id, s32 min, s32 max, u32 step, s32 def)
  1026. hdl是初始化好的v4l2_ctrl_handler结构体;
  1027. ops是v4l2_ctrl_ops结构体,包含ctrls的具体实现;
  1028. id是通过IOCTL的arg参数传过来的指令,定义在v4l2-controls.h文件;
  1029. min、max用来定义某操作对象的范围。如:
  1030. v4l2_ctrl_new_std(hdl, ops, V4L2_CID_BRIGHTNESS,-208, 127, 1, 0);
  1031. 用户空间可以通过ioctl的VIDIOC_S_CTRL指令调用到v4l2_ctrl_handler,id透过arg参数传递。

  1032. (八)ioctl框架
  1033. 你可能观察到用户空间对V4L2设备的操作基本都是ioctl来实现的,V4L2设备都有大量可操作的功能(配置寄存器),所以V4L2的ioctl也是十分庞大的。它是一个怎样的框架,是怎么实现的呢?
  1034. ioctl函数在v4l2-ioctl.h中定义,一共包含79个回调函数,如果在这列举的话,就会显得太冗长了,我们会在下面用到的部分再列举,现显示部分如下所示:
  1035. struct v4l2_ioctl_ops {
  1036.     /* ioctl callbacks */

  1037.     /* VIDIOC_QUERYCAP handler */
  1038.     int (*vidioc_querycap)(struct file *file, void *fh, struct v4l2_capability *cap);

  1039.     /* Priority handling */
  1040.     int (*vidioc_g_priority) (struct file *file, void *fh,
  1041.                  enum v4l2_priority *p);
  1042.     int (*vidioc_s_priority) (struct file *file, void *fh,
  1043.                  enum v4l2_priority p);
  1044. ......................................
  1045.     /* For other private ioctls */
  1046.     long (*vidioc_default)     (struct file *file, void *fh,
  1047.                     bool valid_prio, int cmd, void *arg);
  1048. };

  1049. 8.1 驱动要实现的第一个回调函数可能就是:
  1050. /* VIDIOC_QUERYCAP handler */
  1051.     int (*vidioc_querycap)(struct file *file, void *priv, struct v4l2_capability *cap);
  1052. 这个函数处理 VIDIOC_QUERYCAP 的 ioctl(), 只是简单问问“你是谁?你能干什么?”实现它是 V4L2 驱动的责任。和所有其他V4L2回调函数一样,这个函数中的参数 priv 是 file->private_data 域的内容,通 常的做法是在 open()的时候把它指向驱动中表示设备的内部结构体。
  1053. 驱动应该负责填充cap结构并且返回“0或负的错误码”值。如果成功返回,则V4L2层会负责把回复拷 贝到用户空间。
  1054. struct v4l2_capability定义在videodev2.h中,如下所示:
  1055. /**
  1056.   * struct v4l2_capability - Describes V4L2 device caps returned by                                         VIDIOC_QUERYCAP
  1057.   *
  1058.   * @driver:     name of the driver module (e.g. "bttv")
  1059.   * @card:     name of the card (e.g. "Hauppauge WinTV")
  1060.   * @bus_info:     name of the bus (e.g. "PCI:" + pci_name(pci_dev) )
  1061.   * @version:     KERNEL_VERSION
  1062.   * @capabilities: capabilities of the physical device as a whole
  1063.   * @device_caps: capabilities accessed via this particular device (node)
  1064.   * @reserved:     reserved fields for future extensions
  1065.   */
  1066. struct v4l2_capability {
  1067.     __u8    driver[16]; //driver的名字
  1068.     __u8    card[32]; //设备的硬件描述信息
  1069.     __u8    bus_info[32];
  1070.     __u32 version; //内核版本号
  1071.     __u32    capabilities;
  1072.     __u32    device_caps;
  1073.     __u32    reserved[3];
  1074. };
  1075. 对于bus_info 成员,驱动程序一般用strlcpy(cap->bus_info, dev->v4l2_dev.name, sizeof(cap->bus_info));来填充。
  1076. capabilities 成员是一个位掩码用来描述驱动能做的不同事情,也在videodev2.h中定义:
  1077. /* Values for 'capabilities' field */
  1078. #define V4L2_CAP_VIDEO_CAPTURE        0x00000001 /* Is a video capture device */
  1079. #define V4L2_CAP_VIDEO_OUTPUT        0x00000002 /* Is a video output device */
  1080. #define V4L2_CAP_VIDEO_OVERLAY        0x00000004 /* Can do video overlay */
  1081. #define V4L2_CAP_VBI_CAPTURE        0x00000010 /* Is a raw VBI capture device */
  1082. #define V4L2_CAP_VBI_OUTPUT        0x00000020 /* Is a raw VBI output device */
  1083. #define V4L2_CAP_SLICED_VBI_CAPTURE    0x00000040 /* Is a sliced VBI capture device */
  1084. #define V4L2_CAP_SLICED_VBI_OUTPUT    0x00000080 /* Is a sliced VBI output device */
  1085. #define V4L2_CAP_RDS_CAPTURE        0x00000100 /* RDS data capture */
  1086. #define V4L2_CAP_VIDEO_OUTPUT_OVERLAY    0x00000200 /* Can do video output overlay */
  1087. #define V4L2_CAP_HW_FREQ_SEEK        0x00000400 /* Can do hardware frequency seek */
  1088. #define V4L2_CAP_RDS_OUTPUT        0x00000800 /* Is an RDS encoder */

  1089. /* Is a video capture device that supports multiplanar formats */
  1090. #define V4L2_CAP_VIDEO_CAPTURE_MPLANE    0x00001000
  1091. /* Is a video output device that supports multiplanar formats */
  1092. #define V4L2_CAP_VIDEO_OUTPUT_MPLANE    0x00002000

  1093. #define V4L2_CAP_TUNER            0x00010000 /* has a tuner */
  1094. #define V4L2_CAP_AUDIO            0x00020000 /* has audio support */
  1095. #define V4L2_CAP_RADIO            0x00040000 /* is a radio device */
  1096. #define V4L2_CAP_MODULATOR        0x00080000 /* has a modulator */

  1097. #define V4L2_CAP_READWRITE 0x01000000 /* read/write systemcalls */
  1098. #define V4L2_CAP_ASYNCIO 0x02000000 /* async I/O */
  1099. #define V4L2_CAP_STREAMING 0x04000000 /* streaming I/O ioctls */

  1100. #define V4L2_CAP_DEVICE_CAPS 0x80000000 /* sets device capabilities field */
  1101. 下面我们来看看vivi.c中对它的实现:
  1102. static int vidioc_querycap(struct file *file, void *priv,
  1103.                     struct v4l2_capability *cap)
  1104. {
  1105.     struct vivi_dev *dev = video_drvdata(file);

  1106.     strcpy(cap->driver, "vivi");
  1107.     strcpy(cap->card, "vivi");
  1108.     strlcpy(cap->bus_info, dev->v4l2_dev.name, sizeof(cap->bus_info));
  1109.     cap->device_caps = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING |
  1110.              V4L2_CAP_READWRITE;
  1111.     cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
  1112.     return 0;
  1113. }
  1114. 它就是完成上述我们所说的事情。

  1115. 8.2 输入和输出
  1116. 8.2.1 综述
  1117.     在很多情况下,视频适配器并不能提供很多的输入输出选项。比如摄像头控制器,可能只是提供摄像 头信号输入,而没什么别的功能;然而,在一些其他的情况下,事情就变得复杂了。一个电视卡板上不同 的接口可能对应不同的输入。他甚至可能拥有可独立发挥功能的多路调谐器。有时,那些输入会有不同的 特性,有些调谐器可以支持比其他的更广泛的视频标准。对于输出来说,也有同样的问题。 很明显,一个应用若想有效地利用视频适配器,它必须有能力找到可用的输入和输出,而且他必须能 找到他想操作的那一个。为此,Video4Linux2 API提供三种不同的ioctl()调用来处理输入,相应地有三个来 处理输出。如下所示:
  1118.     int (*vidioc_g_std) (struct file *file, void *fh, v4l2_std_id *norm);
  1119.     int (*vidioc_s_std) (struct file *file, void *fh, v4l2_std_id *norm);
  1120.     int (*vidioc_querystd) (struct file *file, void *fh, v4l2_std_id *a);

  1121.     /* Input handling */
  1122.     int (*vidioc_enum_input)(struct file *file, void *fh, struct v4l2_input *inp);
  1123.     int (*vidioc_g_input) (struct file *file, void *fh, unsigned int *i);
  1124.     int (*vidioc_s_input) (struct file *file, void *fh, unsigned int i);

  1125.     /* Output handling */
  1126.     int (*vidioc_enum_output) (struct file *file, void *fh, struct v4l2_output *a);
  1127.     int (*vidioc_g_output) (struct file *file, void *fh, unsigned int *i);
  1128.     int (*vidioc_s_output) (struct file *file, void *fh, unsigned int i);
  1129. 对于用户空间而言,V4L2提供一个ioctl()命令(VIDIOC_ENUMSTD),它允许应用查询设备实现了哪 些标准。驱动却无需直接回答查询,而是将video_device 结构体的tvnorm字段设置为它所支持的所有标准。
  1130. 然后V4L2层会向应用回复所支持的标准。VIDIOC_G_STD命令可以用来查询现在哪种标准是激活的,它 也是在V4L2层通过返回video_device结构体的current_norm字段来处理的。驱动程序应在启动时,初始化 current_norm来反映现实情况。 当某个应用想要申请某个特定标准时,会发出一个 VIDIOC_S_STD 调用,该调用传到驱动时通过调用int (*vidioc_s_std) (struct file *file, void *fh, v4l2_std_id *norm); 回调函数来实现,来看vivi.c中,
  1131. static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *i)
  1132. {
  1133.     return 0;
  1134. }
  1135. 它就什么都没做,因为在设置video_device结构体的时候设置了:
  1136. static struct video_device vivi_template = {
  1137.     .name        = "vivi",
  1138.     .fops = &vivi_fops,
  1139.     .ioctl_ops     = &vivi_ioctl_ops,
  1140.     .release    = video_device_release,

  1141.     .tvnorms = V4L2_STD_525_60,
  1142.     .current_norm = V4L2_STD_NTSC_M,
  1143. };
  1144. 下面就简单说一些视频标准,这些标准描述的是视频如何为传输 而进行格式化---分辨率、帧率等。 现在世界上使用的 标准主要有三个:NTSC(主要是北美使用)、PAL(主要是欧洲、非洲和中国)和 SECAM(法、俄和非洲部分地 区)
  1145. V4L2 使用v4l2_std_id 来代表视频标准,它是一个64位的掩码。每个标准变种在掩码中就是一位。所
  1146. 以 “标准”NTSC 的定义为V4L2_STD_NTSC_M, 值为 0x1000 ; 而日本的变种就是V4L2_STD_NTSC_M_JP(0x2000)。如果一个设备可以处理所有NTSC变种,它就可以设为V4L2_STD_NTSC,它将所有相关位置位。它同样在videodev2.h中定义:
  1147. /*
  1148.  * A N A L O G V I D E O S T A N D A R D
  1149.  */

  1150. typedef __u64 v4l2_std_id;
  1151.  
  1152. /* one bit for each */
  1153. #define V4L2_STD_PAL_B ((v4l2_std_id)0x00000001)
  1154. #define V4L2_STD_PAL_B1 ((v4l2_std_id)0x00000002)
  1155. #define V4L2_STD_PAL_G ((v4l2_std_id)0x00000004)
  1156. #define V4L2_STD_PAL_H ((v4l2_std_id)0x00000008)
  1157. #define V4L2_STD_PAL_I ((v4l2_std_id)0x00000010)
  1158. #define V4L2_STD_PAL_D ((v4l2_std_id)0x00000020)
  1159. #define V4L2_STD_PAL_D1 ((v4l2_std_id)0x00000040)
  1160. #define V4L2_STD_PAL_K ((v4l2_std_id)0x00000080)

  1161. #define V4L2_STD_PAL_M ((v4l2_std_id)0x00000100)
  1162. #define V4L2_STD_PAL_N ((v4l2_std_id)0x00000200)
  1163. #define V4L2_STD_PAL_Nc ((v4l2_std_id)0x00000400)
  1164. #define V4L2_STD_PAL_60 ((v4l2_std_id)0x00000800)

  1165. #define V4L2_STD_NTSC_M ((v4l2_std_id)0x00001000)    /* BTSC */
  1166. #define V4L2_STD_NTSC_M_JP ((v4l2_std_id)0x00002000)    /* EIA-J */
  1167. #define V4L2_STD_NTSC_443 ((v4l2_std_id)0x00004000)
  1168. #define V4L2_STD_NTSC_M_KR ((v4l2_std_id)0x00008000)    /* FM A2 */

  1169. #define V4L2_STD_SECAM_B ((v4l2_std_id)0x00010000)
  1170. #define V4L2_STD_SECAM_D ((v4l2_std_id)0x00020000)
  1171. #define V4L2_STD_SECAM_G ((v4l2_std_id)0x00040000)
  1172. #define V4L2_STD_SECAM_H ((v4l2_std_id)0x00080000)
  1173. #define V4L2_STD_SECAM_K ((v4l2_std_id)0x00100000)
  1174. #define V4L2_STD_SECAM_K1 ((v4l2_std_id)0x00200000)
  1175. #define V4L2_STD_SECAM_L ((v4l2_std_id)0x00400000)
  1176. #define V4L2_STD_SECAM_LC ((v4l2_std_id)0x00800000)

  1177. /* ATSC/HDTV */
  1178. #define V4L2_STD_ATSC_8_VSB ((v4l2_std_id)0x01000000)
  1179. #define V4L2_STD_ATSC_16_VSB ((v4l2_std_id)0x02000000)

  1180. /*
  1181.  * "Common" NTSC/M - It should be noticed that V4L2_STD_NTSC_443 is
  1182.  * Missing here.
  1183.  */
  1184. #define V4L2_STD_NTSC (V4L2_STD_NTSC_M | V4L2_STD_NTSC_M_JP | V4L2_STD_NTSC_M_KR)

  1185. 8.2.2 输入
  1186. 视频捕获的应用首先要通过 VIDIOC_ENUMINPUT 命令来枚举所有可用的输入。在V4L2层,这个调
  1187. 用会转换成调用驱动中对应的回调函数:
  1188. int (*vidioc_enum_input)(struct file *file, void *priv, struct v4l2_input *inp);
  1189. 在这个调用中,file 对应要打开的视频设备。priv是驱动的私有字段。inp字段是传递的真正 信息,
  1190. 先来看看这个v4l2_input结构体,它在videodev2.h中定义:
  1191. struct v4l2_input {
  1192.     __u32     index;        /* Which input */
  1193.     __u8     name[32];        /* Label */
  1194.     __u32     type;        /* Type of input */
  1195.     __u32     audioset;        /* Associated audios (bitfield) */
  1196.     __u32 tuner; /* Associated tuner */
  1197.     v4l2_std_id std;
  1198.     __u32     status;
  1199.     __u32     capabilities;
  1200.     __u32     reserved[3];
  1201. };
  1202. index:是应用关注的输入索引号; 这是惟一一个用户空间设定的字段。驱动要分配索引号给输入,从0开始,依次增加。想要知道所有可用的输入,应用会调用 VIDIOC_ENUMINPUT,索引号从0开始,并开始递增。一旦驱动返回-EINVAL,应用就知道:输入己经枚举完了。只要有输入,输入索引号0就一定存在。
  1203. name:是输入的名字,由驱动确定。
  1204. type:输入类型,只有两个值可选 : V4L2_INPUT_TYPE_TUNER 和 V4L2_INPUT_TYPE_CAMERA。
  1205. status:给出输入状态,其中设置的每一位都代表一个问题,比如说掉电,无信号等问题,定义如下:
  1206. #define V4L2_IN_ST_NO_POWER 0x00000001 /* Attached device is off */
  1207. #define V4L2_IN_ST_NO_SIGNAL 0x00000002
  1208. #define V4L2_IN_ST_NO_COLOR 0x00000004
  1209. std:描述设备支持哪个或哪些视频标准。就是上面咱们所说的视频标准。
  1210. 来看看vivi.c中是怎么实现这个函数的:
  1211. /* only one input in this sample driver */
  1212. static int vidioc_enum_input(struct file *file, void *priv,
  1213.                 struct v4l2_input *inp)
  1214. {
  1215.     if (inp->index >= NUM_INPUTS)
  1216.         return -EINVAL;

  1217.     inp->type = V4L2_INPUT_TYPE_CAMERA;
  1218.     inp->std = V4L2_STD_525_60;
  1219.     sprintf(inp->name, "Camera %u", inp->index);
  1220.     return 0;
  1221. }

  1222. 当应用想改变当前输入时,驱动会收到一个对回调函数 vidioc_s_input()的调用。
  1223. int (*vidioc_s_input) (struct file *file, void *priv, unsigned int index);
  1224. index与上面提到的相同,它用来确定哪个输入是想要的 ,驱动要对硬件操作,选择指定输
  1225. 入并返回 0。也有可能要返回-EINVAL(索引号不正确)-EIO(硬件故障)。即使只有一路输入,驱动也要实 现这个回调函数。
  1226. 还有另一个回调函数,指示哪一个输入处在激活状态:
  1227. int (*vidioc_g_input) (struct file *file, void *priv, unsigned int *index);
  1228. 这里驱动把*index 值设为当前激活输入的索引号。
  1229. 看看vivi.c中对这两个函数的实现:
  1230. static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
  1231. {
  1232.     struct vivi_dev *dev = video_drvdata(file);

  1233.     *i = dev->input;
  1234.     return 0;
  1235. }

  1236. static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
  1237. {
  1238.     struct vivi_dev *dev = video_drvdata(file);

  1239.     if (i >= NUM_INPUTS)
  1240.         return -EINVAL;

  1241.     if (i == dev->input)
  1242.         return 0;

  1243.     dev->input = i;
  1244.     precalculate_bars(dev);
  1245.     precalculate_line(dev);
  1246.     return 0;
  1247. }

  1248. 8.2.3 输出
  1249. 枚举和选择输出的过程与输入十分相似。
  1250. 输出枚举的回调函数是这样的:
  1251. int (*vidioc_enumoutput) (struct file *file, void *private_data, struct v4l2_output *output);
  1252. 其中v4l2_output结构体如下所示:
  1253. struct v4l2_output {
  1254.     __u32     index;        /* Which output */
  1255.     __u8     name[32];        /* Label */
  1256.     __u32     type;        /* Type of output */
  1257.     __u32     audioset;        /* Associated audios (bitfield) */
  1258.     __u32     modulator; /* Associated modulator */
  1259.     v4l2_std_id std;
  1260.     __u32     capabilities;
  1261.     __u32     reserved[3];
  1262. };
  1263. index:相关输出索引号,工作方式与输入的索引号相同。
  1264. type:输出类型,支持的类型如下:
  1265. /* Values for the 'type' field */
  1266. #define V4L2_OUTPUT_TYPE_MODULATOR         1 //用于模拟电视调制器
  1267. #define V4L2_OUTPUT_TYPE_ANALOG            2 //用于基本模拟视频输出
  1268. #define V4L2_OUTPUT_TYPE_ANALOGVGAOVERLAY     3 //用于模拟 VGA 覆盖设备
  1269. audioset:能与视频协同工作的音频集。
  1270. modulator:与此设备相关的调制器(仅对类型为 V4L2_OUTPUT_TYPE_MODULATOR 的设 备而言)
  1271. std:描述设备支持哪个或哪些视频标准。就是上面咱们所说的视频标准。
  1272. capabilities flags:
  1273. #define V4L2_OUT_CAP_PRESETS         0x00000001 /* Supports S_DV_PRESET */
  1274. #define V4L2_OUT_CAP_CUSTOM_TIMINGS     0x00000002 /* Supports S_DV_TIMINGS */
  1275. #define V4L2_OUT_CAP_STD         0x00000004 /* Supports S_STD */
  1276. 也有用于获得和设定现行输出设置的回调函数:
  1277. int (*vidioc_g_output) (struct file *file, void *fh, unsigned int *i);
  1278. int (*vidioc_s_output) (struct file *file, void *fh, unsigned int i);
  1279. 有了这些函数之后,V4L2 应用就可以知道有哪些输入和输入,并在它们间进行选择。

  1280. 8.3 颜色与格式
  1281. 应用在视频设备可以工作之前,它必须与驱动达成一致,知道视频数据是何种格式。这种协商将是一
  1282. 个非常复杂的过程,其原因有二:
  1283. 1、 视频硬件所支持的视频格各不相同。
  1284. 2、 在内核的格式转换是令人难以接受的。
  1285. 所以应用要找出一种硬件支持的格式,并做出一种大家都可以接受的配置。 这篇文章将会讲述格式的
  1286. 基本描述方式,下篇文章则会讲述 V4L2 驱动与应用协商格式时所实现的 API。

  1287. 8.3.1 色域
  1288. 色域从广义上来讲,就是系统在描述色彩时所使用的坐标系。V4L2 规范中定义了好几个,但只有两个
  1289. 的使用最为广泛。它们是:
  1290. ● V4L2_COLORSPACE_SRGB
  1291. 多数开发者所熟悉的[red、green、blue]数组就包含在这个色域中。它为每一种颜色提供了一个简单的
  1292. 强度值,把它们混合在一起,从而产生了丰富的颜色。表示 RGB 值的方法有很多,我们在下面将会介绍。 这个色域也包含 YUV 和 YCbCr 的表示方法,这个表示方法最早是为了早期的彩色电视信号可以在黑 白电视中的播放,所以 Y(或“亮度” )值只是一个简单的亮度值,单独显示时可以产生灰度图像。U 和 V (或 Cb 和 Cr)色度值描述的是色彩中蓝色和红色的分量。绿色可以通过从亮度中减去这些分量而得到。
  1293. YUV 和 RGB 之间的转换并不那么直接,但是我们有一些公式可用。
  1294. 注意:YUV 和 YCbCr 并非完全一样,虽然有时他们的名字会替代使用。
  1295. ● V4L2_COLORSPACE_SMPTE170M
  1296. 这个是 NTSC 或 PAL 等电视信号的模拟色彩表示方法,电视调谐器通常产生的色域都属于这个色域。 还存在很多其他的色域,他们多数都是电视相关标准的变种。

  1297. 8.3.2 密集存储和平面存储
  1298. 如上所述,像素值是以数组的方式表示的,通常由 RGB 或 YUV 值组成。要把这数组组织成图像,通 常有两种常用的方法。
  1299. ● Packed 格式把一个像素的所有分量值连续存放在一起。
  1300. ● Planar 格式把每一个分量单独存储成一个阵列。例如在 YUV 格式中,所有 Y 值都连续地一起存 储在一个阵列中,U 值存储在另一个中,V 值存在第三个中。这些平面常常都存储在一个缓冲区 中,但并不一定非要这样。
  1301. 紧密型存储方式可能使用更为广泛,特别是 RGB 格式,但这两种存储方式都可以由硬件产生并由应用 程序请求。如果设备可以产生紧密型和平面型两种,那么驱动就要让两种都在用户空间可见。

  1302. 8.3.3 四字符码 (four Charactor Code : FourCC )
  1303. V4L2 API 中表示色彩格式采用的是广受好评的四字符码(fourcc)机制。这些编码都是 32 位的值,由四
  1304. 个 ASCII 码产生。 如此一来, 它就有一个优点就是, 易于传递, 对人可读。 例如, 当一个色彩格式读作“RGB4” 就没有必要去查表了。
  1305. 注意:
  1306. 四字符码在很多不同的配置中都会使用, 有些还是早于linux。 Mplayer 内部使用它们, 然而, fourcc 只是说明一种编码机制,并不说明使用何种编码。Mplayer有一个转换函数,用于在它自己的fourcc码和v4l2 用的fourcc码之间做出转换。

  1307. 8.3.4 RGB 格式:(videodev2.h中)
  1308. /* RGB formats */
  1309. #define V4L2_PIX_FMT_RGB332 v4l2_fourcc('R', 'G', 'B', '1') /* 8 RGB-3-3-2 */
  1310. #define V4L2_PIX_FMT_RGB444 v4l2_fourcc('R', '4', '4', '4') /* 16 xxxxrrrr ggggbbbb */
  1311. #define V4L2_PIX_FMT_RGB555 v4l2_fourcc('R', 'G', 'B', 'O') /* 16 RGB-5-5-5 */
  1312. #define V4L2_PIX_FMT_RGB565 v4l2_fourcc('R', 'G', 'B', 'P') /* 16 RGB-5-6-5 */
  1313. #define V4L2_PIX_FMT_RGB555X v4l2_fourcc('R', 'G', 'B', 'Q') /* 16 RGB-5-5-5 BE */
  1314. #define V4L2_PIX_FMT_RGB565X v4l2_fourcc('R', 'G', 'B', 'R') /* 16 RGB-5-6-5 BE */
  1315. #define V4L2_PIX_FMT_BGR666 v4l2_fourcc('B', 'G', 'R', 'H') /* 18 BGR-6-6-6     */
  1316. #define V4L2_PIX_FMT_BGR24 v4l2_fourcc('B', 'G', 'R', '3') /* 24 BGR-8-8-8 */
  1317. #define V4L2_PIX_FMT_RGB24 v4l2_fourcc('R', 'G', 'B', '3') /* 24 RGB-8-8-8 */
  1318. #define V4L2_PIX_FMT_BGR32 v4l2_fourcc('B', 'G', 'R', '4') /* 32 BGR-8-8-8-8 */
  1319. #define V4L2_PIX_FMT_RGB32 v4l2_fourcc('R', 'G', 'B', '4') /* 32 RGB-8-8-8-8 */

  1320. 8.3.5 YUV 格式(videodev2.h中)
  1321. /* Luminance+Chrominance formats */
  1322. #define V4L2_PIX_FMT_YVU410 v4l2_fourcc('Y', 'V', 'U', '9') /* 9 YVU 4:1:0 */
  1323. #define V4L2_PIX_FMT_YVU420 v4l2_fourcc('Y', 'V', '1', '2') /* 12 YVU 4:2:0 */
  1324. #define V4L2_PIX_FMT_YUYV v4l2_fourcc('Y', 'U', 'Y', 'V') /* 16 YUV 4:2:2 */
  1325. #define V4L2_PIX_FMT_YYUV v4l2_fourcc('Y', 'Y', 'U', 'V') /* 16 YUV 4:2:2 */
  1326. #define V4L2_PIX_FMT_YVYU v4l2_fourcc('Y', 'V', 'Y', 'U') /* 16 YVU 4:2:2 */
  1327. #define V4L2_PIX_FMT_UYVY v4l2_fourcc('U', 'Y', 'V', 'Y') /* 16 YUV 4:2:2 */
  1328. #define V4L2_PIX_FMT_VYUY v4l2_fourcc('V', 'Y', 'U', 'Y') /* 16 YUV 4:2:2 */
  1329. #define V4L2_PIX_FMT_YUV422P v4l2_fourcc('4', '2', '2', 'P') /* 16 YVU422 planar */
  1330. #define V4L2_PIX_FMT_YUV411P v4l2_fourcc('4', '1', '1', 'P') /* 16 YVU411 planar */
  1331. #define V4L2_PIX_FMT_Y41P v4l2_fourcc('Y', '4', '1', 'P') /* 12 YUV 4:1:1 */
  1332. #define V4L2_PIX_FMT_YUV444 v4l2_fourcc('Y', '4', '4', '4') /* 16 xxxxyyyy uuuuvvvv */
  1333. #define V4L2_PIX_FMT_YUV555 v4l2_fourcc('Y', 'U', 'V', 'O') /* 16 YUV-5-5-5 */
  1334. #define V4L2_PIX_FMT_YUV565 v4l2_fourcc('Y', 'U', 'V', 'P') /* 16 YUV-5-6-5 */
  1335. #define V4L2_PIX_FMT_YUV32 v4l2_fourcc('Y', 'U', 'V', '4') /* 32 YUV-8-8-8-8 */
  1336. #define V4L2_PIX_FMT_YUV410 v4l2_fourcc('Y', 'U', 'V', '9') /* 9 YUV 4:1:0 */
  1337. #define V4L2_PIX_FMT_YUV420 v4l2_fourcc('Y', 'U', '1', '2') /* 12 YUV 4:2:0 */
  1338. #define V4L2_PIX_FMT_HI240 v4l2_fourcc('H', 'I', '2', '4') /* 8 8-bit color */
  1339. #define V4L2_PIX_FMT_HM12 v4l2_fourcc('H', 'M', '1', '2') /* 8 YUV 4:2:0 16x16 macroblocks */
  1340. #define V4L2_PIX_FMT_M420 v4l2_fourcc('M', '4', '2', '0') /* 12 YUV 4:2:0 2 lines y, 1 line uv interleaved */

  1341. 8.3.6其他格式
  1342. /* compressed formats */
  1343. #define V4L2_PIX_FMT_MJPEG v4l2_fourcc('M', 'J', 'P', 'G') /* Motion-JPEG */
  1344. #define V4L2_PIX_FMT_JPEG v4l2_fourcc('J', 'P', 'E', 'G') /* JFIF JPEG */
  1345. 等等。。。。。。
  1346. 8.3.7 格式描述符,struct v4l2_pix_format,它在videodev2.h中定义:
  1347. struct v4l2_pix_format {
  1348.     __u32     width;
  1349.     __u32            height;
  1350.     __u32            pixelformat;
  1351.     enum v4l2_field     field;
  1352.     __u32     bytesperline;    /* for padding, zero if unused */
  1353.     __u32         sizeimage;
  1354.     enum v4l2_colorspace    colorspace;
  1355.     __u32            priv;        /* private data, depends on pixelformat */
  1356. };
  1357. width:图像宽度,以像素为单位
  1358. height:图像高度,以像素为单位
  1359. pixelformat:描述图像格式的四字符码
  1360. field:很多图像源会使数据交错——先传输奇数行,然后是偶数行。真正的摄像 头设备是不会做数据交错的。 V4L2 API允许应用使用多种交错方式。常用的值为 V4L2_FIELD_NONE (非交错)、 V4l2_FIELD_TOP (仅顶部交错)或 V4L2_FIELD_ANY (忽略)。具体的值可以去查看 enum v4l2_field的值,在这就不一一列举了。
  1361. bytesperline:相临扫描行之间的字节数,这包括各种设备可能会加入的填充字节。
  1362. sizeimage:存储图像所需的缓冲区的大小。
  1363. colorspace:使用的色域。同样可以查看 enum v4l2_colorspace的值:
  1364. enum v4l2_colorspace {
  1365.     V4L2_COLORSPACE_SMPTE170M = 1,
  1366.     V4L2_COLORSPACE_SMPTE240M = 2,
  1367.     V4L2_COLORSPACE_REC709 = 3,
  1368.     V4L2_COLORSPACE_BT878 = 4,
  1369.     V4L2_COLORSPACE_470_SYSTEM_M = 5,
  1370.     V4L2_COLORSPACE_470_SYSTEM_BG = 6,
  1371.     V4L2_COLORSPACE_JPEG = 7,
  1372.     V4L2_COLORSPACE_SRGB = 8,
  1373. };

  1374. 至此,对于视频数据缓冲区的描述就算完成了,驱动程序需要和应用程序协商,以使硬件设备支持的图像格式能够满足应用程序的使用。下面再来讲驱动程序和应用程序协商的过程。

  1375. 8.4 格式协商
  1376. 在存储器中表示图像的方法有很多种。 市场几乎找不到可以处理所有V4L2所理解的视频格式的设备。驱动不应支持底层硬件不理解的视频格式。实际上在内核中进行格式转换是令人难以接受的。 所以驱动必须能让应用选择一个硬件可以支持的格式。

  1377. 8.4.1 第一步就是简单的允许应用查询所支持的格式。VIDIOC_ENUM_FMT ioctl()就是为此目的而提供的。 在驱动内部,这个调用会转化为如下的回调函数(如果查询的是视频捕获设备 )。
  1378. int (*vidioc_enum_fmt_vid_cap) (struct file *file, void *fh, struct v4l2_fmtdesc *f);
  1379. 这个回调函数要求视频捕获设备描述其支持的格式,应用会传入一个v4l2_fmtdesc结构体:
  1380. struct v4l2_fmtdesc {
  1381.     __u32         index; /* Format number */
  1382.     enum v4l2_buf_type type; /* buffer type */
  1383.     __u32 flags;
  1384.     __u8         description[32]; /* Description string */
  1385.     __u32         pixelformat; /* Format fourcc */
  1386.     __u32         reserved[4];
  1387. };

  1388. 应用会设置index和type成员:
  1389. index:用来确定格式的一个简单整型数;与其他 V4L2 所使用的索引一样,这个也是从 0 开始递 增,至最大允许值为止。应用可以通过一直递增索引值直到返回-EINVAL 的方式枚举所有支持的 格式。
  1390. type:描述的是数据流类型,对于视频捕获设备(摄像头)来说就V4L2_BUF_TYPE_VIDEO_CAPTURE。

  1391. 如果index对就某个支持的格式,驱动应该填写结构体的其他成员:
  1392. flags:只定义了一个值,即 V4L2_FMT_FLAG_COMPRESSED,表示一个压缩的视频格式。
  1393. description:一般来说可以是对这个格式的一种简短的字符串描述。
  1394. pixelformat:描述视频表现方式的四字符码。

  1395. 对于上述这个回调函数,它其实针对的是视频捕获设备,只有当 type 值为V4L2_BUF_TYPE_VIDEO_CAPTURE 时才会调用,这是一个回调函数集, 对于其他不同的设备,会根据不同的type值调用不同的回调函数。下面列举如下:
  1396. /* VIDIOC_ENUM_FMT handlers */
  1397. int (*vidioc_enum_fmt_vid_cap) (struct file *file, void *fh, struct v4l2_fmtdesc *f);
  1398. int (*vidioc_enum_fmt_vid_overlay) (struct file *file, void *fh, struct v4l2_fmtdesc *f);
  1399. int (*vidioc_enum_fmt_vid_out) (struct file *file, void *fh, struct v4l2_fmtdesc *f);
  1400. int (*vidioc_enum_fmt_vid_cap_mplane)(struct file *file, void *fh, struct v4l2_fmtdesc *f);
  1401. int (*vidioc_enum_fmt_vid_out_mplane)(struct file *file, void *fh, struct v4l2_fmtdesc *f);
  1402. int (*vidioc_enum_fmt_type_private)(struct file *file, void *fh, struct v4l2_fmtdesc *f);

  1403. 来看看vivi.c中对于这个回调函数的实现:
  1404. static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
  1405.                     struct v4l2_fmtdesc *f)
  1406. {
  1407.     struct vivi_fmt *fmt;

  1408.     if (f->index >= ARRAY_SIZE(formats))
  1409.         return -EINVAL;

  1410.     fmt = &formats[f->index];

  1411.     strlcpy(f->description, fmt->name, sizeof(f->description));
  1412.     f->pixelformat = fmt->fourcc;
  1413.     return 0;
  1414. }

  1415. 8.4.2 应用程序可以通过调用 VIDIOC_G_FMT 知道硬件现在的配置。 这种情况下传递的参数是一个v4l2_format 结构体:
  1416. struct v4l2_format {
  1417.     enum v4l2_buf_type type;
  1418.     union {
  1419.         struct v4l2_pix_format        pix; /* V4L2_BUF_TYPE_VIDEO_CAPTURE */
  1420.         struct v4l2_pix_format_mplane    pix_mp; /* V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE */
  1421.         struct v4l2_window        win; /* V4L2_BUF_TYPE_VIDEO_OVERLAY */
  1422.         struct v4l2_vbi_format        vbi; /* V4L2_BUF_TYPE_VBI_CAPTURE */
  1423.         struct v4l2_sliced_vbi_format    sliced; /* V4L2_BUF_TYPE_SLICED_VBI_CAPTURE */
  1424.         __u8    raw_data[200]; /* user-defined */
  1425.     } fmt;
  1426. };
  1427. 对于视频捕获(和输出)设备,联合体中pix成员是我们关注的重点。这是我们在上面见过的v4l2_pix_format结构体,驱动应该用现在的硬件设置填充那个结构体并且返回。
  1428. 来看看vivi.c中对于这个回调函数的实现:
  1429. static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
  1430.                     struct v4l2_format *f)
  1431. {
  1432.     struct vivi_dev *dev = video_drvdata(file);

  1433.     f->fmt.pix.width = dev->width;
  1434.     f->fmt.pix.height = dev->height;
  1435.     f->fmt.pix.field = dev->field;
  1436.     f->fmt.pix.pixelformat = dev->fmt->fourcc;
  1437.     f->fmt.pix.bytesperline = (f->fmt.pix.width * dev->fmt->depth) >> 3;
  1438.     f->fmt.pix.sizeimage = f->fmt.pix.height * f->fmt.pix.bytesperline;
  1439.     if (dev->fmt->fourcc == V4L2_PIX_FMT_YUYV ||
  1440.      dev->fmt->fourcc == V4L2_PIX_FMT_UYVY)
  1441.         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
  1442.     else
  1443.         f->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
  1444.     return 0;
  1445. }

  1446. 8.4.3多数应用都想最终对硬件进行配置以使其为应用提供一种合适的格式。改变视频格式有两个函数接口,
  1447. 一个是 VIDIOC_TRY_FMT 调用,它在 V4L2 驱动中转化为下面的回调函数:
  1448. int (*vidioc_try_fmt_vid_cap) (struct file *file, void *fh, struct v4l2_format *f);
  1449. 要处理这个调用,驱动会查看请求的视频格式,然后断定硬件是否支持这个格式。如果应用请求的格 式是不被支持的,就会返回-EINVAL。例如,描述了一个不支持格的 fourcc 编码或者请求了一个隔行扫描 的视频,而设备只支持逐行扫描的就会失败。在另一方面,驱动可以调整 size 字段,以与硬件支持的图像 大小相适应。通常的做法是尽量将大小调小。所以一个只能处理 VGA 分辨率的设备驱动会根据情况相应地 调整 width 和 height 参数而成功返回。v4l2_format结构体会在调用后复制给用户空间,驱动应该更新这个 结构体以反映改变的参数,这样应用才可以知道它真正得到是什么。
  1450. VIDIOC_TRY_FMT这个处理对于驱动来说是可选的,但不推荐忽略这个功能。如果提供了的话,这 个函数可以在任何时候调用,甚至时设备正在工作的时候。它不可以对实质上的硬件参数做任何改变,只 是让应用知道都可以做什么的一种方式。

  1451. 如果应用要真正的改变硬件的格式,它使用 VIDIOC_S_FMT 调用,它以下面的方式到达驱动:
  1452. int (*vidioc_s_fmt_vid_cap) (struct file *file, void *fh, struct v4l2_format *f);
  1453. 与 VIDIOC_TRY_FMT 不同,这个回调是不能随时调用的。如果硬件正在工作或己经开辟了流缓冲区 (后面的文章将介绍),改变格式会带来无尽的麻烦。想想会发生什么?比如,一个新的格式比现在使的缓冲 区大的时候。所以驱动总是要保证硬件是空闲的,否则就对请求返回失败(-EBUSY)
  1454. 格式的改变应该是原子的——它要么改变所有的参数以实现请求,要么一个也不改变。同样,驱动在 必要时是可以改变图像大小的。
  1455. 还是来看看vivi.c中对于这两个回调函数的实现:
  1456. static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
  1457.             struct v4l2_format *f)
  1458. {
  1459.     struct vivi_dev *dev = video_drvdata(file);
  1460.     struct vivi_fmt *fmt;
  1461.     enum v4l2_field field;

  1462.     fmt = get_format(f);
  1463.     if (!fmt) {
  1464.         dprintk(dev, 1, "Fourcc format (0x%08x) invalid. ",
  1465.             f->fmt.pix.pixelformat);
  1466.         return -EINVAL;
  1467.     }

  1468.     field = f->fmt.pix.field;

  1469.     if (field == V4L2_FIELD_ANY) {
  1470.         field = V4L2_FIELD_INTERLACED;
  1471.     } else if (V4L2_FIELD_INTERLACED != field) {
  1472.         dprintk(dev, 1, "Field type invalid. ");
  1473.         return -EINVAL;
  1474.     }

  1475.     f->fmt.pix.field = field;
  1476.     v4l_bound_align_image(&f->fmt.pix.width, 48, MAX_WIDTH, 2,
  1477.              &f->fmt.pix.height, 32, MAX_HEIGHT, 0, 0);
  1478.     f->fmt.pix.bytesperline =
  1479.         (f->fmt.pix.width * fmt->depth) >> 3;
  1480.     f->fmt.pix.sizeimage =
  1481.         f->fmt.pix.height * f->fmt.pix.bytesperline;
  1482.     if (fmt->fourcc == V4L2_PIX_FMT_YUYV ||
  1483.      fmt->fourcc == V4L2_PIX_FMT_UYVY)
  1484.         f->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
  1485.     else
  1486.         f->fmt.pix.colorspace = V4L2_COLORSPACE_SRGB;
  1487.     return 0;
  1488. }

  1489. static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
  1490.                     struct v4l2_format *f)
  1491. {
  1492.     struct vivi_dev *dev = video_drvdata(file);
  1493.     struct vb2_queue *q = &dev->vb_vidq;

  1494.     int ret = vidioc_try_fmt_vid_cap(file, priv, f);
  1495.     if (ret < 0)
  1496.         return ret;

  1497.     if (vb2_is_streaming(q)) {
  1498.         dprintk(dev, 1, "%s device busy ", __func__);
  1499.         return -EBUSY;
  1500.     }

  1501.     dev->fmt = get_format(f);
  1502.     dev->width = f->fmt.pix.width;
  1503.     dev->height = f->fmt.pix.height;
  1504.     dev->field = f->fmt.pix.field;

  1505.     return 0;
  1506. }

  1507. 8.5 IO访问
  1508. V4L2支持三种不同IO访问方式(内核中还支持了其它的访问方式,暂不讨论):
  1509. (1)read和write,是基本帧IO访问方式,通过read读取每一帧数据,数据需要在内核和用户之间拷贝,这种方式访问速度可能会非常慢;
  1510. (2)内存映射缓冲区(V4L2_MEMORY_MMAP),是在内核空间开辟缓冲区,应用通过mmap()系统调用映射到用户地址空间。这些缓冲区可以是大而连续DMA缓冲区、通过vmalloc()创建的虚拟缓冲区,或者直接在设备的IO内存中开辟的缓冲区(如果硬件支持);
  1511. (3)用户空间缓冲区(V4L2_MEMORY_USERPTR),是用户空间的应用中开辟缓冲区,用户与内核空间之间交换缓冲区指针。很明显,在这种情况下是不需要mmap()调用的,但驱动为有效的支持用户空间缓冲区,其工作将也会更困难。

  1512. read和write方式属于帧IO访问方式,每一帧都要通过IO操作,需要用户和内核之间数据拷贝,而后两种是流IO访问方式,不需要内存拷贝,访问速度比较快。内存映射缓冲区访问方式是比较常用的方式。

  1513. 对于其他两种IO访问方式,我们暂时不探讨,因为写到这,我已经腰酸背痛腿抽筋了!_!

  1514. 8.6 流IO方式
  1515. 关于流IO的方式,内核中有一个更高层次的API,它能够帮助驱动作者完成流驱动。当底层设备可以支持分散/聚集I/O的时候,这一层(称为 video-buf)可以使工作变得容易。关于video-buf API我们将在后面讨论。
  1516. 支持流 I/O 的驱动应通过在 vidioc_querycap()方法中设置 V4L2_CAP_STREAMING 标签通知应用。注意:我们无法描述支持哪种缓冲区,那是后话。

  1517. 8.6.1 v4l2_buffer 结构体
  1518. 当使用流 I/O 时,帧以v4l2_buffer的格式在应用和驱动之间传输。
  1519. 首先大家要知道一个缓冲区可以有三种基本状态:
  1520. (1)在驱动的传入队列中。如果驱动不用它做什么有用事的话,应用就可以把缓冲区放在这个队列里。对于一个视频捕获设备,传入队列中的缓冲区是空的,等待驱动向其中填入视频数据;对于输出设备来讲,这些缓冲区是要设备发送的帧数据。
  1521. (2)在驱动的传出队列中。这些缓冲区已由驱动处理过,正等待应用来认领。对于捕获设备而言,传出缓冲区内是新的帧数据;对输出设备而言,这个缓冲区是空的。
  1522. (3)不在上述两个队列里。在这种状态时,缓冲区由用户空间拥有,驱动无法访问。这是应用可对缓冲区进行操作的唯一时间。我们称其为用户空间状态。
  1523. 将这些状态和他们之间传输的操作放在一起,如下图所示:


  1524. 其实缓冲区的三种状态是以驱动为中心的,可以理解为传入队列为要给驱动处理的缓冲区,传出队列为驱动处理完毕的缓冲区,而第三种状态是脱离驱动控制的缓冲区。
  1525. 他们操作的缓冲区核心就是这个v4l2_buffer结构体,它在videodev2.h中定义:
  1526. struct v4l2_buffer {
  1527.     __u32            index;
  1528.     enum v4l2_buf_type type;
  1529.     __u32            bytesused;
  1530.     __u32            flags;
  1531.     enum v4l2_field        field;
  1532.     struct timeval        timestamp;
  1533.     struct v4l2_timecode    timecode;
  1534.     __u32            sequence;

  1535.     /* memory location */
  1536.     enum v4l2_memory memory;
  1537.     union {
  1538.         __u32 offset;
  1539.         unsigned long userptr;
  1540.         struct v4l2_plane *planes;
  1541.     } m;
  1542.     __u32            length;
  1543.     __u32            input;
  1544.     __u32            reserved;
  1545. };
  1546. index:是鉴别缓冲区的序号,它只在内存映射缓冲区中使用。与其它可以在V4L2接口中枚举的对象一样,内存映射缓冲区的index 从0开始,依次递增。
  1547. type:描述的是缓冲区类型,通常是V4L2_BUF_TYPE_VIDEO_CAPTURE 或V4L2_BUF_TYPE_VIDEO_OUTPUT。它是一个枚举值,具体可以自己查看。
  1548. 缓冲区的大小由length给定,单位为byte。缓冲区中的图像数据大小可以在 bytesused 成员中找到。显 然,bytesused<=length。对于捕获设备而言,驱动会设置 bytesused; 对输出设备而言,应用必须设置这个成员。
  1549. flags:代表缓冲区的状态,如下所示:
  1550. /* Flags for 'flags' field */
  1551. #define V4L2_BUF_FLAG_MAPPED    0x0001 /* 缓冲区己映射到用户空间。它只应用于内存映射缓冲区 */
  1552. #define V4L2_BUF_FLAG_QUEUED    0x0002    /* 缓冲区在驱动的传入队列。 */
  1553. #define V4L2_BUF_FLAG_DONE    0x0004    /* 缓冲区在驱动的传出队列 */
  1554. #define V4L2_BUF_FLAG_KEYFRAME    0x0008    /* 缓冲区包含一个关键帧,它在压缩流中是                                    * 非常有用的。 */
  1555. #define V4L2_BUF_FLAG_PFRAME    0x0010    /* 应用于压缩流中,代表的是预测帧 */
  1556. #define V4L2_BUF_FLAG_BFRAME    0x0020    /* 应用于压缩流中,代表的是差分帧 */

  1557. /* Buffer is ready, but the data contained within is corrupted. */
  1558. #define V4L2_BUF_FLAG_ERROR    0x0040
  1559. #define V4L2_BUF_FLAG_TIMECODE    0x0100    /* timecode 字段有效 */
  1560. #define V4L2_BUF_FLAG_INPUT 0x0200 /* input 字段有效 */
  1561. #define V4L2_BUF_FLAG_PREPARED    0x0400    /* 缓冲区准备好进入队列 */

  1562. field :描述存在缓冲区中的图像属于哪一个域,它也是一个枚举值。
  1563. timestamp(时间戳):对于输入设备来说,代表帧捕获的时间。对输出设备来说,在没有到达时间戳所代表的时间前,驱动不可以把帧发送出去,时间戳为0代表越快越好。驱动会把时间戳设为帧的第一个字节传送到设备的时间,或者说是驱动所能达到的最接近的时间。
  1564. timecode:可以用来存放时间编码,对于视频编辑类应用是非常有用的。
  1565. sequence:驱动对传过设备的帧维护了一个递增的计数; 每一帧传送时,它都会在sequence成员中存入当前序号。 对于输入设备来讲,应用可以观察这一成员来检测帧。
  1566. memory:表示缓冲是内存映射缓冲区还是用户空间缓冲区。如果是 V4L2_MEMORY_MMAP方式,m.offset是内核空间图像数据存放的开始地址,会传递给mmap函数作为一个偏移, 通过mmap映射返回一个缓冲区指针p,p+byteused是图像数据在进程的虚拟地址空间所占区域;如果是用户指针缓冲区的方式,可以获取的图像数据开始地址的指针m.userptr,userptr是一个用户空间的指针,userptr+byteused便是所占的虚拟地址空间,应用可以直接访问。
  1567. input:可以用来快速切换捕获设备的输入——如果设备支持帧间的快速切换。

  1568. /* 以下几个函数是参考Tekkaman Ninja 整理的V4L2 驱动编写指南写的,在实际中对于这几个宏的ioctl回调函数已经转移到videobuf2-core.c里面,通过调用vb2_xxx函数来实现了,但是它对于缓冲区的操作过程还是非常重要的,同时希望能够了解更多的底层知识,为后面写videobuf2做准备。 */

  1569. 8.6.2 申请缓冲区
  1570. 当流应用已经完成了基本设置,它将转去执行组织I/O缓冲区的任务。第一步就是使用 VIDIOC_REQBUFS ioctl()来建立一组缓冲区,它由V4L2转换成对驱动vidioc_reqbufs()方法的调用。
  1571. int (*vidioc_reqbufs) (struct file *file, void *priv, struct v4l2_requestbuffers *buf);
  1572. 其中v4l2_requestbuffers结构体在videodev2.h中定义,如下所示:
  1573. struct v4l2_requestbuffers {
  1574.     __u32            count;
  1575.     enum v4l2_buf_type type;
  1576.     enum v4l2_memory memory;
  1577.     __u32            reserved[2];
  1578. };
  1579. count:是期望使用的缓冲区数目。
  1580. type:它是一个枚举值,部分如下所示:
  1581. enum v4l2_buf_type {
  1582.     V4L2_BUF_TYPE_VIDEO_CAPTURE = 1,
  1583.     V4L2_BUF_TYPE_VIDEO_OUTPUT = 2,
  1584.     V4L2_BUF_TYPE_VIDEO_OVERLAY = 3,
  1585.     V4L2_BUF_TYPE_VBI_CAPTURE = 4,
  1586.     ...........
  1587. };
  1588. memory:它也是一个枚举值,如下所示:
  1589. enum v4l2_memory {
  1590.     V4L2_MEMORY_MMAP = 1,
  1591.     V4L2_MEMORY_USERPTR = 2,
  1592.     V4L2_MEMORY_OVERLAY = 3,
  1593. };
  1594. 如果应用想要使用内存映射缓冲区,它会把memory字段置为V4L2_MEMORY_MMAP,count置为期望使用的缓冲区数。如果驱动不支持内存映射,它应返回-EINVAL。否则它将在内部开辟请求的缓冲区并返回0。返回后,应用就会认为缓冲区是存在的,所以任何可能失败的操作都应在这个阶段处理 (比如说内存申请)

  1595. 注意:驱动并不一定要开辟与请求数目一样的缓冲区。在多数情况下,只有最小缓冲区数是有意义的。
  1596. 如果应用请求的比这个最小值小,它可能得到比实际申请的多一些。
  1597. 应用可以通过设置 count 字段为 0 的方式来释放掉所有已存在的缓冲区。在这种情况下, 驱动必须在释放缓冲前停止所有的 DMA 操作,否则会发生非常严重问题。如果缓冲区已映射到用户空间,则释放缓冲区是不可能的。
  1598. 相反,如果使用用户空间缓冲区,则有意义的字段只有缓冲区的type以及仅 V4L2_MEMORY_USERPTR 这个可用的 memory 字段。应用无须指定它想用的缓冲区的数目。因为内存是在用户空间开辟的,驱动无须操心。如果驱动支持用户空间缓冲区,它只须注意应用会使用这一特性, 返回0就可以了,否则返回-EINVAL。

  1599. VIDIOC_REQBUFS 命令是应用得知驱动所支持的流 I/O 缓冲区类型的唯一方法。

  1600. 8.6.3 将缓冲区映射到用户空间
  1601. 如果使用用户空间缓存,在应用向传入队列放置缓冲区之前,驱动看不到任何缓冲区的相关调用。内存映射缓冲区需要更多的设置。应用通常会查看每一个开辟的缓冲区,并将其映射到自己的地址空间。第一步是 VIDIOC_QUERYBUF命令,它将转换成驱动中的vidioc_querybuf()方法:
  1602. int (*vidioc_querybuf)(struct file *file, void *priv, struct v4l2_buffer *buf);

  1603. 进入此方法时, buf字段中要设置的字段有type(在缓冲区开辟时, 它将被检查是否与给定的类型相符) 和 index,它们可以确定一个特定的缓冲区。驱动要保证index有意义,并添充 buf中的其余字段。通常来说,驱动内部存储着一个v4l2_buffer 结构体数组, 所以vidioc_querybuf()方法的核心只是对这个v4l2_buffer结构体进行赋值。

  1604. 应用访问内存映射缓冲区的唯一方法就是将其映射到它们自己的地址空间,所以 vidioc_querybuf()调用后面通常会跟着一个驱动的 mmap()方法---要记住,这个方法指针是存储在相关设备的video_device 结构体中fops 字段中的。设备如何处理 mmap()依赖于内核中缓冲区是如何设置的。
  1605. 当用户空间映射缓冲区时, 驱动应在相关的 v4l2_buffer 结构体中调置 V4L2_BUF_FLAG_MAPPED 标 签。它也必须在 open()和 close()中设定 VMA 操作,这样它才能跟踪映射了缓冲区的进程数。只要缓冲区在任何地方被映射了,它就不能在内核中释放。如果一个或多个缓冲区的映射计数为0,驱动就应该停止正 在进行的 I/O 操作,因为没有进程需要它。

  1606. 8.6.4 流IO
  1607. 到现为止,我们己经看了很多设置,却没有传输过一帧的数据,我们离这步己经很近了,但在此之前还有一个步骤要做。当应用通过 VIDIOC_REQBUFS 获得了缓冲区后,那个缓冲区处于用户空间状态。如果他们是用户空间缓冲区,他们甚至还不存在。在应用开始流I/O之前,它必须至少将一个缓冲区放到驱动传入队列中。对于输出设备,那些缓冲区当然还要先填完有效的视频帧数据。
  1608. 要把一个缓冲区放进传入队列,应用首先要发出一个VIDIOC_QBUF ioctl()调用, V4L2会将其映射为对驱动vidioc_qbuf()方法的调用。
  1609. int (*vidioc_qbuf) (struct file *file, void *priv, struct v4l2_buffer *buf);

  1610. 对于内存映射缓冲而言,还是只有 buf 的 type 和 index 成员有效。驱动只能进行一些显式的检查(type 和index 是否有效、缓冲区是否在驱动队列中、缓冲区已映射等),把缓冲区放进传入队列里(设置
  1611. V4L2_BUF_FLAG_QUEUED标签),并返回。

  1612. 一旦流 I/O 开始,驱动就要从它的传入队列里获取缓冲区,让设备更快地实现转送请求,然后把缓冲区移动到传出队列。转输开始时,缓冲区标签也要相应调整。像序号和时间戳这样的字段必需在这个时候填充。最后,应用会在传出队列中认领缓冲区,让它变回为用户态。这是 VIDIOC_DQBUF 的工作,它最终变为如下调用:
  1613. int (*vidioc_dqbuf) (struct file *file, void *priv, struct v4l2_buffer *buf);

  1614. 这里,驱动会从传出队列中移除第一个缓冲区,把相关的信息存入 buf。通常,传出队列是空的,这个调用会处于阻塞状态直到有缓冲区可用。然而V4L2是用来处理非阻塞I/O的,所以如果视频设备是以O_NONBLOCK 方式打开的,在队列为空的情况下驱动就该返回-EAGAIN。当然,这个要求也暗示驱动必须为流I/O支持poll()

  1615. 8.6.5 打开/关闭流
  1616. 剩下最后的一个步骤实际上就是告诉设备开始流 I/O 操作。 完成这个任务的 Video4Linux2 驱动方法是:
  1617. int (*vidioc_streamon) (struct file *file, void *fh, enum v4l2_buf_type i);
  1618. int (*vidioc_streamoff)(struct file *file, void *fh, enum v4l2_buf_type i);
  1619. 对 vidioc_streamon()的调用应该在检查类型有意义之后才让设备开始工作。如果需要的话,驱动可以请求等传入队列中有一定数目的缓冲区后再开始流传输。

  1620. 当应用关闭时,它应发出一个 vidioc_streamoff()调用,此调用要停止设备。驱动还应从传入和传出队列 中移除所有的缓冲区,使它们都处于用户空间状态。当然,驱动必须意识到:应用可能在没有停止流传输的情况下关闭设备。

  1621. (九)控制




  1622. (十)linux内核v4l2框架中videobuf2分析
  1623. 16年1月19日20:44:18

  1624. 1. 首先在vivi.c中,在vivi_init函数的vivi_create_instance中,对于缓冲区队列的操作有以下的代码:
  1625.     struct vb2_queue *q;
  1626.     /* initialize queue */
  1627.     q = &dev->vb_vidq;
  1628.     memset(q, 0, sizeof(dev->vb_vidq));
  1629.     q->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  1630.     q->io_modes = VB2_MMAP | VB2_USERPTR | VB2_READ;
  1631.     q->drv_priv = dev;
  1632.     q->buf_struct_size = sizeof(struct vivi_buffer);
  1633.     q->ops = &vivi_video_qops;
  1634.     q->mem_ops = &vb2_vmalloc_memops;

  1635.     vb2_queue_init(q);

  1636. 它对struct vb2_queue结构体进行了设置,然后调用vb2_queue_init()函数进行初始化,那么就先来分析这个vb2_queue结构体。

  1637. 2.vb2_queue结构体在videobuf2-core.h中定义,如下所示(对于结构体的注释,我也放在下面了):
  1638. /**
  1639.  * struct vb2_queue - a videobuf queue
  1640.  *
  1641.  * @type:    queue type (see V4L2_BUF_TYPE_* in linux/videodev2.h
  1642.  * @io_modes:    supported io methods (see vb2_io_modes enum)
  1643.  * @io_flags:    additional io flags (see vb2_fileio_flags enum)
  1644.  * @ops:    driver-specific callbacks
  1645.  * @mem_ops:    memory allocator specific callbacks
  1646.  * @drv_priv:    driver private data
  1647.  * @buf_struct_size: size of the driver-specific buffer structure;
  1648.  *        "0" indicates the driver doesn't want to use a custom buffer
  1649.  *        structure type, so sizeof(struct vb2_buffer) will is used
  1650.  *
  1651.  * @memory:    current memory type used
  1652.  * @bufs:    videobuf buffer structures
  1653.  * @num_buffers: number of allocated/used buffers
  1654.  * @queued_list: list of buffers currently queued from userspace
  1655.  * @queued_count: number of buffers owned by the driver
  1656.  * @done_list:    list of buffers ready to be dequeued to userspace
  1657.  * @done_lock:    lock to protect done_list list
  1658.  * @done_wq: waitqueue for processes waiting for buffers ready to be dequeued
  1659.  * @alloc_ctx:    memory type/allocator-specific contexts for each plane
  1660.  * @streaming:    current streaming state
  1661.  * @fileio:    file io emulator internal data, used only if emulator is active
  1662.  */
  1663. struct vb2_queue {
  1664.     enum v4l2_buf_type        type;
  1665.     unsigned int            io_modes;
  1666.     unsigned int            io_flags;
  1667.     const struct vb2_ops        *ops;
  1668.     const struct vb2_mem_ops    *mem_ops;
  1669.     void                *drv_priv;
  1670.     unsigned int            buf_struct_size;
  1671. /* private: internal use only */
  1672.     enum v4l2_memory        memory;
  1673.     struct vb2_buffer        *bufs[VIDEO_MAX_FRAME]; //代表每个buffer (后面分析)
  1674.     unsigned int            num_buffers; //分配的buffer个数
  1675.     struct list_head        queued_list;
  1676.     atomic_t            queued_count;
  1677.     struct list_head        done_list;
  1678.     spinlock_t            done_lock;
  1679.     wait_queue_head_t        done_wq;
  1680.     void                *alloc_ctx[VIDEO_MAX_PLANES];
  1681.     unsigned int            plane_sizes[VIDEO_MAX_PLANES];
  1682.     unsigned int            streaming:1;
  1683.     struct vb2_fileio_data        *fileio;
  1684. };
  1685. type:缓冲区的类型,与v4l2_buf_type这个枚举值相同,为下面其中的一项:
  1686. enum v4l2_buf_type {
  1687.     V4L2_BUF_TYPE_VIDEO_CAPTURE = 1,
  1688.     V4L2_BUF_TYPE_VIDEO_OUTPUT = 2,
  1689.     V4L2_BUF_TYPE_VIDEO_OVERLAY = 3,
  1690.     V4L2_BUF_TYPE_VBI_CAPTURE = 4,
  1691.     V4L2_BUF_TYPE_VBI_OUTPUT = 5,
  1692.     V4L2_BUF_TYPE_SLICED_VBI_CAPTURE = 6,
  1693.     V4L2_BUF_TYPE_SLICED_VBI_OUTPUT = 7,
  1694.     V4L2_BUF_TYPE_VIDEO_OUTPUT_OVERLAY = 8,
  1695.     V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE = 9,
  1696.     V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE = 10,
  1697.     V4L2_BUF_TYPE_PRIVATE = 0x80,
  1698. };
  1699. io_modes:访问IO的方式,与enum vb2_io_modes相同,如下所示:
  1700. **
  1701.  * enum vb2_io_modes - queue access methods
  1702.  * @VB2_MMAP:        driver supports MMAP with streaming API
  1703.  * @VB2_USERPTR:    driver supports USERPTR with streaming API
  1704.  * @VB2_READ:        driver supports read() style access
  1705.  * @VB2_WRITE:        driver supports write() style access
  1706.  */
  1707. enum vb2_io_modes {
  1708.     VB2_MMAP    = (1 << 0),
  1709.     VB2_USERPTR    = (1 << 1),
  1710.     VB2_READ    = (1 << 2),
  1711.     VB2_WRITE    = (1 << 3),
  1712. };
  1713. ops:buffer队列操作函数集合
  1714. mem_ops:buffer memory操作集合
  1715. vb2_queue代表一个videobuffer队列,vb2_buffer是这个队列中的成员,vb2_mem_ops是缓冲内存的操作函数集,vb2_ops用来管理队列。根据vivi.c中的设置,它都对这两个函数集设置了初始值,那么下面我们就来看看这两个函数集。

  1716. 2.1 vb2_mem_ops 包含了内存映射缓冲区、用户空间缓冲区的内存操作方法:
  1717. struct vb2_mem_ops {
  1718.     void        *(*alloc)(void *alloc_ctx, unsigned long size);
  1719.     void        (*put)(void *buf_priv);
  1720.     void        *(*get_userptr)(void *alloc_ctx, unsigned long vaddr,
  1721.                     unsigned long size, int write);
  1722.     void        (*put_userptr)(void *buf_priv);
  1723.     void        *(*vaddr)(void *buf_priv);
  1724.     void        *(*cookie)(void *buf_priv);
  1725.     unsigned int    (*num_users)(void *buf_priv);
  1726.     int        (*mmap)(void *buf_priv, struct vm_area_struct *vma);
  1727. };

  1728. 通过在vivi.c中使用这个结构体,我们发现这几个函数都是直接调用内核中实现好的函数。它提供了三种类型的视频缓存区操作方法:连续的DMA缓冲区、集散的DMA缓冲区以及vmalloc创建的缓冲区,分别由 videobuf2-dma-contig.c、videobuf2-dma-sg.c和videobuf-vmalloc.c文件实现,可以根据实际情况来使用。
  1729. vivi.c中,q->mem_ops = &vb2_vmalloc_memops;它使用vmalloc的方式创建缓冲区,搜索发现vb2_vmalloc_memops在videobuf2-vmalloc.c中定义,如下所示:
  1730. const struct vb2_mem_ops vb2_vmalloc_memops = {
  1731.     .alloc        = vb2_vmalloc_alloc,
  1732.     .put        = vb2_vmalloc_put,
  1733.     .get_userptr    = vb2_vmalloc_get_userptr,
  1734.     .put_userptr    = vb2_vmalloc_put_userptr,
  1735.     .vaddr        = vb2_vmalloc_vaddr,
  1736.     .mmap        = vb2_vmalloc_mmap,
  1737.     .num_users    = vb2_vmalloc_num_users,
  1738. };
  1739. EXPORT_SYMBOL_GPL(vb2_vmalloc_memops);
  1740. 这几个函数暂时先不具体分析他们的代码。

  1741. 2.2 vb2_ops是用来管理buffer队列的函数集合,包括队列和缓冲区初始化:
  1742. struct vb2_ops {
  1743.     int (*queue_setup)(struct vb2_queue *q, const struct v4l2_format *fmt,
  1744.              unsigned int *num_buffers, unsigned int *num_planes,
  1745.              unsigned int sizes[], void *alloc_ctxs[]);
  1746.     void (*wait_prepare)(struct vb2_queue *q);
  1747.     void (*wait_finish)(struct vb2_queue *q);
  1748.     int (*buf_init)(struct vb2_buffer *vb);
  1749.     int (*buf_prepare)(struct vb2_buffer *vb);
  1750.     int (*buf_finish)(struct vb2_buffer *vb);
  1751.     void (*buf_cleanup)(struct vb2_buffer *vb);
  1752.     int (*start_streaming)(struct vb2_queue *q, unsigned int count);
  1753.     int (*stop_streaming)(struct vb2_queue *q);
  1754.     void (*buf_queue)(struct vb2_buffer *vb);
  1755. };
  1756. vivi.c中q->ops = &vivi_video_qops;这几个函数是需要我们自己实现的,如下所示:
  1757. static struct vb2_ops vivi_video_qops = {
  1758.     .queue_setup        = queue_setup, //队列初始化
  1759.     //对buffer的操作
  1760.     .buf_init        = buffer_init,
  1761.     .buf_prepare        = buffer_prepare,
  1762.     .buf_finish        = buffer_finish,
  1763.     .buf_cleanup        = buffer_cleanup,
  1764.     //把vb传递给驱动
  1765.     .buf_queue        = buffer_queue,
  1766.     // 开始/停止视频流
  1767.     .start_streaming    = start_streaming,
  1768.     .stop_streaming        = stop_streaming,
  1769.     //释放和获取设备操作锁
  1770.     .wait_prepare        = vivi_unlock,
  1771.     .wait_finish        = vivi_lock,
  1772. };

  1773. 3. 在vb2_queue中有一个struct vb2_buffer    *bufs[VIDEO_MAX_FRAME];
  1774. 其中这个vb2_buffer是缓存队列的基本单位,内嵌在其中的v4l2_buffer是核心成员。当开始流IO时,帧以v4l2_buffer的格式在应用和驱动之间传输。
  1775. struct vb2_buffer {
  1776.     struct v4l2_buffer    v4l2_buf;
  1777.     struct v4l2_plane    v4l2_planes[VIDEO_MAX_PLANES];
  1778.     struct vb2_queue    *vb2_queue;
  1779.     unsigned int        num_planes;
  1780. /* Private: internal use only */
  1781.     enum vb2_buffer_state    state;
  1782.     struct list_head    queued_entry;
  1783.     struct list_head    done_entry;
  1784.     struct vb2_plane    planes[VIDEO_MAX_PLANES];
  1785. };

  1786. 一个缓冲区有三种状态,我们在上面的V4L2框架分析中:8.6流IO方式一节分析了这三种状态:
  1787. (1)在驱动的传入队列中,驱动程序将会对此队列中的缓冲区进行处理,用户空间通过IOCTL:VIDIOC_QBUF把缓冲区 放入到队列。对于一个视频捕获设备,传入队列中的缓冲区是空的,驱动会往其中填充数据;
  1788. (2)在驱动的传出队列中,这些缓冲区已由驱动处理过,对于一个视频捕获设备,缓存区已经填充了视频数据,正等用 户空间来认领;
  1789. (3)用户空间状态的队列,已经通过IOCTL:VIDIOC_DQBUF传出到用户空间的缓冲区,此时缓冲区由用户空间拥有, 驱动无法访问。
  1790.  
  1791. 当用户空间拿到v4l2_buffer,可以获取到缓冲区的相关信息。byteused是图像数据所占的字节数,如果是V4L2_MEMORY_MMAP方式,m.offset是内核空间图像数据存放的开始地址,会传递给mmap函数作为一个偏移, 通过mmap映射返回一个缓冲区指针p,p+byteused是图像数据在进程的虚拟地址空间所占区域;如果是用户指针缓冲区的方式,可以获取的图像数据开始地址的指针m.userptr,userptr是一个用户空间的指针,userptr+byteused便是所占的虚拟地址空间,应用可以直接访问。

  1792. 4. 下面来结合代码详细分析分析它的流程:
  1793. 4.1 当应用程序调用ioctl:VIDIOC_REQBUFS的时候,应用程序中一般是这样调用的:
  1794. struct v4l2_requestbuffers req;
  1795. req.count = 4;
  1796. req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  1797. req.memory = V4L2_MEMORY_MMAP;
  1798. if (-1 == xioctl (fd, VIDIOC_REQBUFS, &req))
  1799. {
  1800.     ......
  1801. }
  1802. 经过v4l2框架的一系列转换,最终调用到vivi.c驱动中我们自己实现的vidioc_reqbufs函数中:
  1803. static int vidioc_reqbufs(struct file *file, void *priv,
  1804.              struct v4l2_requestbuffers *p)
  1805. {
  1806.     struct vivi_dev *dev = video_drvdata(file);
  1807.     return vb2_reqbufs(&dev->vb_vidq, p);
  1808. }
  1809. 它又调用了vb2_reqbufs这个函数,它就在videobuf2-core.c这个文件中,如下所示:
  1810. /**
  1811.  * vb2_reqbufs() - Initiate streaming
  1812.  * @q:        videobuf2 queue
  1813.  * @req:    struct passed from userspace to vidioc_reqbufs handler in driver
  1814.  *
  1815.  * Should be called from vidioc_reqbufs ioctl handler of a driver.
  1816.  * This function:
  1817.  * 1) verifies streaming parameters passed from the userspace,
  1818.  * 2) sets up the queue,
  1819.  * 3) negotiates number of buffers and planes per buffer with the driver
  1820.  * to be used during streaming,
  1821.  * 4) allocates internal buffer structures (struct vb2_buffer), according to
  1822.  * the agreed parameters,
  1823.  * 5) for MMAP memory type, allocates actual video memory, using the
  1824.  * memory handling/allocation routines provided during queue initialization
  1825.  *
  1826.  * If req->count is 0, all the memory will be freed instead.
  1827.  * If the queue has been allocated previously (by a previous vb2_reqbufs) call
  1828.  * and the queue is not busy, memory will be reallocated.
  1829.  *
  1830.  * The return values from this function are intended to be directly returned
  1831.  * from vidioc_reqbufs handler in driver.
  1832.  */
  1833. int vb2_reqbufs(struct vb2_queue *q, struct v4l2_requestbuffers *req)
  1834. {
  1835.     unsigned int num_buffers, allocated_buffers, num_planes = 0;
  1836.     int ret = 0;

  1837.     if (q->fileio) {
  1838.         dprintk(1, "reqbufs: file io in progress ");
  1839.         return -EBUSY;
  1840.     }
  1841. /* 这个fileio是vb2_queue结构体中的一个成员,它是vb2_fileio_data类型的,它的意思大概是关于读写上下文之间的一个读写锁,应该用于8.5中IO访问中的read,write基本帧IO访问方式,这个我不是太懂,一般情况下为0。*/
  1842.     if (req->memory != V4L2_MEMORY_MMAP
  1843.             && req->memory != V4L2_MEMORY_USERPTR) {
  1844.         dprintk(1, "reqbufs: unsupported memory type ");
  1845.         return -EINVAL;
  1846.     }
  1847. /* 判断req中的memory字段,必须设置了V4L2_MEMORY_MMAP 和V4L2_MEMORY_USERPTR这两个字段,再看之前的应用程序设置中,它没有设置V4L2_MEMORY_USERPTR字段,可能是错误的,我们先分析,等到后面再测试这个应用程序。 */
  1848.     if (req->type != q->type) {
  1849.         dprintk(1, "reqbufs: requested type is incorrect ");
  1850.         return -EINVAL;
  1851.     }
  1852. /* 判断想要申请的v4l2_requestbuffers与vb2_queue中type字段是否相同。不同就返回错误。*/
  1853.     if (q->streaming) {
  1854.         dprintk(1, "reqbufs: streaming active ");
  1855.         return -EBUSY;
  1856.     }
  1857. /* streaming表示当前流状态,为1的话表示streaming active,返回 EBUSY */
  1858.     /*
  1859.      * Make sure all the required memory ops for given memory type
  1860.      * are available.
  1861.      */
  1862.     if (req->memory == V4L2_MEMORY_MMAP && __verify_mmap_ops(q)) {
  1863.         dprintk(1, "reqbufs: MMAP for current setup unsupported ");
  1864.         return -EINVAL;
  1865.     }
  1866. /* 如果v4l2_requestbuffers中memory字段为V4L2_MEMORY_MMAP的话,判断 vb2_queue q队列中io_modes 是否为VB2_MMAP,判断是否提供了vb2_mem_ops操作函数集中的alloc,put,mmap函数,如果这些不符合的话,就返回EINVAL。 __verify_mmap_ops()函数也在videobuf2-core.c文件中提供,如下所示:
  1867. static int __verify_mmap_ops(struct vb2_queue *q)
  1868. {
  1869.     if (!(q->io_modes & VB2_MMAP) || !q->mem_ops->alloc ||
  1870.      !q->mem_ops->put || !q->mem_ops->mmap)
  1871.         return -EINVAL;

  1872.     return 0;
  1873. }
  1874. */
  1875.     if (req->memory == V4L2_MEMORY_USERPTR && __verify_userptr_ops(q)) {
  1876.         dprintk(1, "reqbufs: USERPTR for current setup unsupported ");
  1877.         return -EINVAL;
  1878.     }
  1879. /* 与上面的类似,__verify_userptr_ops(q)函数如下所示:
  1880. static int __verify_userptr_ops(struct vb2_queue *q)
  1881. {
  1882.     if (!(q->io_modes & VB2_USERPTR) || !q->mem_ops->get_userptr ||
  1883.      !q->mem_ops->put_userptr)
  1884.         return -EINVAL;

  1885.     return 0;
  1886. }
  1887.  */
  1888.     if (req->count == 0 || q->num_buffers != 0 || q->memory != req->memory) {
  1889.         /*
  1890.          * We already have buffers allocated, so first check if they
  1891.          * are not in use and can be freed.
  1892.          */
  1893.         if (q->memory == V4L2_MEMORY_MMAP && __buffers_in_use(q)) {
  1894.             dprintk(1, "reqbufs: memory in use, cannot free ");
  1895.             return -EBUSY;
  1896.         }
  1897.  
  1898.         __vb2_queue_free(q, q->num_buffers);

  1899.         /*
  1900.          * In case of REQBUFS(0) return immediately without calling
  1901.          * driver's queue_setup() callback and allocating resources.
  1902.          */
  1903.         if (req->count == 0)
  1904.             return 0;
  1905.     }
  1906. /* 如果申请的v4l2_requestbuffers中count字段为0的话,就释放掉所有已经申请的内存,因为是允许应用程序这样使用ioctl的。如果 q->num_buffers != 0的话,同样释放掉已经申请的内存。因为,应用程序想要使用缓冲区的话,调用的第一个ioctl就是这个VIDIOC_REQBUFS,在它之前是没有申请内存的。然后调用__vb2_queue_free释放掉缓冲区。这个函数暂时先不具体分析代码。
  1907. 如果 req->count == 0的话,意思是应用程序调用的VIDIOC_REQBUFS(0),这个函数就可以直接在这返回了。 */
  1908.     /*
  1909.      * Make sure the requested values and current defaults are sane.
  1910.      */
  1911.     num_buffers = min_t(unsigned int, req->count, VIDEO_MAX_FRAME);
  1912.     memset(q->plane_sizes, 0, sizeof(q->plane_sizes));
  1913.     memset(q->alloc_ctx, 0, sizeof(q->alloc_ctx));
  1914.     q->memory = req->memory;
  1915. /* 经过上面的判断语句以后,开始申请缓冲区的操作。首先将num_buffers设置为 req->count和 VIDEO_MAX_FRAME中较小的一个,然后将 q->plane_sizes和 q->alloc_ctx清零,将 q->memory和 req->memory设置成一致的形式。 */
  1916.     /*
  1917.      * Ask the driver how many buffers and planes per buffer it requires.
  1918.      * Driver also sets the size and allocator context for each plane.
  1919.      */
  1920.     ret = call_qop(q, queue_setup, q, NULL, &num_buffers, &num_planes,
  1921.          q->plane_sizes, q->alloc_ctx);
  1922.     if (ret)
  1923.         return ret;
  1924. /* 看注释应该可以明白,问问驱动一共需要申请几个buffers,并且每一个buffer的位面是多少。于是乎,就调用call_qop去问了,至于这个call_qop是怎么回事,其实在上面的几个函数里面有调用,可是我们没有分析,现在在这分析一下:
  1925. #define call_qop(q, op, args...) (((q)->ops->op) ? ((q)->ops->op(args)) : 0)
  1926. 看这个宏定义,意思就是调用vb2_queue->vb2_ops->queue_setup函数,这个函数就是需要驱动实现的一个函数。在vivi.c中是这样的:
  1927. static int queue_setup(struct vb2_queue *vq, const struct v4l2_format *fmt,
  1928.                 unsigned int *nbuffers, unsigned int *nplanes,
  1929.                 unsigned int sizes[], void *alloc_ctxs[])
  1930. {
  1931.     struct vivi_dev *dev = vb2_get_drv_priv(vq);
  1932.     unsigned long size;

  1933.     size = dev->width * dev->height * 2;

  1934.     if (0 == *nbuffers)
  1935.         *nbuffers = 32;

  1936.     while (size * *nbuffers > vid_limit * 1024 * 1024)
  1937.         (*nbuffers)--;
  1938.  
  1939.     *nplanes = 1;

  1940.     sizes[0] = size;

  1941.     /*
  1942.      * videobuf2-vmalloc allocator is context-less so no need to set
  1943.      * alloc_ctxs array.
  1944.      */

  1945.     dprintk(dev, 1, "%s, count=%d, size=%ld ", __func__,
  1946.         *nbuffers, size);

  1947.     return 0;
  1948. }
  1949. queue_setup 函数的目的是根据vb2_queue 中的 alloc_ctx和plane_sizes来填充 num_buffers和 num_planes,这两个变量以供后面使用。在来看vb2_queue结构体中这三个数组变量:
  1950. struct vb2_buffer        *bufs[VIDEO_MAX_FRAME];
  1951. void                *alloc_ctx[VIDEO_MAX_PLANES];
  1952. unsigned int        plane_sizes[VIDEO_MAX_PLANES];
  1953. bufs数组中每一项对应一个申请的buffer, plane_sizes数组中每一项代表相应buffer的位面大小, alloc_ctx数组的每一项代表相应buffer位面大小的memory type/allocator-specific。这三个数组中的每一项是一一对应关系。
  1954.  */
  1955.     /* Finally, allocate buffers and video memory */
  1956.     ret = __vb2_queue_alloc(q, req->memory, num_buffers, num_planes);
  1957.     if (ret == 0) {
  1958.         dprintk(1, "Memory allocation failed ");
  1959.         return -ENOMEM;
  1960.     }
  1961. /* 最后,调用__vb2_queue_alloc函数来分配缓冲区和内存,这个函数返回值是成功分配的buffer个数。__vb2_queue_alloc函数如下所示:
  1962. static int __vb2_queue_alloc(struct vb2_queue *q, enum v4l2_memory memory,
  1963.              unsigned int num_buffers, unsigned int num_planes)
  1964. {
  1965.     unsigned int buffer;
  1966.     struct vb2_buffer *vb;
  1967.     int ret;

  1968.     for (buffer = 0; buffer < num_buffers; ++buffer) {
  1969.         /* Allocate videobuf buffer structures */
  1970.         vb = kzalloc(q->buf_struct_size, GFP_KERNEL);
  1971.         if (!vb) {
  1972.             dprintk(1, "Memory alloc for buffer struct failed ");
  1973.             break;
  1974.         }
  1975. /* 用kzalloc为结构体分配q->buf_struct_size大小的一块区域。 */

  1976.         /* Length stores number of planes for multiplanar buffers */
  1977.         if (V4L2_TYPE_IS_MULTIPLANAR(q->type))
  1978.             vb->v4l2_buf.length = num_planes;
  1979. /* 判断这个q的type类型是不是V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE和V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE,在这里我们不是。 */
  1980.         vb->state = VB2_BUF_STATE_DEQUEUED;
  1981.         vb->vb2_queue = q;
  1982.         vb->num_planes = num_planes;
  1983.         vb->v4l2_buf.index = q->num_buffers + buffer;
  1984.         vb->v4l2_buf.type = q->type;
  1985.         vb->v4l2_buf.memory = memory;

  1986. /* 设置vb2_buffer的一些属性,在前面说了,vb2_buffer是帧传输的单元,首先设置它的state状态,这个state状态很重要,它有以下几种类型,我连注释也一起复制在这里了,因为注释写的很清楚:
  1987.             /**
  1988.  * enum vb2_buffer_state - current video buffer state
  1989.  * @VB2_BUF_STATE_DEQUEUED:    buffer under userspace control
  1990.  * @VB2_BUF_STATE_PREPARED:    buffer prepared in videobuf and by the driver
  1991.  * @VB2_BUF_STATE_QUEUED:    buffer queued in videobuf, but not in driver
  1992.  * @VB2_BUF_STATE_ACTIVE:    buffer queued in driver and possibly used
  1993.  *                in a hardware operation
  1994.  * @VB2_BUF_STATE_DONE:    buffer returned from driver to                         videobuf, but not yet dequeued to userspace
  1995.  * @VB2_BUF_STATE_ERROR:    same as above, but the operation on the buffer
  1996.  *                has ended with an error, which will be reported
  1997.  *                to the userspace when it is dequeued
  1998.  */
  1999. enum vb2_buffer_state {
  2000.     VB2_BUF_STATE_DEQUEUED,
  2001.     VB2_BUF_STATE_PREPARED,
  2002.     VB2_BUF_STATE_QUEUED,
  2003.     VB2_BUF_STATE_ACTIVE,
  2004.     VB2_BUF_STATE_DONE,
  2005.     VB2_BUF_STATE_ERROR,
  2006. };
  2007. 可以根据缓冲区的三种状态来思考这几种状态,现在首先是reqbuf,现在缓冲区肯定是在用户空间,所以它的状态为 VB2_BUF_STATE_DEQUEUED,然后设置vb2_buffer的父队列为q,设置 num_planes,然后设置v4l2_buffer里面的index,type和memeory。
  2008. */

  2009.         /* Allocate video buffer memory for the MMAP type */
  2010.         if (memory == V4L2_MEMORY_MMAP) {
  2011.             ret = __vb2_buf_mem_alloc(vb);
  2012.             if (ret) {
  2013.                 dprintk(1, "Failed allocating memory for "
  2014.                         "buffer %d ", buffer);
  2015.                 kfree(vb);
  2016.                 break;
  2017.             }
  2018. /* 调用__vb2_buf_mem_alloc函数,为video buffer分配空间。__vb2_buf_mem_alloc函数里面又调用了
  2019. call_memop(q, alloc, q->alloc_ctx[plane], q->plane_sizes[plane]);
  2020. 来分配空间,但是为了文章的可读性,暂时先不分析。
  2021. */
  2022.             /*
  2023.              * Call the driver-provided buffer initialization
  2024.              * callback, if given. An error in initialization
  2025.              * results in queue setup failure.
  2026.              */
  2027.             ret = call_qop(q, buf_init, vb);
  2028.             if (ret) {
  2029.                 dprintk(1, "Buffer %d %p initialization"
  2030.                     " failed ", buffer, vb);
  2031.                 __vb2_buf_mem_free(vb);
  2032.                 kfree(vb);
  2033.                 break;
  2034.             }
  2035.         }
  2036. /* 调用 vb2_queue->ops->buf_init函数,即调用到vivi.c中的 buffer_init函数。*/
  2037.         q->bufs[q->num_buffers + buffer] = vb;
  2038.     }

  2039.     __setup_offsets(q, buffer);

  2040.     dprintk(1, "Allocated %d buffers, %d plane(s) each ",
  2041.             buffer, num_planes);
  2042.  
  2043.     return buffer;
  2044. }
  2045.  */

  2046.     allocated_buffers = ret;
  2047. /* allocated_buffers表示分配成功的缓冲区个数。 */
  2048.     /*
  2049.      * Check if driver can handle the allocated number of buffers.
  2050.      */
  2051.     if (allocated_buffers < num_buffers) {
  2052.         num_buffers = allocated_buffers;
  2053. /* 想要申请num_buffers个缓冲区,但是不一定分配那么多,成功的个数为allocated_buffers。 */

  2054.         ret = call_qop(q, queue_setup, q, NULL, &num_buffers,
  2055.              &num_planes, q->plane_sizes, q->alloc_ctx);
  2056. /* 再次调用 vb2_queue->ops->queue_setup函数 */
  2057.         if (!ret && allocated_buffers < num_buffers)
  2058.             ret = -ENOMEM;

  2059.         /*
  2060.          * Either the driver has accepted a smaller number of buffers,
  2061.          * or .queue_setup() returned an error
  2062.          */
  2063.     }

  2064.     q->num_buffers = allocated_buffers;
  2065. /* 根据成功分配的buffer个数来修改 vb2_queue里面保存的buffer个数。 */
  2066.     if (ret < 0) {
  2067.         __vb2_queue_free(q, allocated_buffers);
  2068.         return ret;
  2069.     }

  2070.     /*
  2071.      * Return the number of successfully allocated buffers
  2072.      * to the userspace.
  2073.      */
  2074.     req->count = allocated_buffers;

  2075.     return 0;
  2076. }
  2077. EXPORT_SYMBOL_GPL(vb2_reqbufs);


  2078. 4.2 当应用程序调用ioctl:VIDIOC_QUERYBUFS的时候,应用程序中一般是这样调用的:
  2079. for (n_buffers = 0; n_buffers < req.count; ++n_buffers) {
  2080.     struct v4l2_buffer buf;
  2081.     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  2082.     buf.memory = V4L2_MEMORY_MMAP;
  2083.     buf.index = n_buffers;
  2084.     if (-1 == xioctl (fd, VIDIOC_QUERYBUF, &buf))
  2085.         errno_exit ("VIDIOC_QUERYBUF");
  2086.     buffers[n_buffers].length = buf.length;
  2087.     buffers[n_buffers].start = mmap (NULL,buf.length,PROT_READ | PROT_WRITE     (没有分析这个mmap函数,以后补上)    ,MAP_SHARED,fd, buf.m.offset);
  2088. }

  2089. 经过v4l2框架的一系列转换,最终调用到vivi.c驱动中我们自己实现的vidioc_querybuf函数中:
  2090. static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
  2091. {
  2092.     struct vivi_dev *dev = video_drvdata(file);
  2093.     return vb2_querybuf(&dev->vb_vidq, p);
  2094. }
  2095. 它又调用了vb2_querybuf这个函数,它就在videobuf2-core.c这个文件中,如下所示:
  2096. /**
  2097.  * vb2_querybuf() - query video buffer information
  2098.  * @q:        videobuf queue
  2099.  * @b:        buffer struct passed from userspace to vidioc_querybuf handler
  2100.  *            in driver
  2101.  *
  2102.  * Should be called from vidioc_querybuf ioctl handler in driver.
  2103.  * This function will verify the passed v4l2_buffer structure and fill the
  2104.  * relevant information for the userspace.
  2105.  *
  2106.  * The return values from this function are intended to be directly returned
  2107.  * from vidioc_querybuf handler in driver.
  2108.  */
  2109. int vb2_querybuf(struct vb2_queue *q, struct v4l2_buffer *b)
  2110. {
  2111.     struct vb2_buffer *vb;

  2112.     if (b->type != q->type) {
  2113.         dprintk(1, "querybuf: wrong buffer type ");
  2114.         return -EINVAL;
  2115.     }

  2116.     if (b->index >= q->num_buffers) {
  2117.         dprintk(1, "querybuf: buffer index out of range ");
  2118.         return -EINVAL;
  2119.     }
  2120.     vb = q->bufs[b->index];

  2121.     return __fill_v4l2_buffer(vb, b);
  2122. }
  2123. EXPORT_SYMBOL(vb2_querybuf);

  2124. 这个函数先判断一些条件,之后将q->bufs[b->index]赋给 vb2_buffer *vb,此时vb的值是队列q中bufs中的某一项(具体哪一项,看应用程序的循环走到哪一步了),之后调用__fill_v4l2_buffer函数,将bufs里面的这一项的内容拷贝到v4l2_buffer b中,这个__fill_v4l2_buffer()函数就是讲怎么拷贝的,它在videobuf2-core.c中定义:
  2125. /**
  2126.  * __fill_v4l2_buffer() - fill in a struct v4l2_buffer with information to be
  2127.  * returned to userspace
  2128.  */
  2129. static int __fill_v4l2_buffer(struct vb2_buffer *vb, struct v4l2_buffer *b)
  2130. {
  2131.     struct vb2_queue *q = vb->vb2_queue;
  2132.     int ret;
  2133. /* 从 vb2_buffer vb里面获取它的父队列。 */
  2134.     /* Copy back data such as timestamp, flags, input, etc. */
  2135.     memcpy(b, &vb->v4l2_buf, offsetof(struct v4l2_buffer, m));
  2136.     b->input = vb->v4l2_buf.input;
  2137.     b->reserved = vb->v4l2_buf.reserved;
  2138. /* 设置 v4l2_buffer b中的timestamp, flags, input,reserved等字段 */
  2139.     if (V4L2_TYPE_IS_MULTIPLANAR(q->type)) {
  2140.         ret = __verify_planes_array(vb, b);
  2141.         if (ret)
  2142.             return ret;

  2143.         /*
  2144.          * Fill in plane-related data if userspace provided an array
  2145.          * for it. The memory and size is verified above.
  2146.          */
  2147.         memcpy(b->m.planes, vb->v4l2_planes,
  2148.             b->length * sizeof(struct v4l2_plane));
  2149.     } else {
  2150.         /*
  2151.          * We use length and offset in v4l2_planes array even for
  2152.          * single-planar buffers, but userspace does not.
  2153.          */
  2154.         b->length = vb->v4l2_planes[0].length;
  2155.         b->bytesused = vb->v4l2_planes[0].bytesused;
  2156.         if (q->memory == V4L2_MEMORY_MMAP)
  2157.             b->m.offset = vb->v4l2_planes[0].m.mem_offset;
  2158.         else if (q->memory == V4L2_MEMORY_USERPTR)
  2159.             b->m.userptr = vb->v4l2_planes[0].m.userptr;
  2160.     /* 设置v4l2_buffer b中的length,bytesused和m.offset/m.userptr字段。 */
  2161.     }

  2162.     /*
  2163.      * Clear any buffer state related flags.
  2164.      */
  2165.     b->flags &= ~V4L2_BUFFER_STATE_FLAGS;
  2166. /* 将v4l2_buffer b中的flags参数全部都清空。 */
  2167.     switch (vb->state) {
  2168.     case VB2_BUF_STATE_QUEUED:
  2169.     case VB2_BUF_STATE_ACTIVE:
  2170.         b->flags |= V4L2_BUF_FLAG_QUEUED;
  2171.         break;
  2172.     case VB2_BUF_STATE_ERROR:
  2173.         b->flags |= V4L2_BUF_FLAG_ERROR;
  2174.         /* fall through */
  2175.     case VB2_BUF_STATE_DONE:
  2176.         b->flags |= V4L2_BUF_FLAG_DONE;
  2177.         break;
  2178.     case VB2_BUF_STATE_PREPARED:
  2179.         b->flags |= V4L2_BUF_FLAG_PREPARED;
  2180.         break;
  2181.     case VB2_BUF_STATE_DEQUEUED:
  2182.         /* nothing */
  2183.         break;
  2184.     }
  2185. /* 根据vb2_buffer vb的flags参数来设置v4l2_buffer b的flags参数。 */

  2186.     if (__buffer_in_use(q, vb))
  2187.         b->flags |= V4L2_BUF_FLAG_MAPPED;

  2188.     return 0;
  2189. }


  2190. 4.3 mmap


  2191. 4.4 当应用程序调用ioctl:VIDIOC_QBUFS的时候,应用程序中一般是这样调用的:
  2192. static void start_capturing (void)
  2193. {
  2194.     unsigned int i;
  2195.     enum v4l2_buf_type type;
  2196.     for (i = 0; i < n_buffers; ++i)
  2197.     {
  2198.         struct v4l2_buffer buf;
  2199.         
  2200.         buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  2201.         buf.memory = V4L2_MEMORY_MMAP;
  2202.         buf.index = i;
  2203.         /* VIDIOC_QBUF把数据从缓存中读取出来*/
  2204.         if (-1 == xioctl (fd, VIDIOC_QBUF, &buf))
  2205.         errno_exit ("VIDIOC_QBUF");
  2206.     }

  2207.     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  2208.     /* VIDIOC_STREAMON开始视频显示函数*/
  2209.     if (-1 == xioctl (fd, VIDIOC_STREAMON, &type))
  2210.     errno_exit ("VIDIOC_STREAMON");
  2211. }

  2212. 经过v4l2框架的一系列转换,最终调用到vivi.c驱动中我们自己实现的vidioc_qbuf函数中:
  2213. static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
  2214. {
  2215.     struct vivi_dev *dev = video_drvdata(file);
  2216.     return vb2_qbuf(&dev->vb_vidq, p);
  2217. }
  2218. 它又调用了vb2_querybuf这个函数,它就在videobuf2-core.c这个文件中,如下所示:
  2219. /**
  2220.  * vb2_qbuf() - Queue a buffer from userspace
  2221.  * @q:        videobuf2 queue
  2222.  * @b:        buffer structure passed from userspace to vidioc_qbuf handler
  2223.  *            in driver
  2224.  *
  2225.  * Should be called from vidioc_qbuf ioctl handler of a driver.
  2226.  * This function:
  2227.  * 1) verifies the passed buffer,
  2228.  * 2) if necessary, calls buf_prepare callback in the driver (if provided), in
  2229.  * which driver-specific buffer initialization can be performed,
  2230.  * 3) if streaming is on, queues the buffer in driver by the means of buf_queue
  2231.  * callback for processing.
  2232.  *
  2233.  * The return values from this function are intended to be directly returned
  2234.  * from vidioc_qbuf handler in driver.
  2235.  */
  2236. int vb2_qbuf(struct vb2_queue *q, struct v4l2_buffer *b)
  2237. {
  2238.     struct rw_semaphore *mmap_sem = NULL;
  2239.     struct vb2_buffer *vb;
  2240.     int ret = 0;

  2241.     if (q->memory == V4L2_MEMORY_USERPTR) {
  2242.         mmap_sem = &current->mm->mmap_sem;
  2243.         call_qop(q, wait_prepare, q);
  2244.         down_read(mmap_sem);
  2245.         call_qop(q, wait_finish, q);
  2246.     }

  2247.     if (q->fileio) {
  2248.         dprintk(1, "qbuf: file io in progress ");
  2249.         ret = -EBUSY;
  2250.         goto unlock;
  2251.     }

  2252.     if (b->type != q->type) {
  2253.         dprintk(1, "qbuf: invalid buffer type ");
  2254.         ret = -EINVAL;
  2255.         goto unlock;
  2256.     }

  2257.     if (b->index >= q->num_buffers) {
  2258.         dprintk(1, "qbuf: buffer index out of range ");
  2259.         ret = -EINVAL;
  2260.         goto unlock;
  2261.     }

  2262.     vb = q->bufs[b->index];
  2263.     if (NULL == vb) {
  2264.         /* Should never happen */
  2265.         dprintk(1, "qbuf: buffer is NULL ");
  2266.         ret = -EINVAL;
  2267.         goto unlock;
  2268.     }
  2269. /* 从vb2_queue q队列的bufs中根据b->index选择一项,赋给vb。 */

  2270.     if (b->memory != q->memory) {
  2271.         dprintk(1, "qbuf: invalid memory type ");
  2272.         ret = -EINVAL;
  2273.         goto unlock;
  2274.     }

  2275.     switch (vb->state) {
  2276.     case VB2_BUF_STATE_DEQUEUED:
  2277.         ret = __buf_prepare(vb, b);
  2278.         if (ret)
  2279.             goto unlock;
  2280.     case VB2_BUF_STATE_PREPARED:
  2281.         break;
  2282.     default:
  2283.         dprintk(1, "qbuf: buffer already in use ");
  2284.         ret = -EINVAL;
  2285.         goto unlock;
  2286.     }
  2287. /* 根据不同的vb->state状态,如果为 VB2_BUF_STATE_DEQUEUED的话,就调用__buf_prepare函数,如果为 VB2_BUF_STATE_PREPARED的话,就直接break,__buf_prepare函数如下所示,他们的主要目的是:到这一步的 vb2_buffer vb该有的属性是VB2_BUF_STATE_PREPARED,如果它仅仅是VB2_BUF_STATE_DEQUEUED的话,就调用__buf_prepare函数来为它添加这一个属性,下面简单看看这个函数是不是这个意思:
  2288. static int __buf_prepare(struct vb2_buffer *vb, const struct v4l2_buffer *b)
  2289. {
  2290.     struct vb2_queue *q = vb->vb2_queue;
  2291.     int ret;

  2292.     switch (q->memory) {
  2293.     case V4L2_MEMORY_MMAP:
  2294.         ret = __qbuf_mmap(vb, b);
  2295.         break;
  2296.     case V4L2_MEMORY_USERPTR:
  2297.         ret = __qbuf_userptr(vb, b);
  2298.         break;
  2299.     default:
  2300.         WARN(1, "Invalid queue type ");
  2301.         ret = -EINVAL;
  2302.     }

  2303.     if (!ret)
  2304.         ret = call_qop(q, buf_prepare, vb);
  2305.     if (ret)
  2306.         dprintk(1, "qbuf: buffer preparation failed: %d ", ret);
  2307.     else
  2308.         vb->state = VB2_BUF_STATE_PREPARED;

  2309.     return ret;
  2310. }
  2311. 暂时先不分析__qbuf_mmap和__qbuf_userptr函数,看最后 vb->state = VB2_BUF_STATE_PREPARED,就是为vb2_buffer vb添加这个 VB2_BUF_STATE_PREPARED属性。
  2312. */

  2313.     /*
  2314.      * Add to the queued buffers list, a buffer will stay on it until
  2315.      * dequeued in dqbuf.
  2316.      */
  2317.     list_add_tail(&vb->queued_entry, &q->queued_list);
  2318.     vb->state = VB2_BUF_STATE_QUEUED;
  2319. /* 重要的就是这个list_add_tail链表操作了,通过这个操作,将vb2_buffer vb中的queued_entry链表头添加到vb2_queue q的queued_list中去,然后为vb2_buffer vb设置VB2_BUF_STATE_QUEUED的属性。 */

  2320.     /*
  2321.      * If already streaming, give the buffer to driver for processing.
  2322.      * If not, the buffer will be given to driver on next streamon.
  2323.      */
  2324.     if (q->streaming)
  2325.         __enqueue_in_driver(vb);

  2326.     /* Fill buffer information for the userspace */
  2327.     __fill_v4l2_buffer(vb, b);

  2328.     dprintk(1, "qbuf of buffer %d succeeded ", vb->v4l2_buf.index);
  2329. unlock:
  2330.     if (mmap_sem)
  2331.         up_read(mmap_sem);
  2332.     return ret;
  2333. }
  2334. EXPORT_SYMBOL_GPL(vb2_qbuf);

  2335. 4.5 然后就是启动摄像头了,ioctl:VIDIOC_STREAMON ,应用程序在4.4节中包含了这一步,经过v4l2框架的一系列转换,最终调用到vivi.c驱动中我们自己实现的vidioc_streamon 函数中:
  2336. static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
  2337. {
  2338.     struct vivi_dev *dev = video_drvdata(file);
  2339.     return vb2_streamon(&dev->vb_vidq, i);
  2340. }
  2341. 它又调用了vb2_streamon这个函数,它就在videobuf2-core.c这个文件中,如下所示:
  2342. /**
  2343.  * vb2_streamon - start streaming
  2344.  * @q:        videobuf2 queue
  2345.  * @type:    type argument passed from userspace to vidioc_streamon handler
  2346.  *
  2347.  * Should be called from vidioc_streamon handler of a driver.
  2348.  * This function:
  2349.  * 1) verifies current state
  2350.  * 2) passes any previously queued buffers to the driver and starts streaming
  2351.  *
  2352.  * The return values from this function are intended to be directly returned
  2353.  * from vidioc_streamon handler in the driver.
  2354.  */
  2355. int vb2_streamon(struct vb2_queue *q, enum v4l2_buf_type type)
  2356. {
  2357.     struct vb2_buffer *vb;
  2358.     int ret;

  2359.     if (q->fileio) {
  2360.         dprintk(1, "streamon: file io in progress ");
  2361.         return -EBUSY;
  2362.     }

  2363.     if (type != q->type) {
  2364.         dprintk(1, "streamon: invalid stream type ");
  2365.         return -EINVAL;
  2366.     }

  2367.     if (q->streaming) {
  2368.         dprintk(1, "streamon: already streaming ");
  2369.         return -EBUSY;
  2370.     }

  2371.     /*
  2372.      * If any buffers were queued before streamon,
  2373.      * we can now pass them to driver for processing.
  2374.      */
  2375.     list_for_each_entry(vb, &q->queued_list, queued_entry)
  2376.         __enqueue_in_driver(vb);
  2377. /* 如果在启动stream之前,已经有buffer被放入队列的话,就调用__enqueue_in_driver函数来处理它。但是我们第一次执行到这里,就是按照先reqbuf,然后querybuf,qbuf的顺序来执行的,在执行qbuf的过程中,肯定有至少一个vb2_buffer是添加到vb2_queue中queued_list链表中的,所以肯定会执行这个__enqueue_in_driver函数。
  2378. 下面来分析分析这个__enqueue_in_driver函数,它也是在这个videobuf2-core.c文件中:
  2379. static void __enqueue_in_driver(struct vb2_buffer *vb)
  2380. {
  2381.     struct vb2_queue *q = vb->vb2_queue;

  2382.     vb->state = VB2_BUF_STATE_ACTIVE;
  2383.     atomic_inc(&q->queued_count);
  2384.     q->ops->buf_queue(vb);
  2385. }
  2386. 首先设置vb2_buffer的state状态为 VB2_BUF_STATE_ACTIVE,然后原子增加vb2_queue队列q的 queued_count数值,然后调用vb2_queue队列q->ops->buf_queue函数,即vivi.c中的buffer_queue函数:
  2387. static void buffer_queue(struct vb2_buffer *vb)
  2388. {
  2389.     struct vivi_dev *dev = vb2_get_drv_priv(vb->vb2_queue);
  2390.     struct vivi_buffer *buf = container_of(vb, struct vivi_buffer, vb);
  2391.     struct vivi_dmaqueue *vidq = &dev->vidq;
  2392.     unsigned long flags = 0;

  2393.     dprintk(dev, 1, "%s ", __func__);

  2394.     spin_lock_irqsave(&dev->slock, flags);
  2395.     list_add_tail(&buf->list, &vidq->active);
  2396.     spin_unlock_irqrestore(&dev->slock, flags);
  2397. }
  2398. 它主要就是将vb2_buffer vb所在的vivi_buffer buf通过list_add_tail添加到vivi_dmaquue vidq结构体中的active链表中。
  2399. */
  2400.     /*
  2401.      * Let driver notice that streaming state has been enabled.
  2402.      */
  2403.     ret = call_qop(q, start_streaming, q, atomic_read(&q->queued_count));
  2404.     if (ret) {
  2405.         dprintk(1, "streamon: driver refused to start streaming ");
  2406.         __vb2_queue_cancel(q);
  2407.         return ret;
  2408.     }

  2409. /* 调用vb2_queue q中的ops->start_streaming函数,即vivi.c中的start_streaming函数:
  2410. static int start_streaming(struct vb2_queue *vq, unsigned int count)
  2411. {
  2412.     struct vivi_dev *dev = vb2_get_drv_priv(vq);
  2413.     dprintk(dev, 1, "%s ", __func__);
  2414.     return vivi_start_generating(dev);
  2415. }
  2416. 它又调用了vivi.c中的vivi_start_generating函数:
  2417. static int vivi_start_generating(struct vivi_dev *dev)
  2418. {
  2419.     struct vivi_dmaqueue *dma_q = &dev->vidq;

  2420.     dprintk(dev, 1, "%s ", __func__);

  2421.     /* Resets frame counters */
  2422.     dev->ms = 0;
  2423.     dev->mv_count = 0;
  2424.     dev->jiffies = jiffies;

  2425.     dma_q->frame = 0;
  2426.     dma_q->ini_jiffies = jiffies;
  2427.     dma_q->kthread = kthread_run(vivi_thread, dev, dev->v4l2_dev.name);

  2428.     if (IS_ERR(dma_q->kthread)) {
  2429.         v4l2_err(&dev->v4l2_dev, "kernel_thread() failed ");
  2430.         return PTR_ERR(dma_q->kthread);
  2431.     }
  2432.     /* Wakes thread */
  2433.     wake_up_interruptible(&dma_q->wq);

  2434.     dprintk(dev, 1, "returning from %s ", __func__);
  2435.     return 0;
  2436. }
  2437. 在这个vivi_start_generating函数中,它通过启动一个内核线程的方式,在内核线程vivi_thread中调用启动一个队列,收集到的信息后填充到队列中的第一个buf中,然后通过wake_up_interruptible来唤醒线程,这些都是vivi.c中对于收集信息所做的处理。我们现在分析的是v4l2框架的流程,知道在这进行了这些处理就行,我们后面再具体分析数据处理的过程。
  2438.  */

  2439.     q->streaming = 1;
  2440. /* 设置vb2_queue q的streaming为1,表明已经启动了流处理。 */
  2441.     dprintk(3, "Streamon successful ");
  2442.     return 0;
  2443. }
  2444. EXPORT_SYMBOL_GPL(vb2_streamon);


  2445. 4.6 分析vivi.c中开启streamon以后的数据处理过程:
  2446. 上面提到一直调用到vivi.c中的vivi_start_generating函数,在这个函数中通过
  2447. dma_q->kthread = kthread_run(vivi_thread, dev, dev->v4l2_dev.name);
  2448. 来启动一个vivi_thread的内核线程:
  2449. static int vivi_thread(void *data)
  2450. {
  2451.     struct vivi_dev *dev = data;

  2452.     dprintk(dev, 1, "thread started ");

  2453.     set_freezable();

  2454.     for (;;) {
  2455.         vivi_sleep(dev);

  2456.         if (kthread_should_stop())
  2457.             break;
  2458.     }
  2459.     dprintk(dev, 1, "thread: exit ");
  2460.     return 0;
  2461. }
  2462. 这个线程进入一个死循环中,在这个死循环中是vivi_sleep函数:
  2463. static void vivi_sleep(struct vivi_dev *dev)
  2464. {
  2465.     struct vivi_dmaqueue *dma_q = &dev->vidq;
  2466.     int timeout;
  2467.     DECLARE_WAITQUEUE(wait, current);

  2468.     dprintk(dev, 1, "%s dma_q=0x%08lx ", __func__,
  2469.         (unsigned long)dma_q);

  2470.     add_wait_queue(&dma_q->wq, &wait);
  2471.     if (kthread_should_stop())
  2472.         goto stop_task;

  2473.     /* Calculate time to wake up */
  2474.     timeout = msecs_to_jiffies(frames_to_ms(1));

  2475.     vivi_thread_tick(dev);

  2476.     schedule_timeout_interruptible(timeout);

  2477. stop_task:
  2478.     remove_wait_queue(&dma_q->wq, &wait);
  2479.     try_to_freeze();
  2480. }
  2481. 在这个vivi_sleep函数中,申请了一个等待队列:dma_q->wq,然后就进入vivi_thread_tick(dev); 中等待队列被唤醒,vivi_thread_tick函数如下所示:
  2482. static void vivi_thread_tick(struct vivi_dev *dev)
  2483. {
  2484.     struct vivi_dmaqueue *dma_q = &dev->vidq;
  2485.     struct vivi_buffer *buf;
  2486.     unsigned long flags = 0;

  2487.     dprintk(dev, 1, "Thread tick ");

  2488.     spin_lock_irqsave(&dev->slock, flags);
  2489.     if (list_empty(&dma_q->active)) {
  2490.         dprintk(dev, 1, "No active queue to serve ");
  2491.         spin_unlock_irqrestore(&dev->slock, flags);
  2492.         return;
  2493.     }

  2494.     buf = list_entry(dma_q->active.next, struct vivi_buffer, list);
  2495.     list_del(&buf->list);
  2496.     spin_unlock_irqrestore(&dev->slock, flags);

  2497.     do_gettimeofday(&buf->vb.v4l2_buf.timestamp);

  2498.     /* Fill buffer */
  2499.     vivi_fillbuff(dev, buf);
  2500.     dprintk(dev, 1, "filled buffer %p ", buf);

  2501.     vb2_buffer_done(&buf->vb, VB2_BUF_STATE_DONE);
  2502.     dprintk(dev, 2, "[%p/%d] done ", buf, buf->vb.v4l2_buf.index);
  2503. }
  2504. 在这个函数中,调用vivi_fillbuff函数来填充数据,然后调用vb2_buffer_done函数,这个函数在videobuf2-core.c文件中,如下所示:
  2505. /**
  2506.  * vb2_buffer_done() - inform videobuf that an operation on a buffer is finished
  2507.  * @vb:        vb2_buffer returned from the driver
  2508.  * @state:    either VB2_BUF_STATE_DONE if the operation finished successfully
  2509.  *        or VB2_BUF_STATE_ERROR if the operation finished with an error
  2510.  *
  2511.  * This function should be called by the driver after a hardware operation on
  2512.  * a buffer is finished and the buffer may be returned to userspace. The driver
  2513.  * cannot use this buffer anymore until it is queued back to it by videobuf
  2514.  * by the means of buf_queue callback. Only buffers previously queued to the
  2515.  * driver by buf_queue can be passed to this function.
  2516.  */
  2517. void vb2_buffer_done(struct vb2_buffer *vb, enum vb2_buffer_state state)
  2518. {
  2519.     struct vb2_queue *q = vb->vb2_queue;
  2520.     unsigned long flags;

  2521.     if (vb->state != VB2_BUF_STATE_ACTIVE)
  2522.         return;
  2523. /* 因为在前面的步骤已经设置了vb2_buffer vb的属性为 VB2_BUF_STATE_ACTIVE,这时候再次检查这个属性,如果不为 VB2_BUF_STATE_ACTIVE的话就直接返回。 */
  2524.     if (state != VB2_BUF_STATE_DONE && state != VB2_BUF_STATE_ERROR)
  2525.         return;
  2526. /* 检查函数传入的属性,它代表vb2_buffer的下一个属性,只能是 VB2_BUF_STATE_DONE和 VB2_BUF_STATE_ERROR中的一个,如果不是这两个就直接返回。 */
  2527.     dprintk(4, "Done processing on buffer %d, state: %d ",
  2528.             vb->v4l2_buf.index, vb->state);

  2529.     /* Add the buffer to the done buffers list */
  2530.     spin_lock_irqsave(&q->done_lock, flags);
  2531.     vb->state = state;
  2532. /* 设置vb2_buffer的属性为 VB2_BUF_STATE_DONE或VB2_BUF_STATE_ERROR。 */
  2533.     list_add_tail(&vb->done_entry, &q->done_list);
  2534. /* 将vb2_buffer里面的done_entry队列添加到 vb2_queue q的done_list链表中去。 */
  2535.     atomic_dec(&q->queued_count);
  2536. /* 原子减少这个计数*/
  2537.     spin_unlock_irqrestore(&q->done_lock, flags);

  2538.     /* Inform any processes that may be waiting for buffers */
  2539.     wake_up(&q->done_wq);
  2540. /* 唤醒vb2_buffer q里面的done_wq等待队列。 */
  2541. }
  2542. EXPORT_SYMBOL_GPL(vb2_buffer_done);

  2543. 这一步的主要目的就是将vivi.c中的vb2加入q->done_list中,然后设置vb->state的属性为VB2_BUF_STATE_DONE,上面的这两步非常重要,在后面会用到这,这两步的核心代码就是videobuf2-core.c中的 vb2_buffer_done函数。


  2544. 4.7 应用程序这时候就开始收集摄像头数据了,当它收集到数据的时候,就调用到了poll/select机制,应用程序如下所示:
  2545. static void run (void)
  2546. {
  2547.     unsigned int count;
  2548.     int frames;
  2549.     frames = 30 * time_in_sec_capture;

  2550.     while (frames-- > 0)
  2551.     {
  2552.         for (;;)
  2553.         {
  2554.             fd_set fds;
  2555.             struct timeval tv;
  2556.             int r;
  2557.             FD_ZERO (&fds);
  2558.             FD_SET (fd, &fds);

  2559.             tv.tv_sec = 2;
  2560.             tv.tv_usec = 0;
  2561.             /* poll method*/
  2562.             r = select (fd + 1, &fds, NULL, NULL, &tv);

  2563.             if (read_frame())
  2564.             break;
  2565.         }
  2566.     }
  2567. }

  2568. 经过v4l2框架的一系列转换,最终调用到vivi.c驱动中我们自己实现的vivi_poll 函数中:
  2569. static unsigned int
  2570. vivi_poll(struct file *file, struct poll_table_struct *wait)
  2571. {
  2572.     struct vivi_dev *dev = video_drvdata(file);
  2573.     struct v4l2_fh *fh = file->private_data;
  2574.     struct vb2_queue *q = &dev->vb_vidq;
  2575.     unsigned int res;

  2576.     dprintk(dev, 1, "%s ", __func__);
  2577.     res = vb2_poll(q, file, wait);
  2578.     if (v4l2_event_pending(fh))
  2579.         res |= POLLPRI;
  2580.     else
  2581.         poll_wait(file, &fh->wait, wait);
  2582.     return res;
  2583. }
  2584. 它又调用到vb2_poll函数,如下所示:
  2585. /**
  2586.  * vb2_poll() - implements poll userspace operation
  2587.  * @q:        videobuf2 queue
  2588.  * @file:    file argument passed to the poll file operation handler
  2589.  * @wait:    wait argument passed to the poll file operation handler
  2590.  *
  2591.  * This function implements poll file operation handler for a driver.
  2592.  * For CAPTURE queues, if a buffer is ready to be dequeued, the userspace will
  2593.  * be informed that the file descriptor of a video device is available for
  2594.  * reading.
  2595.  * For OUTPUT queues, if a buffer is ready to be dequeued, the file descriptor
  2596.  * will be reported as available for writing.
  2597.  *
  2598.  * The return values from this function are intended to be directly returned
  2599.  * from poll handler in driver.
  2600.  */
  2601. unsigned int vb2_poll(struct vb2_queue *q, struct file *file, poll_table *wait)
  2602. {
  2603.     unsigned long flags;
  2604.     unsigned int ret;
  2605.     struct vb2_buffer *vb = NULL;

  2606.     /*
  2607.      * Start file I/O emulator only if streaming API has not been used yet.
  2608.      */
  2609.     if (q->num_buffers == 0 && q->fileio == NULL) {
  2610.         if (!V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_READ)) {
  2611.             ret = __vb2_init_fileio(q, 1);
  2612.             if (ret)
  2613.                 return POLLERR;
  2614.         }
  2615.         if (V4L2_TYPE_IS_OUTPUT(q->type) && (q->io_modes & VB2_WRITE)) {
  2616.             ret = __vb2_init_fileio(q, 0);
  2617.             if (ret)
  2618.                 return POLLERR;
  2619.             /*
  2620.              * Write to OUTPUT queue can be done immediately.
  2621.              */
  2622.             return POLLOUT | POLLWRNORM;
  2623.         }
  2624.     }

  2625.     /*
  2626.      * There is nothing to wait for if no buffers have already been queued.
  2627.      */
  2628.     if (list_empty(&q->queued_list))
  2629.         return POLLERR;
  2630.  
  2631.     poll_wait(file, &q->done_wq, wait);
  2632. /* 调用poll_wait等待vb2_queue q的done_wq队列是否有数据填充,那么它是什么时候有数据填充的呢?就是我们上一步分析的。 */
  2633.     /*
  2634.      * Take first buffer available for dequeuing.
  2635.      */
  2636.     spin_lock_irqsave(&q->done_lock, flags);
  2637.     if (!list_empty(&q->done_list))
  2638.         vb = list_first_entry(&q->done_list, struct vb2_buffer,
  2639.                     done_entry);
  2640.     spin_unlock_irqrestore(&q->done_lock, flags);
  2641. /* 从vb2_queue q队列的done_list中,取出第一个vb2_buffer,为dqbuf做准备。 */
  2642.     if (vb && (vb->state == VB2_BUF_STATE_DONE
  2643.             || vb->state == VB2_BUF_STATE_ERROR)) {
  2644.         return (V4L2_TYPE_IS_OUTPUT(q->type)) ? POLLOUT | POLLWRNORM :
  2645.             POLLIN | POLLRDNORM;
  2646. /* poll机制返回值,根据q->type类型,返回可读还是可写。 */
  2647.     }
  2648.     return 0;
  2649. }
  2650. EXPORT_SYMBOL_GPL(vb2_poll);

  2651. 4.8 看上面4.7步中的应用程序,它在run函数的死循环中,如果poll机制返回可读还是可写的话,就调用read_frame函数,这个函数如下所示:
  2652. static int read_frame (void)
  2653. {
  2654.     struct v4l2_buffer buf;
  2655.     unsigned int i;

  2656.     CLEAR (buf);
  2657.     buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  2658.     buf.memory = V4L2_MEMORY_MMAP;
  2659.     /* VIDIOC_DQBUF把数据放回缓存队列*/
  2660.     if (-1 == xioctl (fd, VIDIOC_DQBUF, &buf))
  2661.     {
  2662.         switch (errno)
  2663.         {
  2664.             case EAGAIN:
  2665.             return 0;
  2666.             case EIO:
  2667.             default:
  2668.             errno_exit ("VIDIOC_DQBUF");
  2669.         }
  2670.     }

  2671.     assert (buf.index < n_buffers);
  2672.     printf("v4l2_pix_format->field(%d)/n", buf.field);
  2673.     //assert (buf.field ==V4L2_FIELD_NONE);
  2674.     process_image (buffers[buf.index].start);

  2675.     /* VIDIOC_QBUF把数据从缓存中读取出来*/
  2676.     if (-1 == xioctl (fd, VIDIOC_QBUF, &buf))
  2677.     errno_exit ("VIDIOC_QBUF");
  2678.     return 1;
  2679. }
  2680. 应用程序调用ioctl:VIDIOC_DQBUF,经过一系列的转换,最终调用到vivi.c中的vidioc_dqbuf 函数:static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
  2681. {
  2682.     struct vivi_dev *dev = video_drvdata(file);
  2683.     return vb2_dqbuf(&dev->vb_vidq, p, file->f_flags & O_NONBLOCK);
  2684. }
  2685. 它有调用到videobuf2-core.c中的vb2_dqbuf函数,如下所示:
  2686. /**
  2687.  * vb2_dqbuf() - Dequeue a buffer to the userspace
  2688.  * @q:        videobuf2 queue
  2689.  * @b:        buffer structure passed from userspace to vidioc_dqbuf handler
  2690.  *        in driver
  2691.  * @nonblocking: if true, this call will not sleep waiting for a buffer if no
  2692.  *         buffers ready for dequeuing are present. Normally the driver
  2693.  *         would be passing (file->f_flags & O_NONBLOCK) here
  2694.  *
  2695.  * Should be called from vidioc_dqbuf ioctl handler of a driver.
  2696.  * This function:
  2697.  * 1) verifies the passed buffer,
  2698.  * 2) calls buf_finish callback in the driver (if provided), in which
  2699.  * driver can perform any additional operations that may be required before
  2700.  * returning the buffer to userspace, such as cache sync,
  2701.  * 3) the buffer struct members are filled with relevant information for
  2702.  * the userspace.
  2703.  *
  2704.  * The return values from this function are intended to be directly returned
  2705.  * from vidioc_dqbuf handler in driver.
  2706.  */
  2707. int vb2_dqbuf(struct vb2_queue *q, struct v4l2_buffer *b, bool nonblocking)
  2708. {
  2709.     struct vb2_buffer *vb = NULL;
  2710.     int ret;

  2711.     if (q->fileio) {
  2712.         dprintk(1, "dqbuf: file io in progress ");
  2713.         return -EBUSY;
  2714.     }

  2715.     if (b->type != q->type) {
  2716.         dprintk(1, "dqbuf: invalid buffer type ");
  2717.         return -EINVAL;
  2718.     }

  2719.     ret = __vb2_get_done_vb(q, &vb, nonblocking);
  2720.     if (ret < 0) {
  2721.         dprintk(1, "dqbuf: error getting next done buffer ");
  2722.         return ret;
  2723.     }
  2724. /*
  2725. /**
  2726.  * __vb2_get_done_vb() - get a buffer ready for dequeuing
  2727.  *
  2728.  * Will sleep if required for nonblocking == false.
  2729.  */
  2730. static int __vb2_get_done_vb(struct vb2_queue *q, struct vb2_buffer **vb,
  2731.                 int nonblocking)
  2732. {
  2733.     unsigned long flags;
  2734.     int ret;

  2735.     /*
  2736.      * Wait for at least one buffer to become available on the done_list.
  2737.      */
  2738.     ret = __vb2_wait_for_done_vb(q, nonblocking);
  2739.     if (ret)
  2740.         return ret;
  2741.     /* 至少等待在done_list链表里面有一个buffer */
  2742.     /*
  2743.      * Driver's lock has been held since we last verified that done_list
  2744.      * is not empty, so no need for another list_empty(done_list) check.
  2745.      */
  2746.     spin_lock_irqsave(&q->done_lock, flags);
  2747.     *vb = list_first_entry(&q->done_list, struct vb2_buffer, done_entry);
  2748.     list_del(&(*vb)->done_entry);
  2749.     spin_unlock_irqrestore(&q->done_lock, flags);
  2750. /* 从vb2_queue队列的done_lise链表中,把vb中done_entry链表删除 */
  2751.     return 0;
  2752. }
  2753. */
  2754.     ret = call_qop(q, buf_finish, vb);
  2755.     if (ret) {
  2756.         dprintk(1, "dqbuf: buffer finish failed ");
  2757.         return ret;
  2758.     }
  2759. /* 最终调用到vivi.c中的buffer_finish函数 */

  2760.     switch (vb->state) {
  2761.     case VB2_BUF_STATE_DONE:
  2762.         dprintk(3, "dqbuf: Returning done buffer ");
  2763.         break;
  2764.     case VB2_BUF_STATE_ERROR:
  2765.         dprintk(3, "dqbuf: Returning done buffer with errors ");
  2766.         break;
  2767.     default:
  2768.         dprintk(1, "dqbuf: Invalid buffer state ");
  2769.         return -EINVAL;
  2770.     }
  2771. /* 这时候传过来的vb_state应该是 VB2_BUF_STATE_ACTIVE的,除此之外的直接返回。 */
  2772.     /* Fill buffer information for the userspace */
  2773.     __fill_v4l2_buffer(vb, b);
  2774. /* 填充v4l2_buffer结构体 */
  2775.     /* Remove from videobuf queue */
  2776.     list_del(&vb->queued_entry);
  2777. /* 把vb2_buffer vb中的queued_entry链表中的一项。 */

  2778.     dprintk(1, "dqbuf of buffer %d, with state %d ",
  2779.             vb->v4l2_buf.index, vb->state);

  2780.     vb->state = VB2_BUF_STATE_DEQUEUED;
  2781. /* 设置vb2_buffer的状态为 VB2_BUF_STATE_DEQUEUED */
  2782.     return 0;
  2783. }
  2784. EXPORT_SYMBOL_GPL(vb2_dqbuf);

  2785. 4.9 看4.8中的read_frame应用程序函数,它执行完ioctl:VIDIOC_DQBUF后,执行process_image函数,来完成对图像的处理,处理完图像以后,就直接再次调用ioctl:VIDIOC_QBUF调用,就这样一直循环执行,直到应用程序调用ioctl:VIDIOC_STREAMOFF 调用。

  2786. 4.10 下面讲ioctl:VIDIOC_STREAMOFF 调用,应用程序一般如下所示:
  2787. static void stop_capturing (void)
  2788. {
  2789.     enum v4l2_buf_type type;
  2790.     type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
  2791.     /* VIDIOC_STREAMOFF结束视频显示函数*/
  2792.     if (-1 == xioctl (fd, VIDIOC_STREAMOFF, &type))
  2793.     errno_exit ("VIDIOC_STREAMOFF");
  2794. }

  2795. 经过一系列的转换,最终调用到vivi.c中的stop_streaming函数,如下所示:
  2796. /* abort streaming and wait for last buffer */
  2797. static int stop_streaming(struct vb2_queue *vq)
  2798. {
  2799.     struct vivi_dev *dev = vb2_get_drv_priv(vq);
  2800.     dprintk(dev, 1, "%s ", __func__);
  2801.     vivi_stop_generating(dev);
  2802.     return 0;
  2803. }
  2804. static void vivi_stop_generating(struct vivi_dev *dev)
  2805. {
  2806.     struct vivi_dmaqueue *dma_q = &dev->vidq;

  2807.     dprintk(dev, 1, "%s ", __func__);

  2808.     /* shutdown control thread */
  2809.     if (dma_q->kthread) {
  2810.         kthread_stop(dma_q->kthread);
  2811.         dma_q->kthread = NULL;
  2812.     }
  2813.  /* 把内核线程关闭了。 */
  2814.     /*
  2815.      * Typical driver might need to wait here until dma engine stops.
  2816.      * In this case we can abort imiedetly, so it's just a noop.
  2817.      */

  2818.     /* Release all active buffers */
  2819.     while (!list_empty(&dma_q->active)) {
  2820.         struct vivi_buffer *buf;
  2821.         buf = list_entry(dma_q->active.next, struct vivi_buffer, list);
  2822.         list_del(&buf->list);
  2823.         vb2_buffer_done(&buf->vb, VB2_BUF_STATE_ERROR);
  2824.         dprintk(dev, 2, "[%p/%d] done ", buf, buf->vb.v4l2_buf.index);
  2825.     }
  2826. /* 一直把所有的缓冲区都释放掉。 */
  2827. }

  2828. 至此,基本所有的过程都分析完毕了,剩下的就是把上面做标记的位置填充了,把哪个ioctl控制的流程图画了,mmap的分析,ioctl的分析。
  2829. 分析这么点东西花了一个星期时间了,先放一放。。。。。。
原文地址:https://www.cnblogs.com/sky-heaven/p/9597134.html