Fixing cosmetic stuff

This commit is contained in:
Unknown 2018-01-24 14:42:22 +10:30
parent 03335f3949
commit 40079c6346
3 changed files with 92 additions and 90 deletions

View File

@ -56,10 +56,15 @@ func (p* H264Parser)Stop(){
p.isParsing = false p.isParsing = false
} }
func (p* H264Parser)Parse() { func (p *H264Parser)Start(){
go p.parse()
}
func (p *H264Parser)parse() {
p.isParsing = true p.isParsing = true
outputBuffer := make([]byte, 0, 10000) outputBuffer := make([]byte, 0, 10000)
searchingForEnd := false searchingForEnd := false
p.InputByteChan = make(chan byte, 10000)
for p.isParsing { for p.isParsing {
aByte := <-p.InputByteChan aByte := <-p.InputByteChan
outputBuffer = append(outputBuffer, aByte) outputBuffer = append(outputBuffer, aByte)

View File

@ -51,33 +51,29 @@ import (
// defaults and networking consts // defaults and networking consts
const ( const (
clipDuration = 1 // s clipDuration = 1 // s
defaultPID = 256 mp2tPacketSize = 188 // MPEG-TS packet size
defaultFrameRate = 25 mp2tMaxPackets = 2016 * clipDuration // # first multiple of 7 and 8 greater than 2000
mp2tPacketSize = 188 // MPEG-TS packet size udpPackets = 7 // # of UDP packets per ethernet frame (8 is the max)
mp2tMaxPackets = 2016 * clipDuration // # first multiple of 7 and 8 greater than 2000 rtpPackets = 7 // # of RTP packets per ethernet frame (7 is the max)
udpPackets = 7 // # of UDP packets per ethernet frame (8 is the max) rtpHeaderSize = 12
rtpPackets = 7 // # of RTP packets per ethernet frame (7 is the max) rtpSSRC = 1 // any value will do
rtpHeaderSize = 12 bufferSize = 100 / clipDuration
rtpSSRC = 1 // any value will do httpTimeOut = 5 // s
bufferSize = 100 / clipDuration packetsPerFrame = 7
httpTimeOut = 5 // s h264BufferSize = 500000
motionThreshold = "0.0025" bitrateTime = 60
qscale = "3"
defaultRaspividCmd = "raspivid -o -"
framesPerSec = 25
packetsPerFrame = 7
h264BufferSize = 500000
bitrateTime = 60
) )
// Log Types
const ( const (
Error = "Error" Error = "Error"
Warning = "Warning" Warning = "Warning"
Info = "Info" Info = "Info"
Debug = "Debug" Debug = "Debug"
) )
// Config enums
const ( const (
Raspivid = 0 Raspivid = 0
Rtp = 1 Rtp = 1
@ -86,9 +82,6 @@ const (
HttpOut = 5 HttpOut = 5
) )
var cmd *exec.Cmd
var inputReader *bufio.Reader
type Config struct { type Config struct {
Input uint8 Input uint8
InputCmd string InputCmd string
@ -98,10 +91,10 @@ type Config struct {
Height string Height string
Width string Width string
Bitrate string Bitrate string
FrameRate string FrameRate string
HttpAddress string HttpAddress string
Quantization string Quantization string
Logger smartLogger.LogInstance Logger smartLogger.LogInstance
} }
type RevidInst interface { type RevidInst interface {
@ -125,10 +118,8 @@ type revidInst struct {
inputFile *os.File inputFile *os.File
generator tsgenerator.TsGenerator generator tsgenerator.TsGenerator
h264Parser h264.H264Parser h264Parser h264.H264Parser
} cmd *exec.Cmd
inputReader *bufio.Reader
func (r *revidInst) GetConfigRef() *Config{
return &r.config
} }
func NewRevidInstance(config Config) (r *revidInst, err error) { func NewRevidInstance(config Config) (r *revidInst, err error) {
@ -150,50 +141,51 @@ func NewRevidInstance(config Config) (r *revidInst, err error) {
return nil, err return nil, err
} }
} }
r.generator = tsgenerator.NewTsGenerator(framesPerSec) r.generator = tsgenerator.NewTsGenerator(r.config.FrameRate)
r.generator.Start()
r.h264Parser = h264.H264Parser{OutputChan: r.generator.GetNalInputChan()} r.h264Parser = h264.H264Parser{OutputChan: r.generator.GetNalInputChan()}
r.h264Parser.InputByteChan = make(chan byte, 10000) r.h264Parser.Start()
// TODO: Need to create constructor for parser otherwise I'm going to break
// something eventuallyl
go r.h264Parser.Parse()
go r.input() go r.input()
go r.generator.Generate()
r.Log(Info, "New revid instance created! config is:") r.Log(Info, "New revid instance created! config is:")
r.Log(Info, fmt.Sprintf("%v",r.config)) r.Log(Info, fmt.Sprintf("%v", r.config))
return return
} }
func (r *revidInst) GetConfigRef() *Config {
return &r.config
}
func (r *revidInst) ChangeState(newconfig Config) error { func (r *revidInst) ChangeState(newconfig Config) error {
// TODO: check that the config is G // TODO: check that the config is legit
r.config = newconfig r.config = newconfig
return nil return nil
} }
func (r *revidInst) Log(logType, m string){ func (r *revidInst) Log(logType, m string) {
r.config.Logger.Log(logType,m) r.config.Logger.Log(logType, m)
} }
func (r *revidInst)IsRunning() bool { func (r *revidInst) IsRunning() bool {
return r.isRunning return r.isRunning
} }
func (r *revidInst) Start() { func (r *revidInst) Start() {
if r.isRunning { if r.isRunning {
r.Log(Warning,"revidInst.Start() called but revid already running!") r.Log(Warning, "revidInst.Start() called but revid already running!")
return return
} }
r.Log(Info,"Starting Revid!") r.Log(Info, "Starting Revid!")
var h264Data []byte var h264Data []byte
switch r.config.Input { switch r.config.Input {
case Raspivid: case Raspivid:
r.Log(Info,"Starting raspivid!") r.Log(Info, "Starting raspivid!")
cmd = exec.Command("raspivid", "-o", "-", "-n", "-t", "0", "-b", cmd = exec.Command("raspivid", "-o", "-", "-n", "-t", "0", "-b",
r.config.Bitrate,"-qp", r.config.Quantization, "-w", r.config.Width, "-h", r.config.Height, "-fps", r.config.FrameRate, "-ih", "-g", "100") r.config.Bitrate, "-qp", r.config.Quantization, "-w", r.config.Width, "-h", r.config.Height, "-fps", r.config.FrameRate, "-ih", "-g", "100")
stdout, _ := cmd.StdoutPipe() stdout, _ := cmd.StdoutPipe()
err := cmd.Start() err := r.cmd.Start()
inputReader = bufio.NewReader(stdout) r.inputReader = bufio.NewReader(stdout)
if err != nil { if err != nil {
r.Log(Error,err.Error()) r.Log(Error, err.Error())
return return
} }
r.isRunning = true r.isRunning = true
@ -201,16 +193,14 @@ func (r *revidInst) Start() {
r.Log(Info, "Reading camera data!") r.Log(Info, "Reading camera data!")
for r.isRunning { for r.isRunning {
h264Data = make([]byte, 1) h264Data = make([]byte, 1)
_, err := io.ReadFull(inputReader, h264Data) _, err := io.ReadFull(r.inputReader, h264Data)
if err != nil { switch {
switch{ case err != nil && err.Error() == "EOF" && r.isRunning:
case err.Error() == "EOF" && r.isRunning: r.Log(Error, "No data from camera!")
r.Log(Error, "No data from camera!") time.Sleep(5 * time.Second)
time.Sleep(5*time.Second) case err != nil && r.isRunning:
case r.isRunning: r.Log(Error, err.Error())
r.Log(Error, err.Error()) default:
}
} else {
r.h264Parser.InputByteChan <- h264Data[0] r.h264Parser.InputByteChan <- h264Data[0]
} }
} }
@ -220,12 +210,15 @@ func (r *revidInst) Start() {
stats, err := r.inputFile.Stat() stats, err := r.inputFile.Stat()
if err != nil { if err != nil {
r.Log(Error, "Could not get input file stats!") r.Log(Error, "Could not get input file stats!")
r.Stop()
return return
} }
h264Data = make([]byte, stats.Size()) h264Data = make([]byte, stats.Size())
_, err = r.inputFile.Read(h264Data) _, err = r.inputFile.Read(h264Data)
if err != nil { if err != nil {
r.Log(Error, err.Error()) r.Log(Error, err.Error())
r.Stop()
return
} }
for i := range h264Data { for i := range h264Data {
r.h264Parser.InputByteChan <- h264Data[i] r.h264Parser.InputByteChan <- h264Data[i]
@ -236,11 +229,11 @@ func (r *revidInst) Start() {
func (r *revidInst) Stop() { func (r *revidInst) Stop() {
if r.isRunning { if r.isRunning {
r.Log(Info,"Stopping revid!") r.Log(Info, "Stopping revid!")
r.isRunning = false r.isRunning = false
cmd.Process.Kill() r.cmd.Process.Kill()
} else { } else {
r.Log(Warning,"revidInst.Stop() called but revid not running!") r.Log(Warning, "revidInst.Stop() called but revid not running!")
} }
} }
@ -251,22 +244,21 @@ func (r *revidInst) input() {
prevTime := now prevTime := now
for { for {
if clip, err := r.ringBuffer.Get(); err != nil { if clip, err := r.ringBuffer.Get(); err != nil {
r.Log(Error,err.Error()) r.Log(Error, err.Error())
r.Log(Warning,"Clearing tsPkt chan!") r.Log(Warning, "Clearing TS chan!")
tsPktChanLen := len(r.generator.GetTsOutputChan()) for len(r.generator.GetTsOutputChan()) > 0 {
for i := 0; i < tsPktChanLen; i++ {
<-(r.generator.GetTsOutputChan()) <-(r.generator.GetTsOutputChan())
} }
time.Sleep(1*time.Second) time.Sleep(1 * time.Second)
} else { } else {
for { for {
tsPacket := <-(r.generator.GetTsOutputChan()) tsPacket := <-(r.generator.GetTsOutputChan())
byteSlice, err := tsPacket.ToByteSlice() tsByteSlice, err := tsPacket.ToByteSlice()
if err != nil { if err != nil {
r.Log(Error,err.Error()) r.Log(Error, err.Error())
} }
upperBound := clipSize + mp2tPacketSize upperBound := clipSize + mp2tPacketSize
copy(clip[clipSize:upperBound], byteSlice) copy(clip[clipSize:upperBound], tsByteSlice)
packetCount++ packetCount++
clipSize += mp2tPacketSize clipSize += mp2tPacketSize
// send if (1) our buffer is full or (2) 1 second has elapsed and we have % packetsPerFrame // send if (1) our buffer is full or (2) 1 second has elapsed and we have % packetsPerFrame
@ -274,8 +266,8 @@ func (r *revidInst) input() {
if (packetCount == mp2tMaxPackets) || if (packetCount == mp2tMaxPackets) ||
(now.Sub(prevTime) > clipDuration*time.Second && packetCount%packetsPerFrame == 0) { (now.Sub(prevTime) > clipDuration*time.Second && packetCount%packetsPerFrame == 0) {
if err := r.ringBuffer.DoneWriting(clipSize); err != nil { if err := r.ringBuffer.DoneWriting(clipSize); err != nil {
r.Log(Error,err.Error()) r.Log(Error, err.Error())
r.Log(Warning,"Dropping clip!") r.Log(Warning, "Dropping clip!")
} }
clipSize = 0 clipSize = 0
packetCount = 0 packetCount = 0
@ -293,36 +285,37 @@ func (r *revidInst) output() {
bytes := 0 bytes := 0
delay := 0 delay := 0
for r.isRunning { for r.isRunning {
switch{ switch {
case r.ringBuffer.GetNoOfElements() < 2: case r.ringBuffer.GetNoOfElements() < 2:
delay++ delay++
time.Sleep(time.Duration(delay)*time.Millisecond) time.Sleep(time.Duration(delay) * time.Millisecond)
case delay > 10: case delay > 10:
delay -= 10 delay -= 10
} }
if clip, err := r.ringBuffer.Read(); err == nil { if clip, err := r.ringBuffer.Read(); err == nil {
r.Log(Debug,fmt.Sprintf("Delay is: %v\n", delay)) r.Log(Debug, fmt.Sprintf("Delay is: %v\n", delay))
r.Log(Debug, fmt.Sprintf("Ring buffer size: %v\n", r.ringBuffer.GetNoOfElements()))
switch r.config.Output { switch r.config.Output {
case File: case File:
r.outputFile.Write(clip) r.outputFile.Write(clip)
case HttpOut: case HttpOut:
bytes += len(clip) bytes += len(clip)
for err := r.sendClipToHTTP(clip, r.config.HttpAddress); err != nil; { for err := r.sendClipToHTTP(clip, r.config.HttpAddress); err != nil; {
r.Log(Error,err.Error()) r.Log(Error, err.Error())
r.Log(Warning,"Post failed trying again!") r.Log(Warning, "Post failed trying again!")
err = r.sendClipToHTTP(clip, r.config.HttpAddress) err = r.sendClipToHTTP(clip, r.config.HttpAddress)
} }
default: default:
r.Log(Error,"No output defined!") r.Log(Error, "No output defined!")
} }
if err := r.ringBuffer.DoneReading(); err != nil { if err := r.ringBuffer.DoneReading(); err != nil {
r.Log(Error,err.Error()) r.Log(Error, err.Error())
} }
now = time.Now() now = time.Now()
deltaTime := now.Sub(prevTime) deltaTime := now.Sub(prevTime)
if deltaTime > time.Duration(bitrateTime)*time.Second { if deltaTime > time.Duration(bitrateTime)*time.Second {
r.Log(Info,fmt.Sprintf("Bitrate: %v bits/s\n", int64(float64(bytes*8) / float64(deltaTime/1e9)))) r.Log(Info, fmt.Sprintf("Bitrate: %v bits/s\n", int64(float64(bytes*8)/float64(deltaTime/1e9))))
r.Log(Info,fmt.Sprintf("Ring buffer size: %v\n", r.ringBuffer.GetNoOfElements())) r.Log(Info, fmt.Sprintf("Ring buffer size: %v\n", r.ringBuffer.GetNoOfElements()))
prevTime = now prevTime = now
bytes = 0 bytes = 0
} }
@ -331,13 +324,13 @@ func (r *revidInst) output() {
} }
// sendClipToHTPP posts a video clip via HTTP, using a new TCP connection each time. // sendClipToHTPP posts a video clip via HTTP, using a new TCP connection each time.
func (r *revidInst)sendClipToHTTP(clip []byte, output string) error { func (r *revidInst) sendClipToHTTP(clip []byte, output string) error {
timeout := time.Duration(httpTimeOut * time.Second) timeout := time.Duration(httpTimeOut * time.Second)
client := http.Client{ client := http.Client{
Timeout: timeout, Timeout: timeout,
} }
url := output + strconv.Itoa(len(clip)) url := output + strconv.Itoa(len(clip))
r.Log(Debug,fmt.Sprintf("Posting %s (%d bytes)\n", url, len(clip))) r.Log(Debug, fmt.Sprintf("Posting %s (%d bytes)\n", url, len(clip)))
resp, err := client.Post(url, "video/mp2t", bytes.NewReader(clip)) // lighter than NewBuffer resp, err := client.Post(url, "video/mp2t", bytes.NewReader(clip)) // lighter than NewBuffer
if err != nil { if err != nil {
return fmt.Errorf("Error posting to %s: %s", output, err) return fmt.Errorf("Error posting to %s: %s", output, err)
@ -345,9 +338,9 @@ func (r *revidInst)sendClipToHTTP(clip []byte, output string) error {
defer resp.Body.Close() defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body) body, err := ioutil.ReadAll(resp.Body)
if err == nil { if err == nil {
r.Log(Debug,fmt.Sprintf("%s\n", body)) r.Log(Debug, fmt.Sprintf("%s\n", body))
} else { } else {
r.Log(Error,err.Error()) r.Log(Error, err.Error())
} }
return nil return nil
} }

View File

@ -51,7 +51,7 @@ const (
) )
type TsGenerator interface { type TsGenerator interface {
Generate() generate()
GetNalInputChan() chan<- []byte GetNalInputChan() chan<- []byte
GetTsOutputChan() <-chan *mpegts.MpegTsPacket GetTsOutputChan() <-chan *mpegts.MpegTsPacket
} }
@ -118,7 +118,11 @@ func (g *tsGenerator) genPcr()(pcr uint64){
return return
} }
func (g *tsGenerator) Generate() { func (g *tsGenerator) Start(){
go g.generate()
}
func (g *tsGenerator) generate() {
var rtpBuffer [](*rtp.RtpPacket) var rtpBuffer [](*rtp.RtpPacket)
for { for {
select { select {