forked from yapingcat/gomedia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
487 lines (441 loc) · 13.7 KB
/
client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package rtmp
import (
"encoding/binary"
"errors"
"strings"
"github.com/yapingcat/gomedia/go-codec"
"github.com/yapingcat/gomedia/go-flv"
)
type RtmpConnectCmd int
const (
CONNECT RtmpConnectCmd = iota
CLOSE
CREATE_STREAM
GET_STREAM_LENGTH
)
type RtmpClient struct {
tcurl string
app string
streamName string
cmdChan *chunkStreamWriter
userCtrlChan *chunkStreamWriter
sourceChan *chunkStreamWriter
audioChan *chunkStreamWriter
videoChan *chunkStreamWriter
reader *chunkStreamReader
wndAckSize uint32
state RtmpParserState
streamState RtmpState
hs *clientHandShake
output OutputCB
onframe OnFrame
onstatus OnStatus
onerror OnError
onstateChange OnStateChange
videoDemuxer flv.VideoTagDemuxer
audioDemuxer flv.AudioTagDemuxer
videoMuxer flv.AVTagMuxer
audioMuxer flv.AVTagMuxer
timestamp uint32
lastMethod RtmpConnectCmd
lastMethodTid int
tid uint32
streamId uint32
writeChunkSize uint32
isPublish bool
}
func NewRtmpClient(options ...func(*RtmpClient)) *RtmpClient {
cli := &RtmpClient{
hs: newClientHandShake(),
cmdChan: newChunkStreamWriter(CHUNK_CHANNEL_CMD),
userCtrlChan: newChunkStreamWriter(CHUNK_CHANNEL_USE_CTRL),
sourceChan: newChunkStreamWriter(CHUNK_CHANNEL_NET_STREAM),
reader: newChunkStreamReader(FIX_CHUNK_SIZE),
tid: 4,
wndAckSize: DEFAULT_ACK_SIZE,
writeChunkSize: DEFAULT_CHUNK_SIZE,
isPublish: false,
}
for _, o := range options {
o(cli)
}
return cli
}
func WithChunkSize(chunkSize uint32) func(*RtmpClient) {
return func(rc *RtmpClient) {
if rc != nil {
rc.writeChunkSize = chunkSize
}
}
}
func WithComplexHandshake() func(*RtmpClient) {
return func(rc *RtmpClient) {
if rc != nil {
rc.hs.simpleHs = false
}
}
}
func WithComplexHandshakeSchema(schema int) func(*RtmpClient) {
return func(rc *RtmpClient) {
if rc != nil {
rc.hs.schema = schema
}
}
}
func WithWndAckSize(ackSize uint32) func(*RtmpClient) {
return func(rc *RtmpClient) {
if rc != nil {
rc.wndAckSize = ackSize
}
}
}
func WithEnablePublish() func(*RtmpClient) {
return func(rc *RtmpClient) {
if rc != nil {
rc.isPublish = true
}
}
}
func WithAudioMuxer(muxer flv.AVTagMuxer) func(*RtmpClient) {
return func(rc *RtmpClient) {
if rc != nil {
rc.audioMuxer = muxer
}
}
}
func (cli *RtmpClient) SetOutput(output OutputCB) {
cli.output = output
cli.hs.output = output
}
func (cli *RtmpClient) OnFrame(onframe OnFrame) {
cli.onframe = onframe
}
func (cli *RtmpClient) OnError(onerror OnError) {
cli.onerror = onerror
}
func (cli *RtmpClient) OnStatus(onstatus OnStatus) {
cli.onstatus = onstatus
}
func (cli *RtmpClient) OnStateChange(stateChange OnStateChange) {
cli.onstateChange = stateChange
}
//url start with "rtmp://"
func (cli *RtmpClient) Start(url string) {
loc := strings.Index(url, "rtmp://")
cli.tcurl = "rtmp://"
tmp := url[loc+7:]
loc = strings.Index(tmp, "/")
cli.tcurl += tmp[:loc]
tmp = tmp[loc+1:]
loc = strings.Index(tmp, "/")
cli.app = tmp[:loc]
cli.tcurl += "/" + cli.app
cli.streamName = tmp[loc+1:]
cli.hs.start()
}
func (cli *RtmpClient) GetState() RtmpState {
return cli.streamState
}
func (cli *RtmpClient) Input(data []byte) error {
switch cli.state {
case HandShake:
cli.changeState(STATE_HANDSHAKEING)
cli.hs.input(data)
if cli.hs.getState() != HANDSHAKE_DONE {
return nil
} else {
cli.changeState(STATE_RTMP_CONNECTING)
cli.state = ReadChunk
cmd := makeConnect(cli.app, cli.tcurl)
bufs := cli.cmdChan.writeData(cmd, Command_AMF0, 0, 0)
if err := cli.output(bufs); err != nil {
return err
}
cli.lastMethod = CONNECT
cli.lastMethodTid = 1
}
case ReadChunk:
err := cli.reader.readRtmpMessage(data, func(msg *rtmpMessage) error {
cli.timestamp = msg.timestamp
return cli.handleMessage(msg)
})
if err != nil {
return err
}
default:
panic("error state")
}
return nil
}
func (cli *RtmpClient) WriteFrame(cid codec.CodecID, frame []byte, pts, dts uint32) error {
if cid == codec.CODECID_AUDIO_AAC || cid == codec.CODECID_AUDIO_G711A || cid == codec.CODECID_AUDIO_G711U {
return cli.WriteAudio(cid, frame, pts, dts)
} else if cid == codec.CODECID_VIDEO_H264 || cid == codec.CODECID_VIDEO_H265 {
return cli.WriteVideo(cid, frame, pts, dts)
} else {
return errors.New("unsupport codec id")
}
}
func (cli *RtmpClient) WriteAudio(cid codec.CodecID, frame []byte, pts, dts uint32) error {
if cli.audioMuxer == nil {
cli.audioMuxer = flv.CreateAudioMuxer(flv.CovertCodecId2SoundFromat(cid))
}
if cli.audioChan == nil {
cli.audioChan = newChunkStreamWriter(CHUNK_CHANNEL_AUDIO)
cli.audioChan.chunkSize = cli.writeChunkSize
}
tags := cli.audioMuxer.Write(frame, pts, dts)
for _, tag := range tags {
pkt := cli.audioChan.writeData(tag, AUDIO, cli.streamId, dts)
if len(pkt) > 0 {
if err := cli.output(pkt); err != nil {
return err
}
}
}
return nil
}
func (cli *RtmpClient) WriteVideo(cid codec.CodecID, frame []byte, pts, dts uint32) error {
if cli.videoMuxer == nil {
cli.videoMuxer = flv.CreateVideoMuxer(flv.CovertCodecId2FlvVideoCodecId(cid))
}
if cli.videoChan == nil {
cli.videoChan = newChunkStreamWriter(CHUNK_CHANNEL_VIDEO)
cli.videoChan.chunkSize = cli.writeChunkSize
}
tags := cli.videoMuxer.Write(frame, pts, dts)
for _, tag := range tags {
pkt := cli.videoChan.writeData(tag, VIDEO, cli.streamId, dts)
if len(pkt) > 0 {
if err := cli.output(pkt); err != nil {
return err
}
}
}
return nil
}
func (cli *RtmpClient) changeState(newState RtmpState) {
if cli.streamState != newState {
cli.streamState = newState
if cli.onstateChange != nil {
cli.onstateChange(newState)
}
}
}
func (cli *RtmpClient) handleMessage(msg *rtmpMessage) error {
switch msg.msgtype {
case SET_CHUNK_SIZE:
if len(msg.msg) < 4 {
return errors.New("bytes of \"set chunk size\" < 4")
}
size := binary.BigEndian.Uint32(msg.msg)
cli.reader.chunkSize = size
case ABORT_MESSAGE:
//TODO
case ACKNOWLEDGEMENT:
if len(msg.msg) < 4 {
return errors.New("bytes of \"window acknowledgement size\" < 4")
}
cli.wndAckSize = binary.BigEndian.Uint32(msg.msg)
case USER_CONTROL:
return cli.handleUserEvent(msg.msg)
case WND_ACK_SIZE:
//TODO
case SET_PEER_BW:
//TODO
case AUDIO:
return cli.handleAudioMessage(msg)
case VIDEO:
return cli.handleVideoMessage(msg)
case Command_AMF0:
return cli.handleCommandRes(msg.msg)
case Command_AMF3:
case Metadata_AMF0:
case Metadata_AMF3:
case SharedObject_AMF0:
case SharedObject_AMF3:
case Aggregate:
default:
return errors.New("unkow message type")
}
return nil
}
func (cli *RtmpClient) handleUserEvent(data []byte) error {
event := decodeUserControlMsg(data)
switch event.code {
case StreamBegin:
case StreamEOF:
case StreamDry:
case SetBufferLength:
case StreamIsRecorded:
case PingRequest:
case PingResponse:
default:
panic("unkown event")
}
return nil
}
func (cli *RtmpClient) handleCommandRes(data []byte) error {
item := amf0Item{}
l := item.decode(data)
data = data[l:]
cmd := string(item.value.([]byte))
switch cmd {
case "_result":
return cli.handleResult(data)
case "_error":
return cli.handleError(data)
case "onStatus":
return cli.handleStatus(data)
default:
}
return nil
}
func (cli *RtmpClient) handleVideoMessage(msg *rtmpMessage) error {
if cli.videoDemuxer == nil {
cli.videoDemuxer = flv.CreateFlvVideoTagHandle(flv.GetFLVVideoCodecId(msg.msg))
cli.videoDemuxer.OnFrame(func(codecid codec.CodecID, frame []byte, cts int) {
dts := cli.timestamp
pts := dts + uint32(cts)
cli.onframe(codecid, pts, dts, frame)
})
}
return cli.videoDemuxer.Decode(msg.msg)
}
func (cli *RtmpClient) handleAudioMessage(msg *rtmpMessage) error {
if cli.audioDemuxer == nil {
cli.audioDemuxer = flv.CreateAudioTagDemuxer(flv.FLV_SOUND_FORMAT((msg.msg[0] >> 4) & 0x0F))
cli.audioDemuxer.OnFrame(func(codecid codec.CodecID, frame []byte) {
dts := cli.timestamp
pts := dts
cli.onframe(codecid, pts, dts, frame)
})
}
return cli.audioDemuxer.Decode(msg.msg)
}
func (cli *RtmpClient) handleResult(data []byte) error {
switch cli.lastMethod {
case CONNECT:
return cli.handleConnectResponse(data)
case CREATE_STREAM:
return cli.handleCreateStreamResponse(data)
case GET_STREAM_LENGTH:
//TODO
}
return nil
}
func (cli *RtmpClient) handleConnectResponse(data []byte) error {
items, _ := decodeAmf0(data)
if len(items) > 0 {
if tid, ok := items[0].value.(float64); ok {
if cli.lastMethodTid != int(tid) {
return nil
}
}
}
cli.lastMethod = CREATE_STREAM
cli.lastMethodTid = 2
if !cli.isPublish {
ack := makeAcknowledgementSize(cli.wndAckSize)
bufs := cli.userCtrlChan.writeData(ack, WND_ACK_SIZE, 0, 0)
cmd := makeCreateStream(cli.streamName, 2)
bufs = append(bufs, cli.cmdChan.writeData(cmd, Command_AMF0, 0, 0)...)
return cli.output(bufs)
} else {
buf := makeSetChunkSize(cli.writeChunkSize)
bufs := cli.userCtrlChan.writeData(buf, SET_CHUNK_SIZE, 0, 0)
cli.cmdChan.chunkSize = cli.writeChunkSize
cli.userCtrlChan.chunkSize = cli.writeChunkSize
cli.sourceChan.chunkSize = cli.writeChunkSize
buf = makeReleaseStream(cli.streamName)
bufs = append(bufs, cli.cmdChan.writeData(buf, Command_AMF0, 0, 0)...)
buf = makeFcPublish(cli.streamName)
bufs = append(bufs, cli.cmdChan.writeData(buf, Command_AMF0, 0, 0)...)
buf = makeCreateStream(cli.streamName, 2)
bufs = append(bufs, cli.cmdChan.writeData(buf, Command_AMF0, 0, 0)...)
return cli.output(bufs)
}
}
func (cli *RtmpClient) handleCreateStreamResponse(data []byte) error {
items, _ := decodeAmf0(data)
if len(items) > 0 {
if tid, ok := items[0].value.(float64); ok {
if cli.lastMethodTid != int(tid) {
return nil
}
}
if sid, ok := items[len(items)-1].value.(float64); ok {
cli.streamId = uint32(sid)
}
}
if !cli.isPublish {
cli.lastMethod = GET_STREAM_LENGTH
cli.lastMethodTid = 3
cmd := makeGetStreamLength(3, cli.streamName)
bufs := cli.cmdChan.writeData(cmd, Command_AMF0, cli.streamId, 0)
req := makePlay(int(cli.tid), cli.streamName, -1, -1, true)
bufs = append(bufs, cli.sourceChan.writeData(req, Command_AMF0, cli.streamId, 0)...)
return cli.output(bufs)
} else {
data := makePublish(cli.streamName, PUBLISHING_LIVE)
bufs := cli.cmdChan.writeData(data, Command_AMF0, cli.streamId, 0)
return cli.output(bufs)
}
}
func (cli *RtmpClient) handleError(data []byte) error {
code := ""
describe := ""
_, objs := decodeAmf0(data)
for _, obj := range objs {
for _, item := range obj.items {
if item.name == "code" {
code = string(item.value.value.([]byte))
} else if item.name == "describe" {
describe = string(item.value.value.([]byte))
}
if cli.onerror != nil {
cli.onerror(code, describe)
}
}
}
if cli.isPublish {
cli.changeState(STATE_RTMP_PUBLISH_FAILED)
} else {
cli.changeState(STATE_RTMP_PLAY_FAILED)
}
return nil
}
func (cli *RtmpClient) handleStatus(data []byte) error {
code := ""
level := ""
describe := ""
foundInfoObj := false
_, objs := decodeAmf0(data)
for _, obj := range objs {
for _, item := range obj.items {
if item.name == "code" {
foundInfoObj = true
code = string(item.value.value.([]byte))
} else if item.name == "level" {
level = string(item.value.value.([]byte))
} else if item.name == "description" {
describe = string(item.value.value.([]byte))
}
}
}
if cli.onstatus != nil && foundInfoObj {
cli.onstatus(code, level, describe)
}
if code == string(NETSTREAM_PUBLISH_START) {
cli.changeState(STATE_RTMP_PUBLISH_START)
} else if code == string(NETSTREAM_PLAY_START) {
cli.changeState(STATE_RTMP_PLAY_START)
} else if level == string(LEVEL_ERROR) {
if cli.isPublish {
cli.changeState(STATE_RTMP_PUBLISH_FAILED)
} else {
cli.changeState(STATE_RTMP_PLAY_FAILED)
}
}
return nil
}