Merged in rtmp-refactoring (pull request #103)

Rtmp refactoring

Approved-by: kortschak <dan@kortschak.io>
Approved-by: Saxon Milton <saxon.milton@gmail.com>
Approved-by: Alan Noble <anoble@gmail.com>
This commit is contained in:
Alan Noble 2019-01-11 01:18:35 +00:00
commit d87dfca283
6 changed files with 518 additions and 605 deletions

View File

@ -3,7 +3,7 @@ NAME
packet.go packet.go
DESCRIPTION DESCRIPTION
See Readme.md RTMP packet functionality.
AUTHORS AUTHORS
Saxon Nelson-Milton <saxon@ausocean.org> Saxon Nelson-Milton <saxon@ausocean.org>
@ -35,37 +35,41 @@ LICENSE
package rtmp package rtmp
import ( import (
"io"
"encoding/binary" "encoding/binary"
"io"
) )
// Packet types.
const ( const (
RTMP_PACKET_TYPE_CHUNK_SIZE = 0x01 packetTypeChunkSize = 0x01
RTMP_PACKET_TYPE_BYTES_READ_REPORT = 0x03 packetTypeBytesReadReport = 0x03
RTMP_PACKET_TYPE_CONTROL = 0x04 packetTypeControl = 0x04
RTMP_PACKET_TYPE_SERVER_BW = 0x05 packetTypeServerBW = 0x05
RTMP_PACKET_TYPE_CLIENT_BW = 0x06 packetTypeClientBW = 0x06
RTMP_PACKET_TYPE_AUDIO = 0x08 packetTypeAudio = 0x08
RTMP_PACKET_TYPE_VIDEO = 0x09 packetTypeVideo = 0x09
RTMP_PACKET_TYPE_FLEX_STREAM_SEND = 0x0F packetTypeFlexStreamSend = 0x0F // not implemented
RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT = 0x10 packetTypeFlexSharedObject = 0x10 // not implemented
RTMP_PACKET_TYPE_FLEX_MESSAGE = 0x11 packetTypeFlexMessage = 0x11 // not implemented
RTMP_PACKET_TYPE_INFO = 0x12 packetTypeInfo = 0x12
RTMP_PACKET_TYPE_INVOKE = 0x14 packetTypeInvoke = 0x14
RTMP_PACKET_TYPE_FLASH_VIDEO = 0x16 packetTypeFlashVideo = 0x16 // not implemented
) )
// Header sizes.
const ( const (
RTMP_PACKET_SIZE_LARGE = 0 headerSizeLarge = 0
RTMP_PACKET_SIZE_MEDIUM = 1 headerSizeMedium = 1
RTMP_PACKET_SIZE_SMALL = 2 headerSizeSmall = 2
RTMP_PACKET_SIZE_MINIMUM = 3 headerSizeMinimum = 3
headerSizeAuto = 4
) )
// Special channels.
const ( const (
RTMP_CHANNEL_BYTES_READ = 0x02 chanBytesRead = 0x02
RTMP_CHANNEL_CONTROL = 0x03 chanControl = 0x03
RTMP_CHANNEL_SOURCE = 0x04 chanSource = 0x04
) )
// headerSizes defines header sizes for header types 0, 1, 2 and 3 respectively: // headerSizes defines header sizes for header types 0, 1, 2 and 3 respectively:
@ -94,16 +98,15 @@ type packet struct {
type chunk struct { type chunk struct {
headerSize int32 headerSize int32
data []byte data []byte
header [RTMP_MAX_HEADER_SIZE]byte header [fullHeaderSize]byte
} }
// ToDo: Consider making the following functions into methods. // read reads a packet.
// readPacket reads a packet. func (pkt *packet) read(s *Session) error {
func readPacket(s *Session, pkt *packet) error { var hbuf [fullHeaderSize]byte
var hbuf [RTMP_MAX_HEADER_SIZE]byte
header := hbuf[:] header := hbuf[:]
err := readN(s, header[:1]) _, err := s.read(header[:1])
if err != nil { if err != nil {
s.log(DebugLevel, pkg+"failed to read packet header 1st byte", "error", err.Error()) s.log(DebugLevel, pkg+"failed to read packet header 1st byte", "error", err.Error())
if err == io.EOF { if err == io.EOF {
@ -117,7 +120,7 @@ func readPacket(s *Session, pkt *packet) error {
switch { switch {
case pkt.channel == 0: case pkt.channel == 0:
err = readN(s, header[:1]) _, err = s.read(header[:1])
if err != nil { if err != nil {
s.log(DebugLevel, pkg+"failed to read packet header 2nd byte", "error", err.Error()) s.log(DebugLevel, pkg+"failed to read packet header 2nd byte", "error", err.Error())
return err return err
@ -126,7 +129,7 @@ func readPacket(s *Session, pkt *packet) error {
pkt.channel = int32(header[0]) + 64 pkt.channel = int32(header[0]) + 64
case pkt.channel == 1: case pkt.channel == 1:
err = readN(s, header[:2]) _, err = s.read(header[:2])
if err != nil { if err != nil {
s.log(DebugLevel, pkg+"failed to read packet header 3rd byte", "error", err.Error()) s.log(DebugLevel, pkg+"failed to read packet header 3rd byte", "error", err.Error())
return err return err
@ -160,9 +163,9 @@ func readPacket(s *Session, pkt *packet) error {
size := headerSizes[pkt.headerType] size := headerSizes[pkt.headerType]
switch { switch {
case size == RTMP_LARGE_HEADER_SIZE: case size == fullHeaderSize:
pkt.hasAbsTimestamp = true pkt.hasAbsTimestamp = true
case size < RTMP_LARGE_HEADER_SIZE: case size < fullHeaderSize:
if s.channelsIn[pkt.channel] != nil { if s.channelsIn[pkt.channel] != nil {
*pkt = *(s.channelsIn[pkt.channel]) *pkt = *(s.channelsIn[pkt.channel])
} }
@ -170,7 +173,7 @@ func readPacket(s *Session, pkt *packet) error {
size-- size--
if size > 0 { if size > 0 {
err = readN(s, header[:size]) _, err = s.read(header[:size])
if err != nil { if err != nil {
s.log(DebugLevel, pkg+"failed to read packet header", "error", err.Error()) s.log(DebugLevel, pkg+"failed to read packet header", "error", err.Error())
return err return err
@ -196,7 +199,7 @@ func readPacket(s *Session, pkt *packet) error {
extendedTimestamp := pkt.timestamp == 0xffffff extendedTimestamp := pkt.timestamp == 0xffffff
if extendedTimestamp { if extendedTimestamp {
err = readN(s, header[size:size+4]) _, err = s.read(header[size : size+4])
if err != nil { if err != nil {
s.log(DebugLevel, pkg+"failed to read extended timestamp", "error", err.Error()) s.log(DebugLevel, pkg+"failed to read extended timestamp", "error", err.Error())
return err return err
@ -207,7 +210,7 @@ func readPacket(s *Session, pkt *packet) error {
} }
if pkt.bodySize > 0 && pkt.body == nil { if pkt.bodySize > 0 && pkt.body == nil {
resizePacket(pkt, pkt.bodySize, (hbuf[0]&0xc0)>>6) pkt.resize(pkt.bodySize, (hbuf[0]&0xc0)>>6)
} }
toRead := int32(pkt.bodySize - pkt.bytesRead) toRead := int32(pkt.bodySize - pkt.bytesRead)
@ -218,12 +221,13 @@ func readPacket(s *Session, pkt *packet) error {
} }
if pkt.chunk != nil { if pkt.chunk != nil {
panic("non-nil chunk")
pkt.chunk.headerSize = int32(hSize) pkt.chunk.headerSize = int32(hSize)
copy(pkt.chunk.header[:], hbuf[:hSize]) copy(pkt.chunk.header[:], hbuf[:hSize])
pkt.chunk.data = pkt.body[pkt.bytesRead : pkt.bytesRead+uint32(chunkSize)] pkt.chunk.data = pkt.body[pkt.bytesRead : pkt.bytesRead+uint32(chunkSize)]
} }
err = readN(s, pkt.body[pkt.bytesRead:][:chunkSize]) _, err = s.read(pkt.body[pkt.bytesRead:][:chunkSize])
if err != nil { if err != nil {
s.log(DebugLevel, pkg+"failed to read packet body", "error", err.Error()) s.log(DebugLevel, pkg+"failed to read packet body", "error", err.Error())
return err return err
@ -257,20 +261,39 @@ func readPacket(s *Session, pkt *packet) error {
return nil return nil
} }
// resizePacket adjusts the packet's storage to accommodate a body of the given size. // resize adjusts the packet's storage to accommodate a body of the given size and header type.
func resizePacket(pkt *packet, size uint32, ht uint8) { func (pkt *packet) resize(size uint32, ht uint8) {
buf := make([]byte, RTMP_MAX_HEADER_SIZE+size) buf := make([]byte, fullHeaderSize+size)
pkt.headerType = ht
pkt.header = buf pkt.header = buf
pkt.body = buf[RTMP_MAX_HEADER_SIZE:] pkt.body = buf[fullHeaderSize:]
if ht != headerSizeAuto {
pkt.headerType = ht
return
}
switch pkt.packetType {
case packetTypeVideo, packetTypeAudio:
if pkt.timestamp == 0 {
pkt.headerType = headerSizeLarge
} else {
pkt.headerType = headerSizeMedium
}
case packetTypeInfo:
pkt.headerType = headerSizeLarge
pkt.bodySize += 16
default:
pkt.headerType = headerSizeMedium
}
} }
// sendPacket sends a packet. // write sends a packet.
func sendPacket(s *Session, pkt *packet, queue bool) error { // When queue is true, we expect a response to this request and cache the method on s.methodCalls.
var prevPkt *packet func (pkt *packet) write(s *Session, queue bool) error {
var last int if pkt.body == nil {
return errInvalidBody
}
if pkt.channel >= s.channelsAllocatedOut { if pkt.channel >= s.channelsAllocatedOut {
s.log(DebugLevel, pkg+"growing channelsOut", "channel", pkt.channel)
n := int(pkt.channel + 10) n := int(pkt.channel + 10)
var pkts []*packet var pkts []*packet
@ -287,16 +310,17 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
s.channelsAllocatedOut = int32(n) s.channelsAllocatedOut = int32(n)
} }
prevPkt = s.channelsOut[pkt.channel]
if prevPkt != nil && pkt.headerType != RTMP_PACKET_SIZE_LARGE { prevPkt := s.channelsOut[pkt.channel]
var last int
if prevPkt != nil && pkt.headerType != headerSizeLarge {
// compress a bit by using the prev packet's attributes // compress a bit by using the prev packet's attributes
if prevPkt.bodySize == pkt.bodySize && prevPkt.packetType == pkt.packetType && pkt.headerType == RTMP_PACKET_SIZE_MEDIUM { if prevPkt.bodySize == pkt.bodySize && prevPkt.packetType == pkt.packetType && pkt.headerType == headerSizeMedium {
pkt.headerType = RTMP_PACKET_SIZE_SMALL pkt.headerType = headerSizeSmall
} }
if prevPkt.timestamp == pkt.timestamp && pkt.headerType == RTMP_PACKET_SIZE_SMALL { if prevPkt.timestamp == pkt.timestamp && pkt.headerType == headerSizeSmall {
pkt.headerType = RTMP_PACKET_SIZE_MINIMUM pkt.headerType = headerSizeMinimum
} }
last = int(prevPkt.timestamp) last = int(prevPkt.timestamp)
@ -307,20 +331,14 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
return errInvalidHeader return errInvalidHeader
} }
var headBytes []byte // The complete packet starts from headerSize _before_ the start the body.
var origIdx int // origIdx is the original offset, which will be 0 for a full (12-byte) header or 11 for a minimum (1-byte) header.
if pkt.body != nil { headBytes := pkt.header
// Span from -packetsize for the type to the start of the body. hSize := headerSizes[pkt.headerType]
headBytes = pkt.header origIdx := fullHeaderSize - hSize
origIdx = RTMP_MAX_HEADER_SIZE - headerSizes[pkt.headerType]
} else {
// Allocate a new header and allow 6 bytes of movement backward.
var hbuf [RTMP_MAX_HEADER_SIZE]byte
headBytes = hbuf[:]
origIdx = 6
}
var cSize int // adjust 1 or 2 bytes for the channel
cSize := 0
switch { switch {
case pkt.channel > 319: case pkt.channel > 319:
cSize = 2 cSize = 2
@ -328,12 +346,12 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
cSize = 1 cSize = 1
} }
hSize := headerSizes[pkt.headerType]
if cSize != 0 { if cSize != 0 {
origIdx -= cSize origIdx -= cSize
hSize += cSize hSize += cSize
} }
// adjust 4 bytes for the timestamp
var ts uint32 var ts uint32
if prevPkt != nil { if prevPkt != nil {
ts = uint32(int(pkt.timestamp) - last) ts = uint32(int(pkt.timestamp) - last)
@ -386,8 +404,8 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
} }
if headerSizes[pkt.headerType] > 8 { if headerSizes[pkt.headerType] > 8 {
n := int(encodeInt32LE(headBytes[headerIdx:headerIdx+4], pkt.info)) binary.LittleEndian.PutUint32(headBytes[headerIdx:headerIdx+4], uint32(pkt.info))
headerIdx += n headerIdx += 4 // 32bits
} }
if ts >= 0xffffff { if ts >= 0xffffff {
@ -398,33 +416,39 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
size := int(pkt.bodySize) size := int(pkt.bodySize)
chunkSize := int(s.outChunkSize) chunkSize := int(s.outChunkSize)
s.log(DebugLevel, pkg+"sending packet", "size", size, "la", s.link.conn.LocalAddr(), "ra", s.link.conn.RemoteAddr()) if s.deferred == nil {
// Defer sending small audio packets (at most once).
if s.deferred != nil && len(s.deferred)+size+hSize > chunkSize { if pkt.packetType == packetTypeAudio && size < chunkSize {
err := writeN(s, s.deferred) s.deferred = headBytes[origIdx:][:size+hSize]
s.log(DebugLevel, pkg+"deferred sending packet", "size", size, "la", s.link.conn.LocalAddr(), "ra", s.link.conn.RemoteAddr())
return nil
}
} else {
// Send previously deferrd packet if combining it with the next one would exceed the chunk size.
if len(s.deferred)+size+hSize > chunkSize {
s.log(DebugLevel, pkg+"sending deferred packet separately", "size", len(s.deferred))
_, err := s.write(s.deferred)
if err != nil { if err != nil {
return err return err
} }
s.deferred = nil s.deferred = nil
} }
}
// TODO(kortschak): Rewrite this horrific peice of premature optimisation. // TODO(kortschak): Rewrite this horrific peice of premature optimisation.
// NB: RTMP wants packets in chunks which are 128 bytes by default, but the server may request a different size. // NB: RTMP wants packets in chunks which are 128 bytes by default, but the server may request a different size.
s.log(DebugLevel, pkg+"sending packet", "la", s.link.conn.LocalAddr(), "ra", s.link.conn.RemoteAddr(), "size", size)
for size+hSize != 0 { for size+hSize != 0 {
if s.deferred == nil && pkt.packetType == RTMP_PACKET_TYPE_AUDIO && size < chunkSize {
s.deferred = headBytes[origIdx:][:size+hSize]
s.log(DebugLevel, pkg+"deferred sending packet")
break
}
if chunkSize > size { if chunkSize > size {
chunkSize = size chunkSize = size
} }
bytes := headBytes[origIdx:][:chunkSize+hSize] bytes := headBytes[origIdx:][:chunkSize+hSize]
if s.deferred != nil { if s.deferred != nil {
// Prepend the previously deferred packet and write it with the current one. // Prepend the previously deferred packet and write it with the current one.
s.log(DebugLevel, pkg+"combining deferred packet", "size", len(s.deferred))
bytes = append(s.deferred, bytes...) bytes = append(s.deferred, bytes...)
} }
err := writeN(s, bytes) _, err := s.write(bytes)
if err != nil { if err != nil {
return err return err
} }
@ -461,12 +485,12 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
} }
// We invoked a remote method // We invoked a remote method
if pkt.packetType == RTMP_PACKET_TYPE_INVOKE { if pkt.packetType == packetTypeInvoke {
buf := pkt.body[1:] buf := pkt.body[1:]
meth := C_AMF_DecodeString(buf) meth := C_AMF_DecodeString(buf)
s.log(DebugLevel, pkg+"invoking method "+meth)
// keep it in call queue till result arrives // keep it in call queue till result arrives
if queue { if queue {
s.log(DebugLevel, pkg+"queuing method "+meth)
buf = buf[3+len(meth):] buf = buf[3+len(meth):]
txn := int32(C_AMF_DecodeNumber(buf[:8])) txn := int32(C_AMF_DecodeNumber(buf[:8]))
s.methodCalls = append(s.methodCalls, method{name: meth, num: txn}) s.methodCalls = append(s.methodCalls, method{name: meth, num: txn})

View File

@ -8,9 +8,10 @@ DESCRIPTION
AUTHOR AUTHOR
Dan Kortschak <dan@ausocean.org> Dan Kortschak <dan@ausocean.org>
Saxon Nelson-Milton <saxon@ausocean.org> Saxon Nelson-Milton <saxon@ausocean.org>
Alan Noble <alan@ausocean.org>
LICENSE LICENSE
parseurl.go is Copyright (C) 2017-2018 the Australian Ocean Lab (AusOcean) parseurl.go is Copyright (C) 2017-2019 the Australian Ocean Lab (AusOcean)
It is free software: you can redistribute it and/or modify them 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 under the terms of the GNU General Public License as published by the
@ -33,7 +34,6 @@ LICENSE
package rtmp package rtmp
import ( import (
"log"
"net/url" "net/url"
"path" "path"
"strconv" "strconv"
@ -41,30 +41,29 @@ import (
) )
// parseURL parses an RTMP URL (ok, technically it is lexing). // parseURL parses an RTMP URL (ok, technically it is lexing).
//
func parseURL(addr string) (protocol int32, host string, port uint16, app, playpath string, err error) { func parseURL(addr string) (protocol int32, host string, port uint16, app, playpath string, err error) {
u, err := url.Parse(addr) u, err := url.Parse(addr)
if err != nil { if err != nil {
log.Printf("failed to parse addr: %v", err)
return protocol, host, port, app, playpath, err return protocol, host, port, app, playpath, err
} }
switch u.Scheme { switch u.Scheme {
case "rtmp": case "rtmp":
protocol = RTMP_PROTOCOL_RTMP protocol = protoRTMP
case "rtmpt": case "rtmpt":
protocol = RTMP_PROTOCOL_RTMPT protocol = protoRTMPT
case "rtmps": case "rtmps":
protocol = RTMP_PROTOCOL_RTMPS protocol = protoRTMPS
case "rtmpe": case "rtmpe":
protocol = RTMP_PROTOCOL_RTMPE protocol = protoRTMPE
case "rtmfp": case "rtmfp":
protocol = RTMP_PROTOCOL_RTMFP protocol = protoRTMFP
case "rtmpte": case "rtmpte":
protocol = RTMP_PROTOCOL_RTMPTE protocol = protoRTMPTE
case "rtmpts": case "rtmpts":
protocol = RTMP_PROTOCOL_RTMPTS protocol = protoRTMPTS
default: default:
log.Printf("unknown scheme: %q", u.Scheme)
return protocol, host, port, app, playpath, errUnknownScheme return protocol, host, port, app, playpath, errUnknownScheme
} }

File diff suppressed because it is too large Load Diff

View File

@ -1,119 +0,0 @@
/*
NAME
rtmp_headers.go
DESCRIPTION
See Readme.md
AUTHORS
Saxon Nelson-Milton <saxon@ausocean.org>
Dan Kortschak <dan@ausocean.org>
Alan Noble <alan@ausocean.org>
LICENSE
rtmp_headers.go is Copyright (C) 2017-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
along with revid in gpl.txt. If not, see http://www.gnu.org/licenses.
Derived from librtmp under the GNU Lesser General Public License 2.1
Copyright (C) 2005-2008 Team XBMC http://www.xbmc.org
Copyright (C) 2008-2009 Andrej Stepanchuk
Copyright (C) 2009-2010 Howard Chu
*/
package rtmp
import (
"net"
)
const (
RTMPT_OPEN = iota
RTMPT_SEND
RTMPT_IDLE
RTMPT_CLOSE
)
const (
RTMP_READ_HEADER = 0x01
RTMP_READ_RESUME = 0x02
RTMP_READ_NO_IGNORE = 0x04
RTMP_READ_GOTKF = 0x08
RTMP_READ_GOTFLVK = 0x10
RTMP_READ_SEEKING = 0x20
RTMP_READ_COMPLETE = -3
RTMP_READ_ERROR = -2
RTMP_READ_EOF = -1
RTMP_READ_IGNORE = 0
)
const (
RTMP_LF_AUTH = 0x0001 /* using auth param */
RTMP_LF_LIVE = 0x0002 /* stream is live */
RTMP_LF_SWFV = 0x0004 /* do SWF verification */
RTMP_LF_PLST = 0x0008 /* send playlist before play */
RTMP_LF_BUFX = 0x0010 /* toggle stream on BufferEmpty msg */
RTMP_LF_FTCU = 0x0020 /* free tcUrl on close */
RTMP_LF_FAPU = 0x0040 /* free app on close */
)
const (
RTMP_FEATURE_HTTP = 0x01
RTMP_FEATURE_ENC = 0x02
RTMP_FEATURE_SSL = 0x04
RTMP_FEATURE_MFP = 0x08 /* not yet supported */
RTMP_FEATURE_WRITE = 0x10 /* publish, not play */
RTMP_FEATURE_HTTP2 = 0x20 /* server-side rtmpt */
)
const (
RTMP_PROTOCOL_RTMP = 0
RTMP_PROTOCOL_RTMPE = RTMP_FEATURE_ENC
RTMP_PROTOCOL_RTMPT = RTMP_FEATURE_HTTP
RTMP_PROTOCOL_RTMPS = RTMP_FEATURE_SSL
RTMP_PROTOCOL_RTMPTE = (RTMP_FEATURE_HTTP | RTMP_FEATURE_ENC)
RTMP_PROTOCOL_RTMPTS = (RTMP_FEATURE_HTTP | RTMP_FEATURE_SSL)
RTMP_PROTOCOL_RTMFP = RTMP_FEATURE_MFP
)
const (
RTMP_DEFAULT_CHUNKSIZE = 128
RTMP_BUFFER_CACHE_SIZE = (16 * 1024)
RTMP_SIG_SIZE = 1536
RTMP_LARGE_HEADER_SIZE = 12
RTMP_MAX_HEADER_SIZE = 18
)
type link struct {
host string
playpath string
tcUrl string
swfUrl string
pageUrl string
app string
auth string
flashVer string
token string
extras C_AMFObject
lFlags int32
swfAge int32
protocol int32
timeout uint
port uint16
conn *net.TCPConn
}
type method struct {
name string
num int32
}

View File

@ -6,6 +6,8 @@ DESCRIPTION
RTMP tests RTMP tests
AUTHORS AUTHORS
Saxon Nelson-Milton <saxon@ausocean.org>
Dan Kortschak <dan@ausocean.org>
Alan Noble <alan@ausocean.org> Alan Noble <alan@ausocean.org>
LICENSE LICENSE
@ -49,20 +51,22 @@ const (
testDataDir = "../../test/test-data/av/input" testDataDir = "../../test/test-data/av/input"
) )
// testVerbosity controls the amount of output // testVerbosity controls the amount of output.
// NB: This is not the log level, which is DebugLevel. // NB: This is not the log level, which is DebugLevel.
// 0: suppress logging completely // 0: suppress logging completely
// 1: log messages only // 1: log messages only
// 2: log messages with errors, if any // 2: log messages with errors, if any
var testVerbosity = 1 var testVerbosity = 1
// testKey is the RTMP key required for YouTube streaming (RTMP_TEST_KEY env var) // testKey is the YouTube RTMP key required for YouTube streaming (RTMP_TEST_KEY env var).
// NB: don't share your key with others.
var testKey string var testKey string
// testFile is the test video file (RTMP_TEST_FILE env var) // testFile is the test video file (RTMP_TEST_FILE env var).
// betterInput.h264 is a good one to use.
var testFile string var testFile string
// testLog is a bare bones logger that logs to stdout. // testLog is a bare bones logger that logs to stdout, and exits upon either an error or fatal error.
func testLog(level int8, msg string, params ...interface{}) { func testLog(level int8, msg string, params ...interface{}) {
logLevels := [...]string{"Debug", "Info", "Warn", "Error", "", "", "Fatal"} logLevels := [...]string{"Debug", "Info", "Warn", "Error", "", "", "Fatal"}
if testVerbosity == 0 { if testVerbosity == 0 {
@ -71,8 +75,14 @@ func testLog(level int8, msg string, params ...interface{}) {
if level < -1 || level > 5 { if level < -1 || level > 5 {
panic("Invalid log level") panic("Invalid log level")
} }
if testVerbosity == 2 && len(params) >= 2 { switch testVerbosity {
// extract the params we know about, otherwise just print the message case 0:
// silence is golden
case 1:
fmt.Printf("%s: %s\n", logLevels[level+1], msg)
case 2:
// extract the first param if it is one we care about, otherwise just print the message
if len(params) >= 2 {
switch params[0].(string) { switch params[0].(string) {
case "error": case "error":
fmt.Printf("%s: %s, error=%v\n", logLevels[level+1], msg, params[1].(string)) fmt.Printf("%s: %s, error=%v\n", logLevels[level+1], msg, params[1].(string))
@ -84,8 +94,9 @@ func testLog(level int8, msg string, params ...interface{}) {
} else { } else {
fmt.Printf("%s: %s\n", logLevels[level+1], msg) fmt.Printf("%s: %s\n", logLevels[level+1], msg)
} }
if level == 5 { }
// Fatal if level >= 4 {
// Error or Fatal
buf := make([]byte, 1<<16) buf := make([]byte, 1<<16)
size := runtime.Stack(buf, true) size := runtime.Stack(buf, true)
fmt.Printf("%s\n", string(buf[:size])) fmt.Printf("%s\n", string(buf[:size]))
@ -113,7 +124,7 @@ func TestSetupURL(t *testing.T) {
if s.url != testBaseURL && s.link.timeout != testTimeout { if s.url != testBaseURL && s.link.timeout != testTimeout {
t.Errorf("NewSession failed") t.Errorf("NewSession failed")
} }
err := setupURL(s, s.url) err := setupURL(s)
if err != nil { if err != nil {
t.Errorf("setupURL(testBaseURL) failed with error: %v", err) t.Errorf("setupURL(testBaseURL) failed with error: %v", err)
} }
@ -166,12 +177,16 @@ func TestFromFrame(t *testing.T) {
} }
// Pass RTMP session, true for audio, true for video, and 25 FPS // Pass RTMP session, true for audio, true for video, and 25 FPS
// ToDo: fix this. Although we can encode the file and YouTube
// doesn't complain, YouTube doesn't play it (even when we
// send 1 minute's worth).
flvEncoder := flv.NewEncoder(s, true, true, 25) flvEncoder := flv.NewEncoder(s, true, true, 25)
for i := 0; i < 25; i++ { for i := 0; i < 25; i++ {
err := flvEncoder.Encode(b) err := flvEncoder.Encode(b)
if err != nil { if err != nil {
t.Errorf("Encoding failed with error: %v", err) t.Errorf("Encoding failed with error: %v", err)
} }
time.Sleep(time.Millisecond / 25) // rate limit to 1/25s
} }
err = s.Close() err = s.Close()

View File

@ -3,7 +3,7 @@ NAME
session.go session.go
DESCRIPTION DESCRIPTION
See Readme.md RTMP session functionality.
AUTHORS AUTHORS
Saxon Nelson-Milton <saxon@ausocean.org> Saxon Nelson-Milton <saxon@ausocean.org>
@ -33,6 +33,12 @@ LICENSE
*/ */
package rtmp package rtmp
import (
"io"
"net"
"time"
)
// Session holds the state for an RTMP session. // Session holds the state for an RTMP session.
type Session struct { type Session struct {
url string url string
@ -62,6 +68,32 @@ type Session struct {
log Log log Log
} }
// link represents RTMP URL and connection information.
type link struct {
host string
playpath string
tcUrl string
swfUrl string
pageUrl string
app string
auth string
flashVer string
token string
extras C_AMFObject
flags int32
swfAge int32
protocol int32
timeout uint
port uint16
conn *net.TCPConn
}
// method represents an RTMP method.
type method struct {
name string
num int32
}
// Log defines the RTMP logging function. // Log defines the RTMP logging function.
type Log func(level int8, message string, params ...interface{}) type Log func(level int8, message string, params ...interface{})
@ -95,63 +127,46 @@ func NewSession(url string, timeout uint, log Log) *Session {
// Open establishes an rtmp connection with the url passed into the constructor. // Open establishes an rtmp connection with the url passed into the constructor.
func (s *Session) Open() error { func (s *Session) Open() error {
s.log(DebugLevel, pkg+"Session.Open")
if s.isConnected() { if s.isConnected() {
return errConnected return errConnected
} }
err := s.start() err := setupURL(s)
if err != nil { if err != nil {
return err return err
} }
return nil
}
// start does the heavylifting for Open().
func (s *Session) start() error {
s.log(DebugLevel, pkg+"Session.start")
err := setupURL(s, s.url)
if err != nil {
s.close()
return err
}
s.enableWrite() s.enableWrite()
err = connect(s) err = connect(s)
if err != nil { if err != nil {
s.close() s.Close()
return err return err
} }
err = connectStream(s) err = connectStream(s)
if err != nil { if err != nil {
s.close() s.Close()
return err return err
} }
return nil return nil
} }
// Close terminates the rtmp connection, // Close terminates the rtmp connection.
// NB: Close is idempotent and the session value is cleared completely.
func (s *Session) Close() error { func (s *Session) Close() error {
s.log(DebugLevel, pkg+"Session.Close")
if !s.isConnected() { if !s.isConnected() {
return errNotConnected return errNotConnected
} }
s.close()
return nil
}
// close does the heavylifting for Close().
// Any errors are ignored as it is often called in response to an earlier error.
func (s *Session) close() {
s.log(DebugLevel, pkg+"Session.close")
if s.isConnected() {
if s.streamID > 0 { if s.streamID > 0 {
if s.link.protocol&RTMP_FEATURE_WRITE != 0 { if s.link.protocol&featureWrite != 0 {
sendFCUnpublish(s) sendFCUnpublish(s)
} }
sendDeleteStream(s, float64(s.streamID)) sendDeleteStream(s, float64(s.streamID))
} }
s.link.conn.Close() s.link.conn.Close()
}
*s = Session{} *s = Session{}
return nil
} }
// Write writes a frame (flv tag) to the rtmp connection. // Write writes a frame (flv tag) to the rtmp connection.
@ -159,13 +174,70 @@ func (s *Session) Write(data []byte) (int, error) {
if !s.isConnected() { if !s.isConnected() {
return 0, errNotConnected return 0, errNotConnected
} }
err := s.write(data) if len(data) < minDataSize {
return 0, errTinyPacket
}
if data[0] == packetTypeInfo || (data[0] == 'F' && data[1] == 'L' && data[2] == 'V') {
return 0, errUnimplemented
}
pkt := packet{
packetType: data[0],
bodySize: C_AMF_DecodeInt24(data[1:4]),
timestamp: C_AMF_DecodeInt24(data[4:7]) | uint32(data[7])<<24,
channel: chanSource,
info: s.streamID,
}
pkt.resize(pkt.bodySize, headerSizeAuto)
copy(pkt.body, data[minDataSize:minDataSize+pkt.bodySize])
err := pkt.write(s, false)
if err != nil { if err != nil {
return 0, err return 0, err
} }
return len(data), nil return len(data), nil
} }
// I/O functions
// read from an RTMP connection. Sends a bytes received message if the
// number of bytes received (nBytesIn) is greater than the number sent
// (nBytesInSent) by 10% of the bandwidth.
func (s *Session) read(buf []byte) (int, error) {
err := s.link.conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(s.link.timeout)))
if err != nil {
return 0, err
}
n, err := io.ReadFull(s.link.conn, buf)
if err != nil {
s.log(DebugLevel, pkg+"read failed", "error", err.Error())
return 0, err
}
s.nBytesIn += int32(n)
if s.nBytesIn > (s.nBytesInSent + s.clientBW/10) {
err := sendBytesReceived(s)
if err != nil {
return n, err // NB: we still read n bytes, even though send bytes failed
}
}
return n, nil
}
// write to an RTMP connection.
func (s *Session) write(buf []byte) (int, error) {
//ToDo: consider using a different timeout for writes than for reads
err := s.link.conn.SetWriteDeadline(time.Now().Add(time.Second * time.Duration(s.link.timeout)))
if err != nil {
return 0, err
}
n, err := s.link.conn.Write(buf)
if err != nil {
s.log(WarnLevel, pkg+"write failed", "error", err.Error())
return 0, err
}
return n, nil
}
// isConnected returns true if the RTMP connection is up. // isConnected returns true if the RTMP connection is up.
func (s *Session) isConnected() bool { func (s *Session) isConnected() bool {
return s.link.conn != nil return s.link.conn != nil
@ -173,5 +245,5 @@ func (s *Session) isConnected() bool {
// enableWrite enables the current session for writing. // enableWrite enables the current session for writing.
func (s *Session) enableWrite() { func (s *Session) enableWrite() {
s.link.protocol |= RTMP_FEATURE_WRITE s.link.protocol |= featureWrite
} }