mirror of https://bitbucket.org/ausocean/av.git
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:
commit
d87dfca283
188
rtmp/packet.go
188
rtmp/packet.go
|
@ -3,7 +3,7 @@ NAME
|
|||
packet.go
|
||||
|
||||
DESCRIPTION
|
||||
See Readme.md
|
||||
RTMP packet functionality.
|
||||
|
||||
AUTHORS
|
||||
Saxon Nelson-Milton <saxon@ausocean.org>
|
||||
|
@ -35,37 +35,41 @@ LICENSE
|
|||
package rtmp
|
||||
|
||||
import (
|
||||
"io"
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
// Packet types.
|
||||
const (
|
||||
RTMP_PACKET_TYPE_CHUNK_SIZE = 0x01
|
||||
RTMP_PACKET_TYPE_BYTES_READ_REPORT = 0x03
|
||||
RTMP_PACKET_TYPE_CONTROL = 0x04
|
||||
RTMP_PACKET_TYPE_SERVER_BW = 0x05
|
||||
RTMP_PACKET_TYPE_CLIENT_BW = 0x06
|
||||
RTMP_PACKET_TYPE_AUDIO = 0x08
|
||||
RTMP_PACKET_TYPE_VIDEO = 0x09
|
||||
RTMP_PACKET_TYPE_FLEX_STREAM_SEND = 0x0F
|
||||
RTMP_PACKET_TYPE_FLEX_SHARED_OBJECT = 0x10
|
||||
RTMP_PACKET_TYPE_FLEX_MESSAGE = 0x11
|
||||
RTMP_PACKET_TYPE_INFO = 0x12
|
||||
RTMP_PACKET_TYPE_INVOKE = 0x14
|
||||
RTMP_PACKET_TYPE_FLASH_VIDEO = 0x16
|
||||
packetTypeChunkSize = 0x01
|
||||
packetTypeBytesReadReport = 0x03
|
||||
packetTypeControl = 0x04
|
||||
packetTypeServerBW = 0x05
|
||||
packetTypeClientBW = 0x06
|
||||
packetTypeAudio = 0x08
|
||||
packetTypeVideo = 0x09
|
||||
packetTypeFlexStreamSend = 0x0F // not implemented
|
||||
packetTypeFlexSharedObject = 0x10 // not implemented
|
||||
packetTypeFlexMessage = 0x11 // not implemented
|
||||
packetTypeInfo = 0x12
|
||||
packetTypeInvoke = 0x14
|
||||
packetTypeFlashVideo = 0x16 // not implemented
|
||||
)
|
||||
|
||||
// Header sizes.
|
||||
const (
|
||||
RTMP_PACKET_SIZE_LARGE = 0
|
||||
RTMP_PACKET_SIZE_MEDIUM = 1
|
||||
RTMP_PACKET_SIZE_SMALL = 2
|
||||
RTMP_PACKET_SIZE_MINIMUM = 3
|
||||
headerSizeLarge = 0
|
||||
headerSizeMedium = 1
|
||||
headerSizeSmall = 2
|
||||
headerSizeMinimum = 3
|
||||
headerSizeAuto = 4
|
||||
)
|
||||
|
||||
// Special channels.
|
||||
const (
|
||||
RTMP_CHANNEL_BYTES_READ = 0x02
|
||||
RTMP_CHANNEL_CONTROL = 0x03
|
||||
RTMP_CHANNEL_SOURCE = 0x04
|
||||
chanBytesRead = 0x02
|
||||
chanControl = 0x03
|
||||
chanSource = 0x04
|
||||
)
|
||||
|
||||
// headerSizes defines header sizes for header types 0, 1, 2 and 3 respectively:
|
||||
|
@ -94,16 +98,15 @@ type packet struct {
|
|||
type chunk struct {
|
||||
headerSize int32
|
||||
data []byte
|
||||
header [RTMP_MAX_HEADER_SIZE]byte
|
||||
header [fullHeaderSize]byte
|
||||
}
|
||||
|
||||
// ToDo: Consider making the following functions into methods.
|
||||
// readPacket reads a packet.
|
||||
func readPacket(s *Session, pkt *packet) error {
|
||||
var hbuf [RTMP_MAX_HEADER_SIZE]byte
|
||||
// read reads a packet.
|
||||
func (pkt *packet) read(s *Session) error {
|
||||
var hbuf [fullHeaderSize]byte
|
||||
header := hbuf[:]
|
||||
|
||||
err := readN(s, header[:1])
|
||||
_, err := s.read(header[:1])
|
||||
if err != nil {
|
||||
s.log(DebugLevel, pkg+"failed to read packet header 1st byte", "error", err.Error())
|
||||
if err == io.EOF {
|
||||
|
@ -117,7 +120,7 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
|
||||
switch {
|
||||
case pkt.channel == 0:
|
||||
err = readN(s, header[:1])
|
||||
_, err = s.read(header[:1])
|
||||
if err != nil {
|
||||
s.log(DebugLevel, pkg+"failed to read packet header 2nd byte", "error", err.Error())
|
||||
return err
|
||||
|
@ -126,7 +129,7 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
pkt.channel = int32(header[0]) + 64
|
||||
|
||||
case pkt.channel == 1:
|
||||
err = readN(s, header[:2])
|
||||
_, err = s.read(header[:2])
|
||||
if err != nil {
|
||||
s.log(DebugLevel, pkg+"failed to read packet header 3rd byte", "error", err.Error())
|
||||
return err
|
||||
|
@ -160,9 +163,9 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
|
||||
size := headerSizes[pkt.headerType]
|
||||
switch {
|
||||
case size == RTMP_LARGE_HEADER_SIZE:
|
||||
case size == fullHeaderSize:
|
||||
pkt.hasAbsTimestamp = true
|
||||
case size < RTMP_LARGE_HEADER_SIZE:
|
||||
case size < fullHeaderSize:
|
||||
if s.channelsIn[pkt.channel] != nil {
|
||||
*pkt = *(s.channelsIn[pkt.channel])
|
||||
}
|
||||
|
@ -170,7 +173,7 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
size--
|
||||
|
||||
if size > 0 {
|
||||
err = readN(s, header[:size])
|
||||
_, err = s.read(header[:size])
|
||||
if err != nil {
|
||||
s.log(DebugLevel, pkg+"failed to read packet header", "error", err.Error())
|
||||
return err
|
||||
|
@ -196,7 +199,7 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
|
||||
extendedTimestamp := pkt.timestamp == 0xffffff
|
||||
if extendedTimestamp {
|
||||
err = readN(s, header[size:size+4])
|
||||
_, err = s.read(header[size : size+4])
|
||||
if err != nil {
|
||||
s.log(DebugLevel, pkg+"failed to read extended timestamp", "error", err.Error())
|
||||
return err
|
||||
|
@ -207,7 +210,7 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
}
|
||||
|
||||
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)
|
||||
|
@ -218,12 +221,13 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
}
|
||||
|
||||
if pkt.chunk != nil {
|
||||
panic("non-nil chunk")
|
||||
pkt.chunk.headerSize = int32(hSize)
|
||||
copy(pkt.chunk.header[:], hbuf[:hSize])
|
||||
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 {
|
||||
s.log(DebugLevel, pkg+"failed to read packet body", "error", err.Error())
|
||||
return err
|
||||
|
@ -257,20 +261,39 @@ func readPacket(s *Session, pkt *packet) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// resizePacket adjusts the packet's storage to accommodate a body of the given size.
|
||||
func resizePacket(pkt *packet, size uint32, ht uint8) {
|
||||
buf := make([]byte, RTMP_MAX_HEADER_SIZE+size)
|
||||
pkt.headerType = ht
|
||||
// resize adjusts the packet's storage to accommodate a body of the given size and header type.
|
||||
func (pkt *packet) resize(size uint32, ht uint8) {
|
||||
buf := make([]byte, fullHeaderSize+size)
|
||||
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.
|
||||
func sendPacket(s *Session, pkt *packet, queue bool) error {
|
||||
var prevPkt *packet
|
||||
var last int
|
||||
// write sends a packet.
|
||||
// When queue is true, we expect a response to this request and cache the method on s.methodCalls.
|
||||
func (pkt *packet) write(s *Session, queue bool) error {
|
||||
if pkt.body == nil {
|
||||
return errInvalidBody
|
||||
}
|
||||
|
||||
if pkt.channel >= s.channelsAllocatedOut {
|
||||
s.log(DebugLevel, pkg+"growing channelsOut", "channel", pkt.channel)
|
||||
n := int(pkt.channel + 10)
|
||||
|
||||
var pkts []*packet
|
||||
|
@ -287,16 +310,17 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
|
|||
|
||||
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
|
||||
if prevPkt.bodySize == pkt.bodySize && prevPkt.packetType == pkt.packetType && pkt.headerType == RTMP_PACKET_SIZE_MEDIUM {
|
||||
pkt.headerType = RTMP_PACKET_SIZE_SMALL
|
||||
if prevPkt.bodySize == pkt.bodySize && prevPkt.packetType == pkt.packetType && pkt.headerType == headerSizeMedium {
|
||||
pkt.headerType = headerSizeSmall
|
||||
}
|
||||
|
||||
if prevPkt.timestamp == pkt.timestamp && pkt.headerType == RTMP_PACKET_SIZE_SMALL {
|
||||
pkt.headerType = RTMP_PACKET_SIZE_MINIMUM
|
||||
if prevPkt.timestamp == pkt.timestamp && pkt.headerType == headerSizeSmall {
|
||||
pkt.headerType = headerSizeMinimum
|
||||
}
|
||||
|
||||
last = int(prevPkt.timestamp)
|
||||
|
@ -307,20 +331,14 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
|
|||
return errInvalidHeader
|
||||
}
|
||||
|
||||
var headBytes []byte
|
||||
var origIdx int
|
||||
if pkt.body != nil {
|
||||
// Span from -packetsize for the type to the start of the body.
|
||||
headBytes = pkt.header
|
||||
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
|
||||
}
|
||||
// The complete packet starts from headerSize _before_ the start the body.
|
||||
// origIdx is the original offset, which will be 0 for a full (12-byte) header or 11 for a minimum (1-byte) header.
|
||||
headBytes := pkt.header
|
||||
hSize := headerSizes[pkt.headerType]
|
||||
origIdx := fullHeaderSize - hSize
|
||||
|
||||
var cSize int
|
||||
// adjust 1 or 2 bytes for the channel
|
||||
cSize := 0
|
||||
switch {
|
||||
case pkt.channel > 319:
|
||||
cSize = 2
|
||||
|
@ -328,12 +346,12 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
|
|||
cSize = 1
|
||||
}
|
||||
|
||||
hSize := headerSizes[pkt.headerType]
|
||||
if cSize != 0 {
|
||||
origIdx -= cSize
|
||||
hSize += cSize
|
||||
}
|
||||
|
||||
// adjust 4 bytes for the timestamp
|
||||
var ts uint32
|
||||
if prevPkt != nil {
|
||||
ts = uint32(int(pkt.timestamp) - last)
|
||||
|
@ -386,8 +404,8 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
|
|||
}
|
||||
|
||||
if headerSizes[pkt.headerType] > 8 {
|
||||
n := int(encodeInt32LE(headBytes[headerIdx:headerIdx+4], pkt.info))
|
||||
headerIdx += n
|
||||
binary.LittleEndian.PutUint32(headBytes[headerIdx:headerIdx+4], uint32(pkt.info))
|
||||
headerIdx += 4 // 32bits
|
||||
}
|
||||
|
||||
if ts >= 0xffffff {
|
||||
|
@ -398,33 +416,39 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
|
|||
size := int(pkt.bodySize)
|
||||
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 && len(s.deferred)+size+hSize > chunkSize {
|
||||
err := writeN(s, s.deferred)
|
||||
if err != nil {
|
||||
return err
|
||||
if s.deferred == nil {
|
||||
// Defer sending small audio packets (at most once).
|
||||
if pkt.packetType == packetTypeAudio && size < chunkSize {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
s.deferred = nil
|
||||
}
|
||||
s.deferred = nil
|
||||
}
|
||||
|
||||
// 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.
|
||||
s.log(DebugLevel, pkg+"sending packet", "la", s.link.conn.LocalAddr(), "ra", s.link.conn.RemoteAddr(), "size", size)
|
||||
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 {
|
||||
chunkSize = size
|
||||
}
|
||||
bytes := headBytes[origIdx:][:chunkSize+hSize]
|
||||
if s.deferred != nil {
|
||||
// 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...)
|
||||
}
|
||||
err := writeN(s, bytes)
|
||||
_, err := s.write(bytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -461,12 +485,12 @@ func sendPacket(s *Session, pkt *packet, queue bool) error {
|
|||
}
|
||||
|
||||
// We invoked a remote method
|
||||
if pkt.packetType == RTMP_PACKET_TYPE_INVOKE {
|
||||
if pkt.packetType == packetTypeInvoke {
|
||||
buf := pkt.body[1:]
|
||||
meth := C_AMF_DecodeString(buf)
|
||||
s.log(DebugLevel, pkg+"invoking method "+meth)
|
||||
// keep it in call queue till result arrives
|
||||
if queue {
|
||||
s.log(DebugLevel, pkg+"queuing method "+meth)
|
||||
buf = buf[3+len(meth):]
|
||||
txn := int32(C_AMF_DecodeNumber(buf[:8]))
|
||||
s.methodCalls = append(s.methodCalls, method{name: meth, num: txn})
|
||||
|
|
|
@ -8,9 +8,10 @@ DESCRIPTION
|
|||
AUTHOR
|
||||
Dan Kortschak <dan@ausocean.org>
|
||||
Saxon Nelson-Milton <saxon@ausocean.org>
|
||||
Alan Noble <alan@ausocean.org>
|
||||
|
||||
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
|
||||
under the terms of the GNU General Public License as published by the
|
||||
|
@ -33,7 +34,6 @@ LICENSE
|
|||
package rtmp
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
|
@ -41,30 +41,29 @@ import (
|
|||
)
|
||||
|
||||
// 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) {
|
||||
u, err := url.Parse(addr)
|
||||
if err != nil {
|
||||
log.Printf("failed to parse addr: %v", err)
|
||||
return protocol, host, port, app, playpath, err
|
||||
}
|
||||
|
||||
switch u.Scheme {
|
||||
case "rtmp":
|
||||
protocol = RTMP_PROTOCOL_RTMP
|
||||
protocol = protoRTMP
|
||||
case "rtmpt":
|
||||
protocol = RTMP_PROTOCOL_RTMPT
|
||||
protocol = protoRTMPT
|
||||
case "rtmps":
|
||||
protocol = RTMP_PROTOCOL_RTMPS
|
||||
protocol = protoRTMPS
|
||||
case "rtmpe":
|
||||
protocol = RTMP_PROTOCOL_RTMPE
|
||||
protocol = protoRTMPE
|
||||
case "rtmfp":
|
||||
protocol = RTMP_PROTOCOL_RTMFP
|
||||
protocol = protoRTMFP
|
||||
case "rtmpte":
|
||||
protocol = RTMP_PROTOCOL_RTMPTE
|
||||
protocol = protoRTMPTE
|
||||
case "rtmpts":
|
||||
protocol = RTMP_PROTOCOL_RTMPTS
|
||||
protocol = protoRTMPTS
|
||||
default:
|
||||
log.Printf("unknown scheme: %q", u.Scheme)
|
||||
return protocol, host, port, app, playpath, errUnknownScheme
|
||||
}
|
||||
|
||||
|
|
608
rtmp/rtmp.go
608
rtmp/rtmp.go
File diff suppressed because it is too large
Load Diff
|
@ -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
|
||||
}
|
|
@ -6,6 +6,8 @@ DESCRIPTION
|
|||
RTMP tests
|
||||
|
||||
AUTHORS
|
||||
Saxon Nelson-Milton <saxon@ausocean.org>
|
||||
Dan Kortschak <dan@ausocean.org>
|
||||
Alan Noble <alan@ausocean.org>
|
||||
|
||||
LICENSE
|
||||
|
@ -49,20 +51,22 @@ const (
|
|||
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.
|
||||
// 0: suppress logging completely
|
||||
// 1: log messages only
|
||||
// 2: log messages with errors, if any
|
||||
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
|
||||
|
||||
// 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
|
||||
|
||||
// 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{}) {
|
||||
logLevels := [...]string{"Debug", "Info", "Warn", "Error", "", "", "Fatal"}
|
||||
if testVerbosity == 0 {
|
||||
|
@ -71,21 +75,28 @@ func testLog(level int8, msg string, params ...interface{}) {
|
|||
if level < -1 || level > 5 {
|
||||
panic("Invalid log level")
|
||||
}
|
||||
if testVerbosity == 2 && len(params) >= 2 {
|
||||
// extract the params we know about, otherwise just print the message
|
||||
switch params[0].(string) {
|
||||
case "error":
|
||||
fmt.Printf("%s: %s, error=%v\n", logLevels[level+1], msg, params[1].(string))
|
||||
case "size":
|
||||
fmt.Printf("%s: %s, size=%d\n", logLevels[level+1], msg, params[1].(int))
|
||||
default:
|
||||
switch testVerbosity {
|
||||
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) {
|
||||
case "error":
|
||||
fmt.Printf("%s: %s, error=%v\n", logLevels[level+1], msg, params[1].(string))
|
||||
case "size":
|
||||
fmt.Printf("%s: %s, size=%d\n", logLevels[level+1], msg, params[1].(int))
|
||||
default:
|
||||
fmt.Printf("%s: %s\n", logLevels[level+1], msg)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("%s: %s\n", logLevels[level+1], msg)
|
||||
}
|
||||
} else {
|
||||
fmt.Printf("%s: %s\n", logLevels[level+1], msg)
|
||||
}
|
||||
if level == 5 {
|
||||
// Fatal
|
||||
if level >= 4 {
|
||||
// Error or Fatal
|
||||
buf := make([]byte, 1<<16)
|
||||
size := runtime.Stack(buf, true)
|
||||
fmt.Printf("%s\n", string(buf[:size]))
|
||||
|
@ -113,7 +124,7 @@ func TestSetupURL(t *testing.T) {
|
|||
if s.url != testBaseURL && s.link.timeout != testTimeout {
|
||||
t.Errorf("NewSession failed")
|
||||
}
|
||||
err := setupURL(s, s.url)
|
||||
err := setupURL(s)
|
||||
if err != nil {
|
||||
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
|
||||
// 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)
|
||||
for i := 0; i < 25; i++ {
|
||||
err := flvEncoder.Encode(b)
|
||||
if err != nil {
|
||||
t.Errorf("Encoding failed with error: %v", err)
|
||||
}
|
||||
time.Sleep(time.Millisecond / 25) // rate limit to 1/25s
|
||||
}
|
||||
|
||||
err = s.Close()
|
||||
|
|
138
rtmp/session.go
138
rtmp/session.go
|
@ -3,7 +3,7 @@ NAME
|
|||
session.go
|
||||
|
||||
DESCRIPTION
|
||||
See Readme.md
|
||||
RTMP session functionality.
|
||||
|
||||
AUTHORS
|
||||
Saxon Nelson-Milton <saxon@ausocean.org>
|
||||
|
@ -33,6 +33,12 @@ LICENSE
|
|||
*/
|
||||
package rtmp
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Session holds the state for an RTMP session.
|
||||
type Session struct {
|
||||
url string
|
||||
|
@ -62,6 +68,32 @@ type Session struct {
|
|||
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.
|
||||
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.
|
||||
func (s *Session) Open() error {
|
||||
s.log(DebugLevel, pkg+"Session.Open")
|
||||
if s.isConnected() {
|
||||
return errConnected
|
||||
}
|
||||
err := s.start()
|
||||
err := setupURL(s)
|
||||
if err != nil {
|
||||
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()
|
||||
err = connect(s)
|
||||
if err != nil {
|
||||
s.close()
|
||||
s.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
err = connectStream(s)
|
||||
if err != nil {
|
||||
s.close()
|
||||
s.Close()
|
||||
return err
|
||||
}
|
||||
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 {
|
||||
s.log(DebugLevel, pkg+"Session.Close")
|
||||
if !s.isConnected() {
|
||||
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.link.protocol&RTMP_FEATURE_WRITE != 0 {
|
||||
sendFCUnpublish(s)
|
||||
}
|
||||
sendDeleteStream(s, float64(s.streamID))
|
||||
if s.streamID > 0 {
|
||||
if s.link.protocol&featureWrite != 0 {
|
||||
sendFCUnpublish(s)
|
||||
}
|
||||
s.link.conn.Close()
|
||||
sendDeleteStream(s, float64(s.streamID))
|
||||
}
|
||||
s.link.conn.Close()
|
||||
*s = Session{}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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() {
|
||||
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 {
|
||||
return 0, err
|
||||
}
|
||||
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.
|
||||
func (s *Session) isConnected() bool {
|
||||
return s.link.conn != nil
|
||||
|
@ -173,5 +245,5 @@ func (s *Session) isConnected() bool {
|
|||
|
||||
// enableWrite enables the current session for writing.
|
||||
func (s *Session) enableWrite() {
|
||||
s.link.protocol |= RTMP_FEATURE_WRITE
|
||||
s.link.protocol |= featureWrite
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue