av/revid/senders.go

480 lines
11 KiB
Go
Raw Normal View History

2018-06-09 07:38:48 +03:00
/*
NAME
senders.go
DESCRIPTION
See Readme.md
AUTHORS
Saxon A. Nelson-Milton <saxon@ausocean.org>
Alan Noble <alan@ausocean.org>
LICENSE
revid is Copyright (C) 2017-2018 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
along with revid in gpl.txt. If not, see http://www.gnu.org/licenses.
*/
package revid
import (
"errors"
"fmt"
"io"
"net"
2018-06-09 07:38:48 +03:00
"os"
"strconv"
2018-06-09 07:38:48 +03:00
"github.com/Comcast/gots/packet"
2019-03-25 04:21:03 +03:00
"bitbucket.org/ausocean/av/container/mts"
"bitbucket.org/ausocean/av/protocol/rtmp"
"bitbucket.org/ausocean/av/protocol/rtp"
"bitbucket.org/ausocean/iot/pi/netsender"
"bitbucket.org/ausocean/utils/logger"
2018-06-09 07:38:48 +03:00
)
// Sender is intended to provided functionality for the sending of a byte slice
// to an implemented destination.
type Sender interface {
// send takes the bytes slice d and sends to a particular destination as
// implemented.
send(d []byte) error
}
2019-03-24 12:34:35 +03:00
// Log is used by the multiSender.
type Log func(level int8, message string, params ...interface{})
// multiSender implements io.Writer. It provides the capacity to send to multiple
// senders from a single Write call.
type multiSender struct {
senders []io.Writer
log Log
}
2019-03-24 12:34:35 +03:00
// newMultiSender returns a pointer to a new multiSender.
func newMultiSender(senders []io.Writer, log Log) *multiSender {
return &multiSender{
senders: senders,
log: log,
}
}
// Write implements io.Writer. This will call load (with the passed slice), send
// and release on all senders of multiSender.
func (s *multiSender) Write(d []byte) (int, error) {
for i, sender := range s.senders {
_, err := sender.Write(d)
if err != nil {
s.log(logger.Warning, pkg+"send failed", "sender", i, "error", err)
2019-03-09 07:58:07 +03:00
}
}
for _, sender := range s.senders {
s, ok := sender.(loadSender)
if !ok {
panic("sender is not a loadSender")
}
s.release()
2019-03-09 07:58:07 +03:00
}
return len(d), nil
}
// minimalHttpSender implements Sender for posting HTTP to netreceiver or vidgrind.
type minimalHttpSender struct {
client *netsender.Sender
log func(lvl int8, msg string, args ...interface{})
}
// newMinimalHttpSender returns a pointer to a new minimalHttpSender.
func newMinimalHttpSender(ns *netsender.Sender, log func(lvl int8, msg string, args ...interface{})) *minimalHttpSender {
return &minimalHttpSender{
client: ns,
log: log,
}
}
// send takes a bytes slice d and sends to http using s' http client.
func (s *minimalHttpSender) send(d []byte) error {
return httpSend(d, s.client, s.log)
}
2018-06-09 07:38:48 +03:00
// loadSender is a destination to send a *ring.Chunk to.
// When a loadSender has finished using the *ring.Chunk
// it must be Closed.
type loadSender interface {
2019-03-29 05:59:31 +03:00
// load assigns the *ring.Chunk to the loadSender.
// The load call may fail, but must not mutate the
// the chunk.
2019-03-09 07:58:07 +03:00
load(d []byte) error
2018-06-09 07:38:48 +03:00
2019-03-29 05:59:31 +03:00
// send performs a destination-specific send
// operation. It must not mutate the chunk.
2018-06-09 07:38:48 +03:00
send() error
// release releases the *ring.Chunk.
release()
// close cleans up after use of the loadSender.
close() error
}
// restart is an optional interface for loadSenders that
// can restart their connection.
type restarter interface {
restart() error
}
// fileSender implements loadSender for a local file destination.
type fileSender struct {
file *os.File
2019-03-09 07:58:07 +03:00
data []byte
2018-06-09 07:38:48 +03:00
}
2019-03-29 05:59:31 +03:00
// Write implements io.Writer. This will attempt to load and send the data given.
func (s *fileSender) Write(d []byte) (int, error) {
err := s.load(d)
if err != nil {
return 0, err
}
err = s.send()
if err != nil {
return len(d), err
}
return len(d), nil
}
func newFileSender(path string) (io.Writer, error) {
2018-06-09 07:38:48 +03:00
f, err := os.Create(path)
if err != nil {
return nil, err
}
return &fileSender{file: f}, nil
}
2019-03-09 07:58:07 +03:00
func (s *fileSender) load(d []byte) error {
s.data = d
2018-06-09 07:38:48 +03:00
return nil
}
func (s *fileSender) send() error {
2019-03-09 07:58:07 +03:00
_, err := s.file.Write(s.data)
2018-06-09 07:38:48 +03:00
return err
}
2019-03-09 07:58:07 +03:00
func (s *fileSender) release() {}
2018-06-09 07:38:48 +03:00
func (s *fileSender) close() error { return s.file.Close() }
2018-06-09 07:38:48 +03:00
// mtsSender implements loadSender and provides sending capability specifically
// for use with MPEGTS packetization. It handles the construction of appropriately
// lengthed clips based on PSI. It also fixes accounts for discontinuities by
// setting the discontinuity indicator for the first packet of a clip.
type mtsSender struct {
sender Sender
buf []byte
next []byte
2019-03-01 07:18:26 +03:00
pkt packet.Packet
failed bool
discarded bool
repairer *mts.DiscontinuityRepairer
curPid int
}
2019-03-29 05:59:31 +03:00
// Write implements io.Writer. This will attempt to load and send the data given.
func (s *mtsSender) Write(d []byte) (int, error) {
return write(s, d)
}
// newMtsSender returns a new mtsSender.
func newMtsSender(s Sender, log func(lvl int8, msg string, args ...interface{})) *mtsSender {
return &mtsSender{
sender: s,
repairer: mts.NewDiscontinuityRepairer(),
}
}
// load takes a *ring.Chunk and assigns to s.next, also grabbing it's pid and
// assigning to s.curPid. s.next if exists is also appended to the sender buf.
2019-03-09 07:58:07 +03:00
func (s *mtsSender) load(d []byte) error {
if s.next != nil {
s.buf = append(s.buf, s.next...)
}
2019-03-09 07:58:07 +03:00
bytes := make([]byte, len(d))
copy(bytes, d)
2019-03-01 07:44:01 +03:00
s.next = bytes
copy(s.pkt[:], bytes)
2019-03-01 07:18:26 +03:00
s.curPid = s.pkt.PID()
return nil
}
// send checks the currently loaded paackets PID; if it is a PAT then what is in
// the mtsSenders buffer is fixed and sent.
2019-03-01 07:44:01 +03:00
func (ms *mtsSender) send() error {
if ms.curPid == mts.PatPid && len(ms.buf) > 0 {
err := ms.fixAndSend()
if err != nil {
return err
}
2019-03-01 07:44:01 +03:00
ms.buf = ms.buf[:0]
}
return nil
}
// fixAndSend checks for discontinuities in the senders buffer and then sends.
// If a discontinuity is found the PAT packet at the start of the clip has it's
// discontintuity indicator set to true.
func (ms *mtsSender) fixAndSend() error {
err := ms.repairer.Repair(ms.buf)
2019-03-01 07:44:01 +03:00
if err == nil {
err = ms.sender.send(ms.buf)
if err == nil {
return nil
}
}
2019-03-01 07:44:01 +03:00
ms.failed = true
ms.repairer.Failed()
return err
}
func (s *mtsSender) close() error { return nil }
// release will set the s.fail flag to false and clear the buffer if
// the previous send was a fail. The currently loaded chunk is also closed.
func (s *mtsSender) release() {
if s.failed {
s.buf = s.buf[:0]
s.failed = false
}
}
// httpSender implements loadSender for posting HTTP to NetReceiver
2018-06-09 07:38:48 +03:00
type httpSender struct {
client *netsender.Sender
2018-06-09 07:38:48 +03:00
2018-09-11 10:45:45 +03:00
log func(lvl int8, msg string, args ...interface{})
2018-06-09 07:38:48 +03:00
2019-03-09 07:58:07 +03:00
data []byte
2018-06-09 07:38:48 +03:00
}
2018-09-11 10:45:45 +03:00
func newHttpSender(ns *netsender.Sender, log func(lvl int8, msg string, args ...interface{})) *httpSender {
2018-06-09 07:38:48 +03:00
return &httpSender{
client: ns,
2018-06-09 07:38:48 +03:00
log: log,
}
}
2019-03-09 07:58:07 +03:00
func (s *httpSender) load(d []byte) error {
s.data = d
2018-06-09 07:38:48 +03:00
return nil
}
2018-06-27 01:20:05 +03:00
func (s *httpSender) send() error {
2019-03-09 07:58:07 +03:00
return httpSend(s.data, s.client, s.log)
}
func httpSend(d []byte, client *netsender.Sender, log func(lvl int8, msg string, args ...interface{})) error {
// Only send if "V0" is configured as an input.
send := false
ip := client.Param("ip")
pins := netsender.MakePins(ip, "V")
for i, pin := range pins {
if pin.Name == "V0" {
send = true
pins[i].Value = len(d)
pins[i].Data = d
pins[i].MimeType = "video/mp2t"
break
}
}
if !send {
return nil
}
var err error
var reply string
reply, _, err = client.Send(netsender.RequestRecv, pins)
if err != nil {
return err
}
return extractMeta(reply, log)
}
2018-12-14 09:16:36 +03:00
// extractMeta looks at a reply at extracts any time or location data - then used
// to update time and location information in the mpegts encoder.
func extractMeta(r string, log func(lvl int8, msg string, args ...interface{})) error {
dec, err := netsender.NewJSONDecoder(r)
if err != nil {
return nil
}
// Extract time from reply
t, err := dec.Int("ts")
if err != nil {
log(logger.Warning, pkg+"No timestamp in reply")
} else {
log(logger.Debug, fmt.Sprintf("%v got timestamp: %v", pkg, t))
mts.Meta.Add("ts", strconv.Itoa(t))
}
// Extract location from reply
g, err := dec.String("ll")
if err != nil {
log(logger.Warning, pkg+"No location in reply")
} else {
log(logger.Debug, fmt.Sprintf("%v got location: %v", pkg, g))
mts.Meta.Add("loc", g)
}
return nil
}
2019-03-09 07:58:07 +03:00
func (s *httpSender) release() {}
2018-06-09 07:38:48 +03:00
func (s *httpSender) close() error { return nil }
// rtmpSender implements loadSender for a native RTMP destination.
type rtmpSender struct {
conn *rtmp.Conn
2018-06-09 07:38:48 +03:00
url string
timeout uint
retries int
2018-09-11 10:45:45 +03:00
log func(lvl int8, msg string, args ...interface{})
2018-06-09 07:38:48 +03:00
data []byte
2018-06-09 07:38:48 +03:00
}
var _ restarter = (*rtmpSender)(nil)
2018-09-11 10:45:45 +03:00
func newRtmpSender(url string, timeout uint, retries int, log func(lvl int8, msg string, args ...interface{})) (*rtmpSender, error) {
var conn *rtmp.Conn
2018-06-09 07:38:48 +03:00
var err error
for n := 0; n < retries; n++ {
conn, err = rtmp.Dial(url, timeout, log)
2018-06-09 07:38:48 +03:00
if err == nil {
break
}
log(logger.Error, err.Error())
2018-06-09 07:38:48 +03:00
if n < retries-1 {
log(logger.Info, pkg+"retry rtmp connection")
2018-06-09 07:38:48 +03:00
}
}
s := &rtmpSender{
conn: conn,
2018-06-09 07:38:48 +03:00
url: url,
timeout: timeout,
retries: retries,
log: log,
}
return s, err
2018-06-09 07:38:48 +03:00
}
2019-03-29 05:59:31 +03:00
// Write implements io.Writer. This will attempt to load and send the data given.
func (s *rtmpSender) Write(d []byte) (int, error) {
return write(s, d)
}
2019-03-09 07:58:07 +03:00
func (s *rtmpSender) load(d []byte) error {
s.data = d
2018-06-09 07:38:48 +03:00
return nil
}
func (s *rtmpSender) send() error {
if s.conn == nil {
return errors.New("no rtmp connection, cannot write")
}
2019-03-09 07:58:07 +03:00
_, err := s.conn.Write(s.data)
if err != nil {
err = s.restart()
}
2018-06-09 07:38:48 +03:00
return err
}
2019-03-09 07:58:07 +03:00
func (s *rtmpSender) release() {}
2018-06-09 07:38:48 +03:00
func (s *rtmpSender) restart() error {
s.close()
2019-03-03 10:11:35 +03:00
var err error
2018-06-09 07:38:48 +03:00
for n := 0; n < s.retries; n++ {
s.conn, err = rtmp.Dial(s.url, s.timeout, s.log)
2018-06-09 07:38:48 +03:00
if err == nil {
break
}
s.log(logger.Error, err.Error())
2018-06-09 07:38:48 +03:00
if n < s.retries-1 {
s.log(logger.Info, pkg+"retry rtmp connection")
2018-06-09 07:38:48 +03:00
}
}
return err
}
func (s *rtmpSender) close() error {
if s.conn != nil {
return s.conn.Close()
}
return nil
2018-06-09 07:38:48 +03:00
}
// TODO: Write restart func for rtpSender
// rtpSender implements loadSender for a native udp destination with rtp packetization.
type rtpSender struct {
log func(lvl int8, msg string, args ...interface{})
encoder *rtp.Encoder
2019-03-09 07:58:07 +03:00
data []byte
}
2019-03-29 05:59:31 +03:00
// Write implements io.Writer. This will attempt to load and send the data given.
func (s *rtpSender) Write(d []byte) (int, error) {
return write(s, d)
}
func newRtpSender(addr string, log func(lvl int8, msg string, args ...interface{}), fps uint) (*rtpSender, error) {
conn, err := net.Dial("udp", addr)
if err != nil {
return nil, err
}
s := &rtpSender{
log: log,
encoder: rtp.NewEncoder(conn, int(fps)),
}
return s, nil
}
2019-03-09 07:58:07 +03:00
func (s *rtpSender) load(d []byte) error {
s.data = make([]byte, len(d))
copy(s.data, d)
return nil
}
func (s *rtpSender) close() error { return nil }
2019-03-09 07:58:07 +03:00
func (s *rtpSender) release() {}
func (s *rtpSender) send() error {
2019-03-09 07:58:07 +03:00
_, err := s.encoder.Write(s.data)
return err
}
2019-03-29 05:59:31 +03:00
// write wraps the load and send method for loadSenders.
func write(s loadSender, d []byte) (int, error) {
err := s.load(d)
if err != nil {
return 0, err
}
err = s.send()
if err != nil {
return len(d), err
}
return len(d), nil
}