Camera timeout duration as parameter (#408)

Set PION_MEDIADEVICES_CAMERA_READ_TIMEOUT environment variable
to set the timeout duration.
This commit is contained in:
f-fl0
2022-06-23 10:33:23 +09:00
committed by GitHub
parent e371c0d955
commit 5b99500290
2 changed files with 45 additions and 1 deletions

View File

@@ -10,6 +10,7 @@ import (
"io" "io"
"os" "os"
"path/filepath" "path/filepath"
"strconv"
"sync" "sync"
"github.com/blackjack/webcam" "github.com/blackjack/webcam"
@@ -133,6 +134,19 @@ func newCamera(path string) *camera {
return c return c
} }
func getCameraReadTimeout() uint32 {
// default to 5 seconds
var readTimeoutSec uint32 = 5
if val, ok := os.LookupEnv("PION_MEDIADEVICES_CAMERA_READ_TIMEOUT"); ok {
if valInt, err := strconv.Atoi(val); err == nil {
if valInt > 0 {
readTimeoutSec = uint32(valInt)
}
}
}
return readTimeoutSec
}
func (c *camera) Open() error { func (c *camera) Open() error {
cam, err := webcam.Open(c.path) cam, err := webcam.Open(c.path)
if err != nil { if err != nil {
@@ -192,6 +206,8 @@ func (c *camera) VideoRecord(p prop.Media) (video.Reader, error) {
cam := c.cam cam := c.cam
readTimeoutSec := getCameraReadTimeout()
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
c.cancel = cancel c.cancel = cancel
var buf []byte var buf []byte
@@ -207,7 +223,7 @@ func (c *camera) VideoRecord(p prop.Media) (video.Reader, error) {
return nil, func() {}, io.EOF return nil, func() {}, io.EOF
} }
err := cam.WaitForFrame(5) // 5 seconds err := cam.WaitForFrame(readTimeoutSec)
switch err.(type) { switch err.(type) {
case nil: case nil:
case *webcam.Timeout: case *webcam.Timeout:

View File

@@ -70,3 +70,31 @@ func TestDiscover(t *testing.T) {
t.Errorf("Expected label: %s, got: %s", expectedNoLink, label) t.Errorf("Expected label: %s, got: %s", expectedNoLink, label)
} }
} }
func TestGetCameraReadTimeout(t *testing.T) {
var expected uint32 = 5
value := getCameraReadTimeout()
if value != expected {
t.Errorf("Expected: %d, got: %d", expected, value)
}
envVarName := "PION_MEDIADEVICES_CAMERA_READ_TIMEOUT"
os.Setenv(envVarName, "text")
value = getCameraReadTimeout()
if value != expected {
t.Errorf("Expected: %d, got: %d", expected, value)
}
os.Setenv(envVarName, "-1")
value = getCameraReadTimeout()
if value != expected {
t.Errorf("Expected: %d, got: %d", expected, value)
}
os.Setenv(envVarName, "1")
expected = 1
value = getCameraReadTimeout()
if value != expected {
t.Errorf("Expected: %d, got: %d", expected, value)
}
}