Merged in geovision-api (pull request #263)

input/gvctrl: GeoVision control API

Approved-by: Alan Noble <anoble@gmail.com>
This commit is contained in:
Saxon Milton 2019-10-17 22:31:16 +00:00
commit ce6c12cce8
6 changed files with 1056 additions and 0 deletions

3
input/gvctrl/go.mod Normal file
View File

@ -0,0 +1,3 @@
module bitbucket.org/ausocean/av/input/gvctrl
go 1.12

View File

@ -0,0 +1,98 @@
/*
DESCRIPTION
See package description.
AUTHORS
Saxon A. Nelson-Milton <saxon@ausocean.org>
LICENSE
Copyright (C) 2019 the Australian Ocean Lab (AusOcean)
It is free software: you can redistribute it and/or modify them
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
in gpl.txt. If not, see http://www.gnu.org/licenses.
*/
// Package gvctrl-cli provides a command line interface for controlling GeoVision
// camera settings using the gvctrl package.
package main
import (
"flag"
"fmt"
"strconv"
"bitbucket.org/ausocean/av/input/gvctrl"
)
func main() {
var (
hostPtr = flag.String("host", "192.168.1.50", "IP of GeoVision camera.")
codecPtr = flag.String("codec", "", "h264, h265 or mjpeg")
heightPtr = flag.Int("height", 0, "256, 360 or 720")
fpsPtr = flag.Int("fps", 0, "Frame rate in frames per second.")
vbrPtr = flag.Bool("vbr", false, "If true, variable bitrate.")
vbrQualityPtr = flag.Int("quality", -1, "General quality under variable bitrate, 0 to 4 inclusive.")
vbrRatePtr = flag.Int("vbr-rate", 0, "Variable bitrate maximal bitrate in kbps.")
cbrRatePtr = flag.Int("cbr-rate", 0, "Constant bitrate, bitrate in kbps.")
refreshPtr = flag.Float64("refresh", 0, "Inter refresh period in seconds.")
)
flag.Parse()
var options []gvctrl.Option
if *codecPtr != "" {
var c gvctrl.Codec
switch *codecPtr {
case "h264":
c = gvctrl.CodecH264
case "h265":
c = gvctrl.CodecH265
case "mjpeg":
c = gvctrl.CodecMJPEG
default:
panic(fmt.Sprintf("invalid codec: %s", *codecPtr))
}
options = append(options, gvctrl.CodecOut(c))
}
if *heightPtr != 0 {
options = append(options, gvctrl.Height(*heightPtr))
}
if *fpsPtr != 0 {
options = append(options, gvctrl.FrameRate(*fpsPtr))
}
options = append(options, gvctrl.VariableBitrate(*vbrPtr))
if *vbrQualityPtr != -1 {
options = append(options, gvctrl.VBRQuality(gvctrl.Quality(strconv.Itoa(*vbrQualityPtr))))
}
if *vbrRatePtr != 0 {
options = append(options, gvctrl.VBRBitrate(*vbrRatePtr))
}
if *cbrRatePtr != 0 {
options = append(options, gvctrl.CBRBitrate(*cbrRatePtr))
}
if *refreshPtr != 0 {
options = append(options, gvctrl.Refresh(*refreshPtr))
}
err := gvctrl.Set(*hostPtr, options...)
if err != nil {
panic(fmt.Sprintf("error from gvctrl.Set: %v", err))
}
}

263
input/gvctrl/gvctrl.go Normal file
View File

@ -0,0 +1,263 @@
/*
DESCRIPTION
gvctrl.go provides exported functionality of a basic API to allow programmatic
control over the GeoVision camera (namely the GV-BX4700) through the HTTP
server used for settings control. See package documentation for further
information on the API.
AUTHORS
Saxon A. Nelson-Milton <saxon@ausocean.org>
LICENSE
Copyright (C) 2019 the Australian Ocean Lab (AusOcean)
It is free software: you can redistribute it and/or modify them
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
Option) any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
in gpl.txt. If not, see http://www.gnu.org/licenses.
*/
// Package gvctrl provides a basic API for programmatic control of the
// web based interface provided by GeoVision cameras. This API has been
// developed and tested only with the GV-BX4700, and therefore may not work
// with other models without further evolution.
//
// Settings on a GeoVision camera are updated using the Set function. One or
// more option functions may be provided to control camera function.
package gvctrl
import (
"fmt"
"math/rand"
"net/http"
"net/http/cookiejar"
"strconv"
"time"
)
// Option describes a function that will apply an option to the passed s.
type Option func(s settings) (settings, error)
// Set will log-in to the camera at host and submit a form of settings. The
// settings form is populated with values influenced by the optional options
// passed. Available options are defined below this function.
//
// The following defaults are applied to each configurable parameter if not
// influenced by the passed options:
// codec: H264
// resolution: 640x360
// framerate: 25
// variable bitrate: off
// variable bitrate quality: good
// vbr bitrate: 250 kbps
// cbr bitrate: 512 kbps
// refresh: 2 seconds
func Set(host string, options ...Option) error {
// Randomly generate an ID our client will use.
const (
minID = 10000
maxID = 99999
)
rand.Seed(time.Now().UTC().UnixNano())
id := strconv.Itoa(maxID + rand.Intn(maxID-minID))
// Create a client with a cookie jar.
jar, err := cookiejar.New(nil)
if err != nil {
return fmt.Errorf("could not create cookie jar, failed with error: %v", err)
}
client := &http.Client{
Timeout: time.Duration(5 * time.Second),
Jar: jar,
}
// Get the request body required for log-in.
body, err := getLogin(client, id, host)
if err != nil {
return fmt.Errorf("could not generate log-in request data: %v", err)
}
// Log in using generated log-in request body.
err = login(client, id, host, body)
if err != nil {
return fmt.Errorf("could not login: %v", err)
}
// Apply the options to the settings specified by the user.
s := newSettings()
for _, op := range options {
s, err = op(s)
if err != nil {
return fmt.Errorf("could not action Option: %v", err)
}
}
// Submit the settings to the server.
err = submitSettings(client, id, host, s)
if err != nil {
return fmt.Errorf("could not submit settings: %v", err)
}
return nil
}
// Codec is a video codec.
type Codec string
// The avilable codecs that may be selected using CodecOut below.
const (
CodecH265 Codec = "28"
CodecH264 Codec = "10"
CodecMJPEG Codec = "4"
)
// CodecOut will set the video codec outputted by the camera. The available
// codec options are listed above as consts.
func CodecOut(c Codec) Option {
return func(s settings) (settings, error) {
switch c {
case CodecH265, CodecH264, CodecMJPEG:
s.codec = c
return s, nil
default:
return s, fmt.Errorf("unknown Codec: %v", c)
}
}
}
// Height will set the height component of the video resolution. Available
// heights are 256, 360 and 720.
func Height(h int) Option {
return func(s settings) (settings, error) {
v, ok := map[int]string{256: res256, 360: res360, 720: res720}[h]
if !ok {
return s, fmt.Errorf("invalid display height: %d", h)
}
s.res = v
return s, nil
}
}
// FrameRate will set the frame rate of the video. This value is defined in
// units of frames per second, and must be between 1 and 30 inclusive.
func FrameRate(f int) Option {
return func(s settings) (settings, error) {
if 1 > f || f > 30 {
return s, fmt.Errorf("invalid frame rate: %d", f)
}
s.frameRate = strconv.Itoa(f * 1000)
return s, nil
}
}
// VariableBitrate with b set true will turn on variable bitrate video and
// with b set false will turn off variable bitrate (resulting in constant bitrate).
func VariableBitrate(b bool) Option {
return func(s settings) (settings, error) {
s.vbr = "0"
if b {
s.vbr = "1"
}
return s, nil
}
}
// Quality defines an average quality of video from the camera.
type Quality string
// The available video qualities under variable bitrate. NB: it is not known
// what bitrates these correspond to.
const (
QualityStandard Quality = "4"
QualityFair Quality = "3"
QualityGood Quality = "2"
QualityGreat Quality = "1"
QualityExcellent Quality = "0"
)
// VBRQuality will set the average quality of video under variable bitrate.
// The quality may be chosen from standard to excellent, as defined above.
func VBRQuality(q Quality) Option {
return func(s settings) (settings, error) {
switch q {
case QualityStandard, QualityFair, QualityGood, QualityGreat, QualityExcellent:
s.quality = q
return s, nil
default:
return s, fmt.Errorf("invalid Quality: %v", q)
}
}
}
// VBRBitrate will set the maximal bitrate when the camera is set to variable
// bitrate. The possible values of maximal bitrate in kbps are predefined (by
// the camera) as: 250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250 and 2500.
// If the passed rate does not match one of these values, the closest value is
// selected.
func VBRBitrate(r int) Option {
return func(s settings) (settings, error) {
var vbrRates = []int{250, 500, 750, 1000, 1250, 1500, 1750, 2000, 2250, 2500}
if s.vbr == "1" {
s.vbrBitrate = convRate(r, vbrRates)
return s, nil
}
return s, nil
}
}
// CBRBitrate will select the bitrate when the camera is set to constant bitrate.
// The possible values of bitrate are predefined for each resolution as follows:
// 256p: 128, 256, 512, 1024
// 360p: 512, 1024, 2048, 3072
// 720p: 1024, 2048, 4096, 6144
// If the passed rate does not align with one of these values, the closest
// value is selected.
func CBRBitrate(r int) Option {
return func(s settings) (settings, error) {
var (
cbrRates256 = []int{128, 256, 512, 1024}
cbrRates360 = []int{512, 1024, 2048, 3072}
cbrRates720 = []int{1024, 2048, 4096, 6144}
)
switch s.res {
case res720:
s.cbrBitrate = convRate(r, cbrRates720)
case res360:
s.cbrBitrate = convRate(r, cbrRates360)
case res256:
s.cbrBitrate = convRate(r, cbrRates256)
default:
panic("bad resolution")
}
return s, nil
}
}
// Refresh will set the intra refresh period. The passed value is in seconds and
// must be between .25 and 5 inclusive. The value will be rounded to the nearest
// value divisible by .25 seconds.
func Refresh(r float64) Option {
return func(s settings) (settings, error) {
const (
maxRefreshPeriod = 5
minRefreshPeriod = .25
)
if minRefreshPeriod > r || r > maxRefreshPeriod {
return s, fmt.Errorf("invalid refresh period: %g", r)
}
refOptions := []int{250, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000}
s.refresh = strconv.Itoa(refOptions[closestValIdx(int(r*1000), refOptions)])
return s, nil
}
}

350
input/gvctrl/gvctrl_test.go Normal file
View File

@ -0,0 +1,350 @@
/*
DESCRIPTION
gvctrl_test.go provides tests of functionality in the gvctrl package.
AUTHORS
Saxon A. Nelson-Milton <saxon@ausocean.org>
LICENSE
Copyright (C) 2019 the Australian Ocean Lab (AusOcean)
It is free software: you can redistribute it and/or modify them
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
in gpl.txt. If not, see http://www.gnu.org/licenses.
*/
package gvctrl
import (
"errors"
"net/url"
"reflect"
"testing"
)
func TestClosestValIdx(t *testing.T) {
tests := []struct {
l []int
v int
want int
}{
{
l: []int{2, 5, 8, 11, 14},
v: 6,
want: 1,
},
{
l: []int{2, 5, 8, 11, 14},
v: 12,
want: 3,
},
{
l: []int{2, 5, 8, 11, 14},
v: 13,
want: 4,
},
{
l: []int{2, 5, 8, 11, 14},
v: 0,
want: 0,
},
{
l: []int{2, 5, 8, 11, 14},
v: 17,
want: 4,
},
{
l: []int{2, 5, 8, 11, 15},
v: 13,
want: 3,
},
{
l: []int{},
v: 17,
want: 0,
},
}
for i, test := range tests {
got := closestValIdx(test.v, test.l)
if got != test.want {
t.Errorf("did not get expected result for test: %d\nGot: %v\nWant: %v", i, got, test.want)
}
}
}
func TestConvRate(t *testing.T) {
tests := []struct {
l []int
v int
want string
}{
{
l: []int{512, 1024, 2048, 3072},
v: 1400,
want: "1024000",
},
{
l: []int{512, 1024, 2048, 3072},
v: 1900,
want: "2048000",
},
{
l: []int{512, 1024, 2048, 3072},
v: 4000,
want: "3072000",
},
}
for i, test := range tests {
got := convRate(test.v, test.l)
if got != test.want {
t.Errorf("did not get expected result for test: %d\nGot: %v\nWant: %v", i, got, test.want)
}
}
}
func TestHeight(t *testing.T) {
tests := []struct {
h int
want settings
err error
}{
{
h: 256,
want: settings{res: "4480256"},
},
{
h: 360,
want: settings{res: "6400360"},
},
{
h: 720,
want: settings{res: "12800720"},
},
{
h: 500,
want: settings{},
err: errors.New(""),
},
}
for i, test := range tests {
s := settings{}
got, err := Height(test.h)(s)
if test.err == nil && err != nil || test.err != nil && err == nil {
t.Errorf("did not get expected error: %v", test.err)
}
if got != test.want {
t.Errorf("did not get expected result for test: %d\nGot: %v\nWant: %v", i, got, test.want)
}
}
}
func TestVBRBitrate(t *testing.T) {
tests := []struct {
r int
in settings
want settings
}{
{
r: 300,
in: settings{vbr: "1"},
want: settings{
vbr: "1",
vbrBitrate: "250000",
},
},
{
r: 400,
in: settings{vbr: "1"},
want: settings{
vbr: "1",
vbrBitrate: "500000",
},
},
}
for i, test := range tests {
got, _ := VBRBitrate(test.r)(test.in)
if got != test.want {
t.Errorf("did not get expected result for test: %d\nGot: %v\nWant: %v", i, got, test.want)
}
}
}
func TestCBRBitrate(t *testing.T) {
tests := []struct {
r int
in settings
want settings
}{
{
r: 600,
in: settings{
vbr: "0",
res: res256,
},
want: settings{
vbr: "0",
res: res256,
cbrBitrate: "512000",
},
},
{
r: 100,
in: settings{
vbr: "0",
res: res256,
},
want: settings{
vbr: "0",
res: res256,
cbrBitrate: "128000",
},
},
{
r: 2048,
in: settings{
vbr: "0",
res: res360,
},
want: settings{
vbr: "0",
res: res360,
cbrBitrate: "2048000",
},
},
{
r: 500,
in: settings{
vbr: "0",
res: res720,
},
want: settings{
vbr: "0",
res: res720,
cbrBitrate: "1024000",
},
},
}
for i, test := range tests {
got, _ := CBRBitrate(test.r)(test.in)
if got != test.want {
t.Errorf("did not get expected result for test: %d\nGot: %v\nWant: %v", i, got, test.want)
}
}
}
func TestRefresh(t *testing.T) {
tests := []struct {
r float64
want settings
err error
}{
{
r: 1.6,
want: settings{refresh: "1500"},
},
{
r: 2.4,
want: settings{refresh: "2500"},
},
{
r: 0,
want: settings{},
err: errors.New(""),
},
{
r: 6,
want: settings{},
err: errors.New(""),
},
}
for i, test := range tests {
s := settings{}
got, err := Refresh(test.r)(s)
if test.err == nil && err != nil || test.err != nil && err == nil {
t.Errorf("did not get expected error: %v", test.err)
}
if got != test.want {
t.Errorf("did not get expected result for test: %d\nGot: %v\nWant: %v", i, got, test.want)
}
}
}
func TestPopulateForm(t *testing.T) {
tests := []struct {
in settings
want string
}{
{
in: newSettings(),
want: "dwConnType=5&mpeg_type=10&dwflicker_hz=0&szResolution=6400360&dwFrameRate=25000&vbr_enable=0&max_bit_rate=512000&custom_rate_control_type=0&custom_bitrate=0&custom_qp_init=25&custom_qp_min=10&custom_qp_max=40&gop_N=2000&dwEncProfile=1&dwEncLevel=31&dwEntropy=0&u8PreAlarmBuf=1&u32PostAlarmBuf2Disk=1&u8SplitInterval=5&bEnableIO=1&bEbIoIn=1&bEbIoIn1=1&bOSDFontSize=0&bEnableOSDCameraName=1&bCamNamePos=2&bEnableOSDDate=1&bDatePos=2&bEnableOSDTime=1&bTimePos=2&szOsdCamName=Camera&u16PostAlarmBuf=1&dwCameraId=1&LangCode=undefined&Recflag=0&submit=Apply",
},
{
in: settings{
codec: CodecH265,
res: defaultRes,
frameRate: defaultFrameRate,
vbr: defaultVBR,
quality: defaultQuality,
vbrBitrate: defaultVBRBitrate,
cbrBitrate: defaultCBRBitrate,
refresh: defaultRefresh,
},
want: "dwConnType=5&mpeg_type=28&dwflicker_hz=0&szResolution=6400360&dwFrameRate=25000&vbr_enable=0&max_bit_rate=512000&custom_rate_control_type=0&custom_bitrate=0&custom_qp_init=25&custom_qp_min=10&custom_qp_max=40&gop_N=2000&dwEncProfile=1&dwEncLevel=31&dwEntropy=0&u8PreAlarmBuf=1&u32PostAlarmBuf2Disk=1&u8SplitInterval=5&bEnableIO=1&bEbIoIn=1&bEbIoIn1=1&bOSDFontSize=0&bEnableOSDCameraName=1&bCamNamePos=2&bEnableOSDDate=1&bDatePos=2&bEnableOSDTime=1&bTimePos=2&szOsdCamName=Camera&u16PostAlarmBuf=1&dwCameraId=1&LangCode=undefined&Recflag=0&submit=Apply",
},
{
in: settings{
codec: CodecMJPEG,
res: defaultRes,
frameRate: defaultFrameRate,
vbr: defaultVBR,
quality: defaultQuality,
vbrBitrate: defaultVBRBitrate,
cbrBitrate: defaultCBRBitrate,
refresh: defaultRefresh,
},
want: "dwConnType=5&mpeg_type=4&dwflicker_hz=0&szResolution=6400360&dwFrameRate=25000&vbr_enable=1&dwVbrQuality=2&vbrmaxbitrate=500000&custom_qp_init=25&gop_N=1500&u8PreAlarmBuf=1&u32PostAlarmBuf2Disk=1&u8SplitInterval=5&bEnableIO=1&bEbIoIn=1&bEbIoIn1=1&bOSDFontSize=0&bEnableOSDCameraName=1&bCamNamePos=2&bEnableOSDDate=1&bDatePos=2&bEnableOSDTime=1&bTimePos=2&szOsdCamName=Camera&u16PostAlarmBuf=1&dwCameraId=1&LangCode=undefined&Recflag=0&submit=Apply",
},
{
in: settings{
codec: CodecH264,
res: defaultRes,
frameRate: defaultFrameRate,
vbr: "1",
quality: defaultQuality,
vbrBitrate: defaultVBRBitrate,
cbrBitrate: defaultCBRBitrate,
refresh: defaultRefresh,
},
want: "dwConnType=5&mpeg_type=10&dwflicker_hz=0&szResolution=6400360&dwFrameRate=25000&vbr_enable=1&dwVbrQuality=2&vbrmaxbitrate=250000&custom_rate_control_type=0&custom_bitrate=0&custom_qp_init=25&custom_qp_min=10&custom_qp_max=40&gop_N=2000&dwEncProfile=1&dwEncLevel=31&dwEntropy=0&u8PreAlarmBuf=1&u32PostAlarmBuf2Disk=1&u8SplitInterval=5&bEnableIO=1&bEbIoIn=1&bEbIoIn1=1&bOSDFontSize=0&bEnableOSDCameraName=1&bCamNamePos=2&bEnableOSDDate=1&bDatePos=2&bEnableOSDTime=1&bTimePos=2&szOsdCamName=Camera&u16PostAlarmBuf=1&dwCameraId=1&LangCode=undefined&Recflag=0&submit=Apply",
},
}
for i, test := range tests {
got := populateForm(test.in)
want, err := url.ParseQuery(test.want)
if err != nil {
t.Fatalf("should not have got error: %v parsing want string for test: %d", err, i)
}
if !reflect.DeepEqual(got, want) {
t.Errorf("did not get expected result for test: %d\nGot: %v\nWant: %v", i, got, want)
}
}
}

158
input/gvctrl/request.go Normal file
View File

@ -0,0 +1,158 @@
/*
DESCRIPTION
request.go provides unexported functionality for creating and sending requests
required to configure settings of the GeoVision camera.
AUTHORS
Saxon A. Nelson-Milton <saxon@ausocean.org>
LICENSE
Copyright (C) 2019 the Australian Ocean Lab (AusOcean)
It is free software: you can redistribute it and/or modify them
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
in gpl.txt. If not, see http://www.gnu.org/licenses.
*/
package gvctrl
import (
"bytes"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"regexp"
"strconv"
)
// Relevant sub directories.
const (
loginSubDir = "/ssi.cgi/login.htm" // Used to get log-in page.
loggedInSubDir = "/LoginPC.cgi" // Used to submit log-in.
settingsSubDir = "/VideoSetting.cgi" // Used to submit settings.
)
// TODO: make this configurable.
const (
user = "admin"
pass = "admin"
)
// getLogin gets the log-in page and extracts the randomly generated cc values
// from which (as well as username and password) two hashes are generated.
// The generated hex is encoded into a url encoded form and returned as a string.
func getLogin(c *http.Client, id, host string) (string, error) {
req, err := http.NewRequest("GET", "https://"+host+loginSubDir, nil)
if err != nil {
return "", fmt.Errorf("can't create GET request for log-in page: %v", err)
}
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Cache-Control", "max-age=0")
req.Header.Set("Upgrade-Insecure-Requests", "1")
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
req.Header.Set("Accept-Encoding", "gzip, deflate")
req.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Set("Cookie", "CLIENT_ID="+id)
resp, err := c.Do(req)
if err != nil {
return "", fmt.Errorf("could not do GET request for log-in page: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("could not read response of GET request for log-in page: %v", err)
}
// Find the CC values in the source of the response.
// These are used in calculation of the md5 hashes for the form submitted at
// log-in.
var cc [2]string
for i := range cc {
regStr := "cc" + strconv.Itoa(i+1) + "=\".{4}\""
exp := regexp.MustCompile(regStr).FindString(string(body))
cc[i] = exp[5 : len(exp)-1]
}
f := url.Values{}
f.Set("grp", "-1")
f.Set("username", "")
f.Set("password", "")
f.Set("Apply", "Apply")
f.Set("umd5", md5Hex(cc[0]+user+cc[1]))
f.Set("pmd5", md5Hex(cc[1]+pass+cc[0]))
f.Set("browser", "1")
f.Set("is_check_OCX_OK", "0")
return f.Encode(), nil
}
// login will submit the form b generated by genLogin.
func login(c *http.Client, id, host, b string) error {
req, err := http.NewRequest("POST", "http://"+host+loggedInSubDir, bytes.NewBuffer([]byte(b)))
if err != nil {
return fmt.Errorf("could not create log-in request: %v", err)
}
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Content-Length", "142")
req.Header.Set("Cache-Control", "max-age=0")
req.Header.Set("Origin", "http://"+host)
req.Header.Set("Upgrade-Insecure-Requests", "1")
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
req.Header.Set("Referer", "http://"+host+"/ssi.cgi/Login.htm")
req.Header.Set("Accept-Encoding", "gzip, deflate")
req.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Set("Cookie", "CLIENT_ID="+id+"; CLIENT_ID="+id)
_, err = c.Do(req)
if err != nil {
return fmt.Errorf("could not do log-in request: %v", err)
}
return nil
}
// submitSettings will populate a url encoded form using s and submit the
// settings to the server.
func submitSettings(c *http.Client, id, host string, s settings) error {
fBytes := []byte(populateForm(s).Encode())
req, err := http.NewRequest("POST", "http://"+host+settingsSubDir, bytes.NewReader(fBytes))
if err != nil {
return fmt.Errorf("could not create settings submit request: %v", err)
}
req.Header.Set("Connection", "keep-alive")
req.Header.Set("Content-Length", strconv.Itoa(len(fBytes)))
req.Header.Set("Cache-Control", "max-age=0")
req.Header.Set("Origin", "http://"+host)
req.Header.Set("Upgrade-Insecure-Requests", "1")
req.Header.Set("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36")
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3")
req.Header.Set("Referer", "http://"+host+"/ssi.cgi/VideoSettingSub.htm?cam=2")
req.Header.Set("Accept-Encoding", "gzip, deflate")
req.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Set("Cookie", "CLIENT_ID="+id)
// NB: not capturing error, as we always get one here for some reason.
// TODO: figure out why. Does not affect submission.
c.Do(req)
return nil
}

184
input/gvctrl/utils.go Normal file
View File

@ -0,0 +1,184 @@
/*
DESCRIPTION
utils.go provides general constants, structs and helper functions for use in
this package.
AUTHORS
Saxon A. Nelson-Milton <saxon@ausocean.org>
LICENSE
Copyright (C) 2019 the Australian Ocean Lab (AusOcean)
It is free software: you can redistribute it and/or modify them
under the terms of the GNU General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) any later version.
It is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
in gpl.txt. If not, see http://www.gnu.org/licenses.
*/
package gvctrl
import (
"crypto/md5"
"encoding/hex"
"math"
"net/url"
"strconv"
"strings"
)
// The strings used in encoding the settings form to indicate resultion.
const (
res256 = "4480256" // 480x256
res360 = "6400360" // 640x360
res720 = "12800720" // 1280x720
)
// Default values for fields in the settings struct when the newSettings
// constructor is used.
const (
defaultCodec = CodecH264
defaultRes = "6400360" // 360p
defaultFrameRate = "25000" // 25 fps
defaultVBR = "0" // Variable bitrate off
defaultQuality = QualityGood
defaultVBRBitrate = "250000" // 512 kbps (lowest with 360p)
defaultCBRBitrate = "512000"
defaultRefresh = "2000" // 2 seconds
)
// settings holds string representations required by the settings form for each
// of the parameters configurable through this API.
type settings struct {
codec Codec
res string
frameRate string
vbr string
quality Quality
vbrBitrate string
cbrBitrate string
refresh string
}
// newSetting will return a settings with default values.
func newSettings() settings {
return settings{
codec: defaultCodec,
res: defaultRes,
frameRate: defaultFrameRate,
vbr: defaultVBR,
quality: defaultQuality,
vbrBitrate: defaultVBRBitrate,
cbrBitrate: defaultCBRBitrate,
refresh: defaultRefresh,
}
}
// md5Hex returns the md5 hex string of s with alphanumerics as upper case.
func md5Hex(s string) string {
h := md5.New()
h.Write([]byte(s))
return strings.ToUpper(hex.EncodeToString(h.Sum(nil)))
}
// closestValIdx will return the index of the value in l that is closest to the
// value v.
func closestValIdx(v int, l []int) int {
var idx int
for i := range l {
if math.Abs(float64(l[i]-v)) < math.Abs(float64(l[idx]-v)) {
idx = i
}
}
return idx
}
// convRate is used to firstly find a value in l closest to the bitrate v (in
// kbps), convert from kbps to bps, and the convert to string.
func convRate(v int, l []int) string {
return strconv.Itoa(l[closestValIdx(v, l)] * 1000)
}
// populateForm will populate the settings form using the passed settings struct
// s and return as a url.Values.
func populateForm(s settings) url.Values {
f := url.Values{}
f.Set("dwConnType", "5")
f.Set("mpeg_type", string(s.codec))
f.Set("dwflicker_hz", "0")
f.Set("szResolution", s.res)
f.Set("dwFrameRate", s.frameRate)
f.Set("custom_qp_init", "25")
if s.codec == CodecMJPEG {
f.Set("vbr_enable", "1")
f.Set("dwVbrQuality", string(s.quality))
switch s.res {
case res256:
f.Set("vbrmaxbitrate", "250000")
case res360:
f.Set("vbrmaxbitrate", "500000")
case res720:
f.Set("vbrmaxbitrate", "750000")
default:
panic("invalid resolution")
}
} else {
switch s.vbr {
case "0":
f.Set("vbr_enable", "0")
f.Set("max_bit_rate", s.cbrBitrate)
case "1":
f.Set("vbr_enable", "1")
f.Set("dwVbrQuality", string(s.quality))
f.Set("vbrmaxbitrate", s.vbrBitrate)
default:
panic("invalid vbrEnable parameter")
}
f.Set("custom_rate_control_type", "0")
f.Set("custom_bitrate", "0")
f.Set("custom_qp_min", "10")
f.Set("custom_qp_max", "40")
}
f.Set("gop_N", s.refresh)
if s.codec == CodecMJPEG {
f.Set("gop_N", "1500")
}
if s.codec == CodecH264 || s.codec == CodecH265 {
f.Set("dwEncProfile", "1")
f.Set("dwEncLevel", "31")
f.Set("dwEntropy", "0")
}
f.Set("u8PreAlarmBuf", "1")
f.Set("u32PostAlarmBuf2Disk", "1")
f.Set("u8SplitInterval", "5")
f.Set("bEnableIO", "1")
f.Set("bEbIoIn", "1")
f.Set("bEbIoIn1", "1")
f.Set("bOSDFontSize", "0")
f.Set("bEnableOSDCameraName", "1")
f.Set("bCamNamePos", "2")
f.Set("bEnableOSDDate", "1")
f.Set("bDatePos", "2")
f.Set("bEnableOSDTime", "1")
f.Set("bTimePos", "2")
f.Set("szOsdCamName", "Camera")
f.Set("u16PostAlarmBuf", "1")
f.Set("dwCameraId", "1") // Channel=1 => cameraID=0 and chanel=2 => cameraID=1
f.Set("LangCode", "undefined")
f.Set("Recflag", "0")
f.Set("submit", "Apply")
return f
}