From 204ec0144cafb9b37ac4b63ec2fb2c60f9067621 Mon Sep 17 00:00:00 2001 From: Ravi Shekhar Jethani Date: Wed, 2 Oct 2019 08:43:17 +0200 Subject: [PATCH] Add FindAndOpen() func This function will lookup suitable webcam device and open it. IMO this is better than hardcoding `/dev/video0`. --- webcam.go | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/webcam.go b/webcam.go index 19d3559..3a7f035 100644 --- a/webcam.go +++ b/webcam.go @@ -6,6 +6,8 @@ package webcam import ( "errors" "golang.org/x/sys/unix" + "os" + "path/filepath" "reflect" "unsafe" ) @@ -26,6 +28,44 @@ type Control struct { Max int32 } +// FindAndOpen unlike Open() will itself search for a suitable webcam +// device on the system. It will return error if unable to locate one +func FindAndOpen() (*Webcam, error) { + // First option: look at the well known location + cam, err := Open("/dev/vide0") + if err == nil { + return cam, nil + } + + // Second option: Walk over all the character devices in /dev and try + // locating a suitable webcam device + err = filepath.Walk("/dev", func(path string, info os.FileInfo, err error) error { + if err != nil { + return errors.New("error while searching for webcam device: " + err.Error()) + } + if info.Mode()&os.ModeCharDevice != 0 { + c, err := Open(path) + if err == nil { + cam = c + return filepath.SkipDir + } + } + return nil + }) + // cam is not nil: this means we found a suitable webcam device while walking /dev + if cam != nil { + return cam, nil + } + // cam is nil but err is not nil: this means some error occured while walking over + // device files. Simply return the error + if err != nil { + return nil, err + } + // cam is nil and err is also nil: this means we successfully walked + // over available device files but cannot locate a suitable webcam device + return nil, errors.New("no working webcam device found") +} + // Open a webcam with a given path // Checks if device is a v4l2 device and if it is // capable to stream video