main.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. package main
  2. import (
  3. "context"
  4. "encoding/binary"
  5. "fmt"
  6. "net"
  7. "os"
  8. "time"
  9. )
  10. // Use FFmpeg to push stream to this proxy:
  11. // ffmpeg -re -i ~/git/srs/trunk/doc/source.flv -c copy -pes_payload_size 0 -f mpegts 'srt://localhost:10081?streamid=#!::r=live/livestream?m=publish'
  12. // Play by SRT from this proxy:
  13. // ffplay 'srt://localhost:10081?streamid=#!::r=live/livestream,latency=20,m=request'
  14. var listenAddress = "127.0.0.1:10081"
  15. // Proxy to backend SRS Server.
  16. // Play by HTTP-FLV from SRS:
  17. // ffplay http://localhost:8080/live/livestream.flv
  18. // Play by SRT from SRS:
  19. // ffplay 'srt://localhost:10080?streamid=#!::r=live/livestream,latency=20,m=request'
  20. var backendAddress = "127.0.0.1:10080"
  21. func main() {
  22. fmt.Println("Hello, SRT!")
  23. if err := doMain(context.Background()); err != nil {
  24. fmt.Println(fmt.Sprintf("err %+v", err))
  25. os.Exit(1)
  26. }
  27. }
  28. func doMain(ctx context.Context) error {
  29. serverAddr, err := net.ResolveUDPAddr("udp", listenAddress)
  30. if err != nil {
  31. return err
  32. }
  33. server, err := net.ListenUDP("udp", serverAddr)
  34. if err != nil {
  35. return err
  36. }
  37. defer server.Close()
  38. fmt.Println("UDP server listening on", server.LocalAddr().String())
  39. start := time.Now()
  40. buf := make([]byte, 4096)
  41. connections := make(map[string]*SRTConnection)
  42. for {
  43. n, clientAddr, err := server.ReadFromUDP(buf)
  44. if err != nil {
  45. return err
  46. }
  47. connection, ok := connections[clientAddr.String()]
  48. if !ok {
  49. connection = &SRTConnection{
  50. start: start,
  51. server: server,
  52. serverAddr: serverAddr,
  53. clientAddr: clientAddr,
  54. }
  55. connections[clientAddr.String()] = connection
  56. fmt.Println("New connection from", clientAddr.String())
  57. }
  58. if err := connection.Consume(buf[:n]); err != nil {
  59. return err
  60. }
  61. fmt.Println(fmt.Sprintf("Received %v bytes from %s", n, clientAddr.String()))
  62. }
  63. return nil
  64. }
  65. type SRTConnection struct {
  66. // Listener start time.
  67. start time.Time
  68. // Local UDP server connection.
  69. server *net.UDPConn
  70. // Local UDP server listen address.
  71. serverAddr *net.UDPAddr
  72. // Client remote address.
  73. clientAddr *net.UDPAddr
  74. // Backend server connection.
  75. backend *net.UDPConn
  76. // Handshake packets with client.
  77. handshake0 *SRTHandshakePacket
  78. handshake1 *SRTHandshakePacket
  79. handshake2 *SRTHandshakePacket
  80. handshake3 *SRTHandshakePacket
  81. }
  82. func (v *SRTConnection) Close() error {
  83. if v.backend != nil {
  84. return v.backend.Close()
  85. }
  86. return nil
  87. }
  88. func (v *SRTConnection) Consume(b []byte) error {
  89. pkt := &SRTHandshakePacket{}
  90. if err := pkt.UnmarshalBinary(b); err != nil {
  91. return err
  92. }
  93. // Handle handshake messages.
  94. if pkt.IsHandshake() {
  95. if pkt.SynCookie == 0 {
  96. // Save handshake packet.
  97. v.handshake0 = pkt
  98. fmt.Println(fmt.Sprintf("Handshake 0: %v", v.handshake0.String()))
  99. // Response handshake 1.
  100. v.handshake1 = &SRTHandshakePacket{
  101. ControlFlag: pkt.ControlFlag,
  102. ControlType: 0,
  103. SubType: 0,
  104. AdditionalInfo: 0,
  105. Timestamp: uint32(time.Since(v.start).Microseconds()),
  106. SocketID: pkt.SRTSocketID,
  107. Version: 5,
  108. EncryptionField: 0,
  109. ExtensionField: 0x4A17,
  110. InitSequence: pkt.InitSequence,
  111. MTU: pkt.MTU,
  112. FlowWindow: pkt.FlowWindow,
  113. HandshakeType: 1,
  114. SRTSocketID: pkt.SRTSocketID,
  115. SynCookie: 0x418d5e4e,
  116. PeerIP: v.serverAddr.IP,
  117. }
  118. fmt.Println(fmt.Sprintf("Handshake 1: %v", v.handshake1.String()))
  119. if b, err := v.handshake1.MarshalBinary(); err != nil {
  120. return err
  121. } else if _, err = v.server.WriteToUDP(b, v.clientAddr); err != nil {
  122. return err
  123. }
  124. return nil
  125. } else {
  126. // Save handshake packet.
  127. v.handshake2 = pkt
  128. fmt.Println(fmt.Sprintf("Handshake 2: %v", v.handshake2.String()))
  129. // Ignore if already connected.
  130. if v.backend == nil {
  131. remoteAddress, err := net.ResolveUDPAddr("udp", backendAddress)
  132. if err != nil {
  133. return err
  134. }
  135. if v.backend, err = net.DialUDP("udp", nil, remoteAddress); err != nil {
  136. return err
  137. }
  138. }
  139. // Proxy handshake 0 to backend server.
  140. if b, err := v.handshake0.MarshalBinary(); err != nil {
  141. return err
  142. } else if _, err = v.backend.Write(b); err != nil {
  143. return err
  144. }
  145. fmt.Println(fmt.Sprintf("Proxy send handshake 0: %v", v.handshake0.String()))
  146. // Read handshake 1 from backend server.
  147. b := make([]byte, 4096)
  148. handshake1p := &SRTHandshakePacket{}
  149. if nn, err := v.backend.Read(b); err != nil {
  150. return err
  151. } else if err := handshake1p.UnmarshalBinary(b[:nn]); err != nil {
  152. return err
  153. }
  154. fmt.Println(fmt.Sprintf("Proxy got handshake 1: %v", handshake1p.String()))
  155. // Proxy handshake 2 to backend server.
  156. handshake2p := *v.handshake2
  157. handshake2p.SynCookie = handshake1p.SynCookie
  158. if b, err := handshake2p.MarshalBinary(); err != nil {
  159. return err
  160. } else if _, err = v.backend.Write(b); err != nil {
  161. return err
  162. }
  163. fmt.Println(fmt.Sprintf("Proxy send handshake 2: %v", handshake2p.String()))
  164. // Read handshake 3 from backend server.
  165. handshake3p := &SRTHandshakePacket{}
  166. if nn, err := v.backend.Read(b); err != nil {
  167. return err
  168. } else if err := handshake3p.UnmarshalBinary(b[:nn]); err != nil {
  169. return err
  170. }
  171. fmt.Println(fmt.Sprintf("Proxy got handshake 3: %v", handshake3p.String()))
  172. // Response handshake 3 to client.
  173. v.handshake3 = &*handshake3p
  174. v.handshake3.SynCookie = v.handshake1.SynCookie
  175. fmt.Println(fmt.Sprintf("Handshake 3: %v", v.handshake3.String()))
  176. if b, err := v.handshake3.MarshalBinary(); err != nil {
  177. return err
  178. } else if _, err = v.server.WriteToUDP(b, v.clientAddr); err != nil {
  179. return err
  180. }
  181. // Start a goroutine to proxy message from backend to client.
  182. go func() {
  183. for {
  184. nn, err := v.backend.Read(b)
  185. if err != nil {
  186. return
  187. } else if _, err = v.server.WriteToUDP(b[:nn], v.clientAddr); err != nil {
  188. return
  189. }
  190. fmt.Println(fmt.Sprintf("Proxy got %d bytes from backend server.", nn))
  191. }
  192. }()
  193. return nil
  194. }
  195. }
  196. // Proxy all other messages to backend server.
  197. if _, err := v.backend.Write(b); err != nil {
  198. return err
  199. }
  200. fmt.Println(fmt.Sprintf("Packet: %v", pkt))
  201. return nil
  202. }
  203. // See https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-3.2
  204. // See https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-3.2.1
  205. type SRTHandshakePacket struct {
  206. // F: 1 bit. Packet Type Flag. The control packet has this flag set to
  207. // "1". The data packet has this flag set to "0".
  208. ControlFlag uint8
  209. // Control Type: 15 bits. Control Packet Type. The use of these bits
  210. // is determined by the control packet type definition.
  211. // Handshake control packets (Control Type = 0x0000) are used to
  212. // exchange peer configurations, to agree on connection parameters, and
  213. // to establish a connection.
  214. ControlType uint16
  215. // Subtype: 16 bits. This field specifies an additional subtype for
  216. // specific packets.
  217. SubType uint16
  218. // Type-specific Information: 32 bits. The use of this field depends on
  219. // the particular control packet type. Handshake packets do not use
  220. // this field.
  221. AdditionalInfo uint32
  222. // Timestamp: 32 bits.
  223. Timestamp uint32
  224. // Destination Socket ID: 32 bits.
  225. SocketID uint32
  226. // Version: 32 bits. A base protocol version number. Currently used
  227. // values are 4 and 5. Values greater than 5 are reserved for future
  228. // use.
  229. Version uint32
  230. // Encryption Field: 16 bits. Block cipher family and key size. The
  231. // values of this field are described in Table 2. The default value
  232. // is AES-128.
  233. // 0 | No Encryption Advertised
  234. // 2 | AES-128
  235. // 3 | AES-192
  236. // 4 | AES-256
  237. EncryptionField uint16
  238. // Extension Field: 16 bits. This field is message specific extension
  239. // related to Handshake Type field. The value MUST be set to 0
  240. // except for the following cases. (1) If the handshake control
  241. // packet is the INDUCTION message, this field is sent back by the
  242. // Listener. (2) In the case of a CONCLUSION message, this field
  243. // value should contain a combination of Extension Type values.
  244. // 0x00000001 | HSREQ
  245. // 0x00000002 | KMREQ
  246. // 0x00000004 | CONFIG
  247. // 0x4A17 if HandshakeType is INDUCTION, see https://datatracker.ietf.org/doc/html/draft-sharabayko-srt-01#section-4.3.1.1
  248. ExtensionField uint16
  249. // Initial Packet Sequence Number: 32 bits. The sequence number of the
  250. // very first data packet to be sent.
  251. InitSequence uint32
  252. // Maximum Transmission Unit Size: 32 bits. This value is typically set
  253. // to 1500, which is the default Maximum Transmission Unit (MTU) size
  254. // for Ethernet, but can be less.
  255. MTU uint32
  256. // Maximum Flow Window Size: 32 bits. The value of this field is the
  257. // maximum number of data packets allowed to be "in flight" (i.e. the
  258. // number of sent packets for which an ACK control packet has not yet
  259. // been received).
  260. FlowWindow uint32
  261. // Handshake Type: 32 bits. This field indicates the handshake packet
  262. // type.
  263. // 0xFFFFFFFD | DONE
  264. // 0xFFFFFFFE | AGREEMENT
  265. // 0xFFFFFFFF | CONCLUSION
  266. // 0x00000000 | WAVEHAND
  267. // 0x00000001 | INDUCTION
  268. HandshakeType uint32
  269. // SRT Socket ID: 32 bits. This field holds the ID of the source SRT
  270. // socket from which a handshake packet is issued.
  271. SRTSocketID uint32
  272. // SYN Cookie: 32 bits. Randomized value for processing a handshake.
  273. // The value of this field is specified by the handshake message
  274. // type.
  275. SynCookie uint32
  276. // Peer IP Address: 128 bits. IPv4 or IPv6 address of the packet's
  277. // sender. The value consists of four 32-bit fields.
  278. PeerIP net.IP
  279. // Extensions.
  280. // Extension Type: 16 bits. The value of this field is used to process
  281. // an integrated handshake. Each extension can have a pair of
  282. // request and response types.
  283. // Extension Length: 16 bits. The length of the Extension Contents
  284. // field in four-byte blocks.
  285. // Extension Contents: variable length. The payload of the extension.
  286. ExtraData []byte
  287. }
  288. func (v *SRTHandshakePacket) IsControl() bool {
  289. return v.ControlFlag == 0x80
  290. }
  291. func (v *SRTHandshakePacket) IsHandshake() bool {
  292. return v.IsControl() && v.ControlType == 0x00 && v.SubType == 0x00
  293. }
  294. func (v *SRTHandshakePacket) String() string {
  295. return fmt.Sprintf("Control=%v, CType=%v, SType=%v, Timestamp=%v, SocketID=%v, Version=%v, Encrypt=%v, Extension=%v, InitSequence=%v, MTU=%v, FlowWnd=%v, HSType=%v, SRTSocketID=%v, Cookie=%v, Peer=%vB, Extra=%vB",
  296. v.IsControl(), v.ControlType, v.SubType, v.Timestamp, v.SocketID, v.Version, v.EncryptionField, v.ExtensionField, v.InitSequence, v.MTU, v.FlowWindow, v.HandshakeType, v.SRTSocketID, v.SynCookie, len(v.PeerIP), len(v.ExtraData))
  297. }
  298. func (v *SRTHandshakePacket) UnmarshalBinary(b []byte) error {
  299. if len(b) < 4 {
  300. return fmt.Errorf("Invalid packet length %v", len(b))
  301. }
  302. v.ControlFlag = b[0] & 0x80
  303. v.ControlType = binary.BigEndian.Uint16(b[0:2]) & 0x7fff
  304. v.SubType = binary.BigEndian.Uint16(b[2:4])
  305. if !v.IsHandshake() {
  306. return nil
  307. }
  308. if len(b) < 64 {
  309. return fmt.Errorf("Invalid packet length %v", len(b))
  310. }
  311. v.AdditionalInfo = binary.BigEndian.Uint32(b[4:])
  312. v.Timestamp = binary.BigEndian.Uint32(b[8:])
  313. v.SocketID = binary.BigEndian.Uint32(b[12:])
  314. v.Version = binary.BigEndian.Uint32(b[16:])
  315. v.EncryptionField = binary.BigEndian.Uint16(b[20:])
  316. v.ExtensionField = binary.BigEndian.Uint16(b[22:])
  317. v.InitSequence = binary.BigEndian.Uint32(b[24:])
  318. v.MTU = binary.BigEndian.Uint32(b[28:])
  319. v.FlowWindow = binary.BigEndian.Uint32(b[32:])
  320. v.HandshakeType = binary.BigEndian.Uint32(b[36:])
  321. v.SRTSocketID = binary.BigEndian.Uint32(b[40:])
  322. v.SynCookie = binary.BigEndian.Uint32(b[44:])
  323. // Only support IPv4.
  324. v.PeerIP = net.IPv4(b[51], b[50], b[49], b[48])
  325. v.ExtraData = b[64:]
  326. return nil
  327. }
  328. func (v *SRTHandshakePacket) MarshalBinary() ([]byte, error) {
  329. b := make([]byte, 64+len(v.ExtraData))
  330. binary.BigEndian.PutUint16(b, uint16(v.ControlFlag)<<8|v.ControlType)
  331. binary.BigEndian.PutUint16(b[2:], v.SubType)
  332. binary.BigEndian.PutUint32(b[4:], v.AdditionalInfo)
  333. binary.BigEndian.PutUint32(b[8:], v.Timestamp)
  334. binary.BigEndian.PutUint32(b[12:], v.SocketID)
  335. binary.BigEndian.PutUint32(b[16:], v.Version)
  336. binary.BigEndian.PutUint16(b[20:], v.EncryptionField)
  337. binary.BigEndian.PutUint16(b[22:], v.ExtensionField)
  338. binary.BigEndian.PutUint32(b[24:], v.InitSequence)
  339. binary.BigEndian.PutUint32(b[28:], v.MTU)
  340. binary.BigEndian.PutUint32(b[32:], v.FlowWindow)
  341. binary.BigEndian.PutUint32(b[36:], v.HandshakeType)
  342. binary.BigEndian.PutUint32(b[40:], v.SRTSocketID)
  343. binary.BigEndian.PutUint32(b[44:], v.SynCookie)
  344. // Only support IPv4.
  345. ip := v.PeerIP.To4()
  346. b[48] = ip[3]
  347. b[49] = ip[2]
  348. b[50] = ip[1]
  349. b[51] = ip[0]
  350. if len(v.ExtraData) > 0 {
  351. copy(b[64:], v.ExtraData)
  352. }
  353. return b, nil
  354. }