How to get a list of video capture devices (web cameras) on linux ( ubuntu )? (C/C++)

83,585

Solution 1

This is a code snippet I had laying around. Probably from a book. I guess you could just iterate over all /dev/videoN nodes and get the info.

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/videodev.h>

int main(){
    int fd;
    struct video_capability video_cap;
    struct video_window     video_win;
    struct video_picture   video_pic;

    if((fd = open("/dev/video0", O_RDONLY)) == -1){
        perror("cam_info: Can't open device");
        return 1;
    }

    if(ioctl(fd, VIDIOCGCAP, &video_cap) == -1)
        perror("cam_info: Can't get capabilities");
    else {
        printf("Name:\t\t '%s'\n", video_cap.name);
        printf("Minimum size:\t%d x %d\n", video_cap.minwidth, video_cap.minheight);
        printf("Maximum size:\t%d x %d\n", video_cap.maxwidth, video_cap.maxheight);
    }

    if(ioctl(fd, VIDIOCGWIN, &video_win) == -1)
        perror("cam_info: Can't get window information");
    else
        printf("Current size:\t%d x %d\n", video_win.width, video_win.height);

    if(ioctl(fd, VIDIOCGPICT, &video_pic) == -1)
        perror("cam_info: Can't get picture information");
    else
        printf("Current depth:\t%d\n", video_pic.depth);

    close(fd);
    return 0;
}

Solution 2

You can use the following bash command:

v4l2-ctl --list-devices

In order to use the above command, you must install package v4l-utils before. In Ubuntu/Debian you can use the command:

sudo apt-get install v4l-utils

Solution 3

It's easy by just traversing sysfs devices by a given class. The following command-line one liner would do so:

for I in /sys/class/video4linux/*; do cat $I/name; done

You can do the same thing in C/C++ application, by just opening up /sys/class/video4linux directory, it will have symlinks to all your web cameras as video4linux devices:

$ ls -al /sys/class/video4linux                          
drwxr-xr-x  2 root root 0 Ноя 27 12:19 ./
drwxr-xr-x 34 root root 0 Ноя 26 00:08 ../
lrwxrwxrwx  1 root root 0 Ноя 27 12:19 video0 -> ../../devices/pci0000:00/0000:00:13.2/usb2/2-5/2-5:1.0/video4linux/video0/

You can follow every symlink to a directory of every device and read full contents of name file in that directory to get the name.

Share:
83,585
Rella
Author by

Rella

Hi! sorry - I am C/C++ noobe, and I am reading a book=)

Updated on August 09, 2020

Comments