Improved error reporting and other changes to make more Go idiomatic.

This commit is contained in:
Alan Noble 2017-09-21 13:36:54 +09:30
parent d0e796f47d
commit b54068e0a2
1 changed files with 81 additions and 116 deletions

View File

@ -40,6 +40,7 @@ import (
"math/rand" "math/rand"
"net" "net"
"net/http" "net/http"
"os"
"os/exec" "os/exec"
"strconv" "strconv"
"strings" "strings"
@ -50,32 +51,23 @@ import (
"github.com/Comcast/gots/psi" "github.com/Comcast/gots/psi"
) )
// program modes
const (
File = iota
HTTP
UDP
RTP
Dump
)
// defaults and networking consts // defaults and networking consts
const ( const (
defaultPid = 256 defaultPID = 256
defaultFrameRate = 25 defaultFrameRate = 25
defaultHTTPOutput = "http://localhost:8080?" defaultHTTPOutput = "http://localhost:8080?"
defaultUDPOutput = "udp://0.0.0.0:16384" defaultUDPOutput = "udp://0.0.0.0:16384"
defaultRTPOutput = "rtp://0.0.0.0:16384" defaultRTPOutput = "rtp://0.0.0.0:16384"
mp2tPacketSize = 188 // MPEG-TS packet size mp2tPacketSize = 188 // MPEG-TS packet size
mp2tMaxPackets = 2016 // # first multiple of 7 and 8 greater than 2000 mp2tMaxPackets = 2016 // # first multiple of 7 and 8 greater than 2000
UDPPackets = 7 // # of UDP packets per ethernet frame (8 is the max) udpPackets = 7 // # of UDP packets per ethernet frame (8 is the max)
RTPPackets = 7 // # of RTP packets per ethernet frame (7 is the max) rtpPackets = 7 // # of RTP packets per ethernet frame (7 is the max)
RTPHeaderSize = 12 rtpHeaderSize = 12
RTPSSRC = 1 // any value will do rtpSSRC = 1 // any value will do
ffmpegPath = "/usr/bin/ffmpeg" ffmpegPath = "/usr/bin/ffmpeg"
) )
// flags // flag values
const ( const (
filterFixPTS = 0x0001 filterFixPTS = 0x0001
filterDropAudio = 0x0002 filterDropAudio = 0x0002
@ -91,27 +83,25 @@ const (
// globals // globals
var ( var (
sendClip = sendClipToRTP sendClip = sendClipToRTP
packetsPerFrame = RTPPackets packetsPerFrame = rtpPackets
flags *int
frameRate *int
selectedPid *int
clipCount int clipCount int
expectCC int expectCC int
dumpCC int dumpCC int
dumpPcrBase uint64 dumpPCRBase uint64
RTPSequenceNum uint16 RTPSequenceNum uint16
) )
func main() { // command-line flags
var ( var (
input = flag.String("i", "", "Input RTSP URL") input = flag.String("i", "", "Input RTSP URL")
output = flag.String("o", "", "Output URL (HTTP, UDP or RTP)") output = flag.String("o", "", "Output URL (HTTP, UDP or RTP)")
mode = flag.String("m", "r", "Mode: one of f,h,u,r or d") mode = flag.String("m", "r", "Mode: one of f,h,u,r or d")
) flags = flag.Int("f", 0, "Flags: see readme for explanation")
flags = flag.Int("f", 0, "Flags: see readme for explanation") frameRate = flag.Int("r", defaultFrameRate, "Input video frame rate (25fps by default)")
frameRate = flag.Int("r", defaultFrameRate, "Input video frame rate (25fps by default)") selectedPID = flag.Int("p", defaultPID, "Select packets with this packet ID (PID)")
selectedPid = flag.Int("p", defaultPid, "Select packets with this packet ID (PID)") )
func main() {
flag.Parse() flag.Parse()
if *input == "" { if *input == "" {
@ -128,20 +118,20 @@ func main() {
} }
case "u": case "u":
sendClip = sendClipToUDP sendClip = sendClipToUDP
packetsPerFrame = UDPPackets packetsPerFrame = udpPackets
if *output == "" { if *output == "" {
*output = defaultUDPOutput *output = defaultUDPOutput
} }
case "r": case "r":
sendClip = sendClipToRTP sendClip = sendClipToRTP
packetsPerFrame = RTPPackets packetsPerFrame = rtpPackets
if *output == "" { if *output == "" {
*output = defaultRTPOutput *output = defaultRTPOutput
} }
case "d": case "d":
sendClip = sendClipToStdout sendClip = sendClipToStdout
default: default:
log.Fatal("Invalid mode %s\n", *mode) log.Fatalf("Invalid mode %s\n", *mode)
} }
if *flags&filterFixContinuity != 0 && *flags&dumpProgramInfo != 0 { if *flags&filterFixContinuity != 0 && *flags&dumpProgramInfo != 0 {
@ -149,9 +139,10 @@ func main() {
} }
for { for {
_ = readWriteVideo(*input, *output) err := readWriteVideo(*input, *output)
fmt.Printf("Trying again in 10s\n") fmt.Fprintln(os.Stderr, err)
time.Sleep(1e10 * time.Nanosecond) fmt.Fprintln(os.Stderr, "Trying again in 10s")
time.Sleep(10 * time.Second)
} }
} }
@ -160,78 +151,59 @@ func main() {
func readWriteVideo(input string, output string) error { func readWriteVideo(input string, output string) error {
fmt.Printf("Reading video from %s\n", input) fmt.Printf("Reading video from %s\n", input)
var videoArg, audioArg [2]string args := []string{
"-r", strconv.Itoa(*frameRate),
"-i", input,
}
if *flags&(filterFixPTS|filterScale640|filterScale320) == 0 { if *flags&(filterFixPTS|filterScale640|filterScale320) == 0 {
videoArg[0] = "-vcodec" args = append(args, "-vcodec", "copy")
videoArg[1] = "copy"
} else { } else {
videoArg[0] = "-vf" vfArg := []string{}
videoArg[1] = ""
if *flags&filterFixPTS != 0 { if *flags&filterFixPTS != 0 {
videoArg[1] += "setpts='PTS-STARTPTS'" // start counting PTS from zero vfArg = append(vfArg, "setpts='PTS-STARTPTS'") // start counting PTS from zero
} }
if *flags&filterScale640 != 0 { if *flags&filterScale640 != 0 {
videoArg[1] += ", scale=640:352" vfArg = append(vfArg, "scale=640:352")
} else if *flags&filterScale320 != 0 { } else if *flags&filterScale320 != 0 {
videoArg[1] += ", scale=320:176" vfArg = append(vfArg, "scale=320:176")
} }
args = append(args, "-vf", strings.Join(vfArg, ","))
} }
if *flags&filterDropAudio == 0 { if *flags&filterDropAudio == 0 {
audioArg[0] = "-acodec" args = append(args, "-acodec", "copy")
audioArg[1] = "copy"
} else { } else {
audioArg[0] = "-an" args = append(args, "-an")
audioArg[1] = ""
}
fmt.Printf("Executing: %s -r %d -i %s %s \"%s\" %s %s -f mpegts -\n",
ffmpegPath, *frameRate, input, videoArg[0], videoArg[1], audioArg[0], audioArg[1])
var cmd *exec.Cmd
if audioArg[1] == "" {
cmd = exec.Command(ffmpegPath,
"-r", strconv.Itoa(*frameRate),
"-i", input,
videoArg[0], videoArg[1],
audioArg[0],
"-f", "mpegts", "-")
} else {
cmd = exec.Command(ffmpegPath,
"-r", strconv.Itoa(*frameRate),
"-i", input,
videoArg[0], videoArg[1],
audioArg[0], audioArg[1],
"-f", "mpegts", "-")
} }
args = append(args, "-f", "mpegts", "-")
fmt.Printf("Executing: %s %s\n", ffmpegPath, strings.Join(args, " "))
cmd := exec.Command(ffmpegPath, args...)
stdout, err := cmd.StdoutPipe() stdout, err := cmd.StdoutPipe()
if err != nil { if err != nil {
fmt.Printf("Error creating pipe: %s\n", err) return fmt.Errorf("Error creating pipe: %s", err)
return err
} }
err = cmd.Start() err = cmd.Start()
if err != nil { if err != nil {
fmt.Printf("Error starting pipe: %s\n", err) return fmt.Errorf("Error starting pipe: %s", err)
return err
} }
// (re)initialize globals // (re)initialize globals
clipCount = 0 clipCount = 0
expectCC = -1 expectCC = -1
dumpCC = -1 dumpCC = -1
dumpPcrBase = 0 dumpPCRBase = 0
RTPSequenceNum = uint16(rand.Intn(1 << 15)) RTPSequenceNum = uint16(rand.Intn(1 << 15))
// for UDP and RTP only dial once // for UDP and RTP only dial once
var conn net.Conn var conn net.Conn
if strings.Index(output, "udp://") == 0 || strings.Index(output, "rtp://") == 0 { if strings.HasPrefix(output, "udp://") || strings.HasPrefix(output, "rtp://") {
conn, err = net.Dial("udp", output[6:]) conn, err = net.Dial("udp", output[6:])
if err != nil { if err != nil {
fmt.Printf("Error dialing %s: %s\n", output, err) return fmt.Errorf("Error dialing %s: %s", output, err)
return err
} }
defer conn.Close() defer conn.Close()
} }
@ -241,17 +213,17 @@ func readWriteVideo(input string, output string) error {
clip := make([]byte, mp2tMaxPackets*mp2tPacketSize) clip := make([]byte, mp2tMaxPackets*mp2tPacketSize)
clipSize := 0 clipSize := 0
packetCount := 0 packetCount := 0
prevTime := time.Now() now := time.Now()
prevTime := now
fmt.Printf("Looping\n") fmt.Printf("Looping\n")
for { for {
_, err := io.ReadFull(br, pkt) _, err := io.ReadFull(br, pkt)
if err != nil { if err != nil {
fmt.Printf("Error reading from ffmpeg: %s\n", err) return fmt.Errorf("Error reading from ffmpeg: %s", err)
return err
} }
if *flags&filterFixContinuity != 0 && mp2tFixContinuity(pkt, packetCount, (uint16)(*selectedPid)) { if *flags&filterFixContinuity != 0 && mp2tFixContinuity(pkt, packetCount, uint16(*selectedPID)) {
fmt.Printf("Packet #%d.%d fixed\n", clipCount, packetCount) fmt.Printf("Packet #%d.%d fixed\n", clipCount, packetCount)
} }
copy(clip[clipSize:], pkt) copy(clip[clipSize:], pkt)
@ -259,15 +231,16 @@ func readWriteVideo(input string, output string) error {
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
now = time.Now()
if (packetCount == mp2tMaxPackets) || if (packetCount == mp2tMaxPackets) ||
(time.Now().Sub(prevTime) > 1*time.Second && packetCount%packetsPerFrame == 0) { (now.Sub(prevTime) > 1*time.Second && packetCount%packetsPerFrame == 0) {
clipCount++ clipCount++
if err = sendClip(clip[:clipSize], output, conn); err != nil { if err = sendClip(clip[:clipSize], output, conn); err != nil {
return err return err
} }
clipSize = 0 clipSize = 0
packetCount = 0 packetCount = 0
prevTime = time.Now() prevTime = now
} }
} }
return nil return nil
@ -279,40 +252,36 @@ func sendClipToFile(clip []byte, _ string, _ net.Conn) error {
fmt.Printf("Writing %s (%d bytes)\n", filename, len(clip)) fmt.Printf("Writing %s (%d bytes)\n", filename, len(clip))
err := ioutil.WriteFile(filename, clip, 0644) err := ioutil.WriteFile(filename, clip, 0644)
if err != nil { if err != nil {
fmt.Printf("Error writing file %s: %s\n", filename, err) return fmt.Errorf("Error writing file %s: %s", filename, err)
return err
} }
return nil return nil
} }
// 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 sendClipToHTTP(clip []byte, output string, _ net.Conn) error { func sendClipToHTTP(clip []byte, output string, _ net.Conn) error {
URL := output + strconv.Itoa(len(clip)) // NB: append the size to the output url := output + strconv.Itoa(len(clip)) // NB: append the size to the output
fmt.Printf("Posting %s (%d bytes)\n", URL, len(clip)) fmt.Printf("Posting %s (%d bytes)\n", url, len(clip))
resp, err := http.Post(URL, "video/mp2t", bytes.NewReader(clip)) // lighter than NewBuffer resp, err := http.Post(url, "video/mp2t", bytes.NewReader(clip)) // lighter than NewBuffer
if err != nil { if err != nil {
fmt.Printf("Error posting to %s: %s\n", output, err) return fmt.Errorf("Error posting to %s: %s", output, err)
return err
} }
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 {
fmt.Printf(string(body) + "\n") fmt.Printf("%s\n", body)
} }
return err return err
} }
// sendClipToUDP sends a video clip over UDP. // sendClipToUDP sends a video clip over UDP.
func sendClipToUDP(clip []byte, _ string, conn net.Conn) error { func sendClipToUDP(clip []byte, _ string, conn net.Conn) error {
size := UDPPackets * mp2tPacketSize size := udpPackets * mp2tPacketSize
fmt.Printf("Sending %d UDP packets of size %d (%d bytes)\n", len(clip)/size, size, len(clip)) fmt.Printf("Sending %d UDP packets of size %d (%d bytes)\n", len(clip)/size, size, len(clip))
for offset := 0; offset < len(clip); offset += size { for offset := 0; offset < len(clip); offset += size {
pkt := clip[offset : offset+size] pkt := clip[offset : offset+size]
_, err := conn.Write(pkt) _, err := conn.Write(pkt)
if err != nil { if err != nil {
fmt.Printf("UDP write error %s. Is your player listening?\n", err) return fmt.Errorf("UDP write error %s. Is your player listening?", err)
return err
} }
} }
return nil return nil
@ -320,16 +289,15 @@ func sendClipToUDP(clip []byte, _ string, conn net.Conn) error {
// sendClipToRTP sends a video clip over RTP. // sendClipToRTP sends a video clip over RTP.
func sendClipToRTP(clip []byte, _ string, conn net.Conn) error { func sendClipToRTP(clip []byte, _ string, conn net.Conn) error {
size := RTPPackets * mp2tPacketSize size := rtpPackets * mp2tPacketSize
fmt.Printf("Sending %d RTP packets of size %d (%d bytes)\n", fmt.Printf("Sending %d RTP packets of size %d (%d bytes)\n",
len(clip)/size, size+RTPHeaderSize, len(clip)) len(clip)/size, size+rtpHeaderSize, len(clip))
pkt := make([]byte, RTPHeaderSize+RTPPackets*mp2tPacketSize) pkt := make([]byte, rtpHeaderSize+rtpPackets*mp2tPacketSize)
for offset := 0; offset < len(clip); offset += size { for offset := 0; offset < len(clip); offset += size {
RTPEncapsulate(clip[offset:offset+size], pkt) RTPEncapsulate(clip[offset:offset+size], pkt)
_, err := conn.Write(pkt) _, err := conn.Write(pkt)
if err != nil { if err != nil {
fmt.Printf("RTP write error %s. Is your player listening?\n", err) return fmt.Errorf("RTP write error %s. Is your player listening?", err)
return err
} }
} }
return nil return nil
@ -351,11 +319,11 @@ func sendClipToStdout(clip []byte, _ string, _ net.Conn) error {
packetCount++ packetCount++
pkt := clip[offset : offset+mp2tPacketSize] pkt := clip[offset : offset+mp2tPacketSize]
pktPid, err := packet.Pid(pkt) pktPID, err := packet.Pid(pkt)
if err != nil { if err != nil {
return err return err
} }
if pktPid != (uint16)(*selectedPid) { if pktPID != uint16(*selectedPID) {
continue continue
} }
@ -391,14 +359,14 @@ func sendClipToStdout(clip []byte, _ string, _ net.Conn) error {
// adaptation field, followed by payload // adaptation field, followed by payload
afl := adaptationfield.Length(pkt) afl := adaptationfield.Length(pkt)
if adaptationfield.HasPCR(pkt) { if adaptationfield.HasPCR(pkt) {
pcrBase, pcrExt, _ := mp2tGetPcr(pkt) pcrBase, pcrExt, _ := mp2tGetPCR(pkt)
if *flags&dumpPacketHeader != 0 { if *flags&dumpPacketHeader != 0 {
fmt.Printf("\t\tAFL=%d, PCRbase=%d, PCRext=%d\n", afl, pcrBase, pcrExt) fmt.Printf("\t\tAFL=%d, PCRbase=%d, PCRext=%d\n", afl, pcrBase, pcrExt)
} }
if pcrBase < dumpPcrBase { if pcrBase < dumpPCRBase {
fmt.Printf("Warning: PCRbase went backwards!\n") fmt.Printf("Warning: PCRbase went backwards!\n")
} }
dumpPcrBase = pcrBase dumpPCRBase = pcrBase
} else if *flags&dumpPacketHeader != 0 { } else if *flags&dumpPacketHeader != 0 {
fmt.Printf("\t\tAFL=%d\n", afl) fmt.Printf("\t\tAFL=%d\n", afl)
} }
@ -422,13 +390,11 @@ func mp2tDumpProgram(clip []byte) error {
_, err := packet.Sync(reader) _, err := packet.Sync(reader)
if err != nil { if err != nil {
fmt.Println("Warning: Bad MPEG-TS sync byte") return fmt.Errorf("Error reading sync byte: %s", err)
return err
} }
pat, err := psi.ReadPAT(reader) pat, err := psi.ReadPAT(reader)
if err != nil { if err != nil {
fmt.Printf("ReadPAT error: %s\n", err) return fmt.Errorf("Error reading PAT: %s", err)
return err
} }
mp2tDumpPat(pat) mp2tDumpPat(pat)
@ -437,8 +403,7 @@ func mp2tDumpProgram(clip []byte) error {
for pn, pid := range pm { for pn, pid := range pm {
pmt, err := psi.ReadPMT(reader, pid) pmt, err := psi.ReadPMT(reader, pid)
if err != nil { if err != nil {
fmt.Printf("ReadPMT error: %s\n", err) return fmt.Errorf("Error reading PMT: %s", err)
return err
} }
pmts = append(pmts, pmt) pmts = append(pmts, pmt)
mp2tDumpPmt(pn, pmt) mp2tDumpPmt(pn, pmt)
@ -458,7 +423,7 @@ func mp2tDumpPmt(pn uint16, pmt psi.PMT) {
fmt.Printf("\tPIDs %v\n", pmt.Pids()) fmt.Printf("\tPIDs %v\n", pmt.Pids())
fmt.Printf("\tElementary Streams") fmt.Printf("\tElementary Streams")
for _, es := range pmt.ElementaryStreams() { for _, es := range pmt.ElementaryStreams() {
fmt.Printf("\t\tPid %v : StreamType %v\n", es.ElementaryPid(), es.StreamType()) fmt.Printf("\t\tPID %v : StreamType %v\n", es.ElementaryPid(), es.StreamType())
for _, d := range es.Descriptors() { for _, d := range es.Descriptors() {
fmt.Printf("\t\t\t%+v\n", d) fmt.Printf("\t\t\t%+v\n", d)
} }
@ -475,7 +440,7 @@ func mp2tFixContinuity(pkt []byte, packetCount int, pid uint16) bool {
if !hasPayload { if !hasPayload {
return false return false
} }
if pktPid, _ := packet.Pid(pkt); pktPid != pid { if pktPID, _ := packet.Pid(pkt); pktPID != pid {
return false return false
} }
fixed := false fixed := false
@ -491,8 +456,8 @@ func mp2tFixContinuity(pkt []byte, packetCount int, pid uint16) bool {
return fixed return fixed
} }
// Mp2tGetPcr extracts the Program Clock Reference (PCR) from an MPEG-TS packet (if any) // Mp2tGetPCR extracts the Program Clock Reference (PCR) from an MPEG-TS packet (if any)
func mp2tGetPcr(pkt []byte) (uint64, uint32, bool) { func mp2tGetPCR(pkt []byte) (uint64, uint32, bool) {
if !adaptationfield.HasPCR(pkt) { if !adaptationfield.HasPCR(pkt) {
return 0, 0, false return 0, 0, false
} }
@ -523,8 +488,8 @@ func RTPEncapsulate(mp2tPacket []byte, pkt []byte) {
timestamp := uint32(time.Now().UnixNano() / 1e6) // ms timestamp timestamp := uint32(time.Now().UnixNano() / 1e6) // ms timestamp
binary.BigEndian.PutUint32(pkt[4:8], timestamp) binary.BigEndian.PutUint32(pkt[4:8], timestamp)
// bytes 8,9,10&11: SSRC // bytes 8,9,10&11: SSRC
binary.BigEndian.PutUint32(pkt[8:12], RTPSSRC) binary.BigEndian.PutUint32(pkt[8:12], rtpSSRC)
// payload follows // payload follows
copy(pkt[RTPHeaderSize:RTPHeaderSize+RTPPackets*mp2tPacketSize], mp2tPacket) copy(pkt[rtpHeaderSize:rtpHeaderSize+rtpPackets*mp2tPacketSize], mp2tPacket)
} }