forked from iizukanao/node-rtsp-rtmp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtmp.coffee
2373 lines (2140 loc) · 75.2 KB
/
rtmp.coffee
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# RTMP/RTMPE/RTMPT/RTMPTE server
#
# RTMP specification is available at:
# http://wwwimages.adobe.com/content/dam/Adobe/en/devnet/rtmp/pdf/rtmp_specification_1.0.pdf
net = require 'net'
url = require 'url'
crypto = require 'crypto'
Sequent = require 'sequent'
rtmp_handshake = require './rtmp_handshake'
codec_utils = require './codec_utils'
config = require './config'
h264 = require './h264'
aac = require './aac'
flv = require './flv'
avstreams = require './avstreams'
logger = require './logger'
# enum
SESSION_STATE_NEW = 1
SESSION_STATE_HANDSHAKE_ONGOING = 2
SESSION_STATE_HANDSHAKE_DONE = 3
AVC_PACKET_TYPE_SEQUENCE_HEADER = 0
AVC_PACKET_TYPE_NALU = 1
AVC_PACKET_TYPE_END_OF_SEQUENCE = 2
TIMESTAMP_ROUNDOFF = 4294967296 # 32 bits
DEBUG_INCOMING_RTMP_PACKETS = false
DEBUG_OUTGOING_RTMP_PACKETS = false
RTMPT_SEND_REQUEST_BUFFER_SIZE = 10
# Number of active sessions
sessionsCount = 0
# Active sessions
sessions = {}
# Number of active RTMPT sessions
rtmptSessionsCount = 0
# Active RTMPT sessions
rtmptSessions = {}
# The newest client ID
clientMaxId = 0
queuedRTMPMessages = {}
# Generate a new client ID without collision
generateNewClientID = ->
clientID = generateClientID()
while sessions[clientID]?
clientID = generateClientID()
return clientID
# Generate a new random client ID (like Cookie)
generateClientID = ->
possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
numPossible = possible.length
clientID = ''
for i in [0..7]
clientID += possible.charAt((Math.random() * numPossible) | 0)
return clientID
parseAcknowledgementMessage = (buf) ->
sequenceNumber = (buf[0] * Math.pow(256, 3)) + (buf[1] << 16) + (buf[2] << 8) + buf[3]
return {
sequenceNumber: sequenceNumber
}
convertPTSToMilliseconds = (pts) ->
Math.round pts / 90
createAudioMessage = (params) ->
# TODO: Use type 1/2/3
audioMessage = createRTMPMessage
chunkStreamID: 4
timestamp: params.timestamp
messageTypeID: 0x08 # Audio Data
messageStreamID: 1
body: params.body
, params.chunkSize
queueVideoMessage = (stream, params) ->
params.avType = 'video'
params.chunkStreamID = 4
params.messageTypeID = 0x09 # Video Data
params.messageStreamID = 1
params.originalTimestamp = params.timestamp
if queuedRTMPMessages[stream.id]?
queuedRTMPMessages[stream.id].push params
else
queuedRTMPMessages[stream.id] = [ params ]
setImmediate ->
flushRTMPMessages stream
queueAudioMessage = (stream, params) ->
params.avType = 'audio'
params.chunkStreamID = 4
params.messageTypeID = 0x08 # Audio Data
params.messageStreamID = 1
params.originalTimestamp = params.timestamp
if queuedRTMPMessages[stream.id]?
queuedRTMPMessages[stream.id].push params
else
queuedRTMPMessages[stream.id] = [ params ]
setImmediate ->
flushRTMPMessages stream
createVideoMessage = (params) ->
# TODO: Use type 1/2/3
videoMessage = createRTMPMessage
chunkStreamID: 4
timestamp: params.timestamp
messageTypeID: 0x09 # Video Data
messageStreamID: 1
body: params.body
, params.chunkSize
parseUserControlMessage = (buf) ->
eventType = (buf[0] << 8) + buf[1]
eventData = buf[2..]
message =
eventType: eventType
eventData: eventData
if eventType is 3 # SetBufferLength
# first 4 bytes: stream ID
message.streamID = (eventData[0] << 24) + (eventData[1] << 16) +
(eventData[2] << 8) + eventData[3]
# next 4 bytes: buffer length in milliseconds
message.bufferLength = (eventData[4] << 24) + (eventData[5] << 16) +
(eventData[6] << 8) + eventData[7]
return message
parseIEEE754Double = (buf) ->
sign = buf[0] >> 7 # 1 == negative
exponent = ((buf[0] & 0b1111111) << 4) + (buf[1] >> 4)
exponent -= 1023 # because 1023 means zero
fraction = 1
for i in [0..51]
byteIndex = 1 + parseInt (i + 4) / 8
bitIndex = 7 - (i + 4) % 8
bitValue = (buf[byteIndex] >> bitIndex) & 0b1
if bitValue > 0
fraction += Math.pow(2, -(i+1))
value = fraction * Math.pow 2, exponent
if sign is 1
value = -value
value
parseAMF0StrictArray = (buf) ->
arr = []
len = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3]
readLen = 4
while len-- >= 0
result = parseAMF0Data buf[readLen..]
arr.push result.value
readLen += result.readLen
return { value: arr, readLen: readLen }
parseAMF0ECMAArray = (buf) ->
obj = {}
bufLen = buf.length
readLen = 0
while readLen < bufLen
nameLen = (buf[readLen++] << 8) + buf[readLen++]
name = buf.toString 'utf8', readLen, readLen + nameLen
readLen += nameLen
result = parseAMF0Data buf[readLen..]
readLen += result.readLen
if result.type is 'object-end-marker'
break
obj[name] = result.value
return { value: obj, readLen: readLen }
# Decode AMF0 data message buffer into AMF0 packets
parseAMF0DataMessage = (buf) ->
amf0Packets = []
remainingLen = buf.length
while remainingLen > 0
result = parseAMF0Data buf
amf0Packets.push result
remainingLen -= result.readLen
buf = buf[result.readLen..]
return {
objects: amf0Packets
}
# Decode buffer into AMF0 packets
parseAMF0CommandMessage = (buf) ->
amf0Packets = []
remainingLen = buf.length
while remainingLen > 0
result = parseAMF0Data buf
amf0Packets.push result
remainingLen -= result.readLen
buf = buf[result.readLen..]
return {
command: amf0Packets[0].value
transactionID: amf0Packets[1].value
objects: amf0Packets[2..]
}
parseAMF0Data = (buf) ->
i = 0
type = buf[i++]
if type is 0x00 # number-marker
value = buf.readDoubleBE i
return { type: 'number', value: value, readLen: i + 8 }
else if type is 0x01 # boolean-marker
value = if buf[i] is 0x00 then false else true
return { type: 'boolean', value: value, readLen: i + 1 }
else if type is 0x02 # string-marker
strLen = (buf[i++] << 8) + buf[i++]
value = buf.toString 'utf8', i, i+strLen
return { type: 'string', value: value, readLen: i + strLen }
else if type is 0x03 # object-marker
result = parseAMF0ECMAArray buf[i..]
return { type: 'object', value: result.value, readLen: i + result.readLen }
else if type is 0x05 # null-marker
return { type: 'null', value: null, readLen: i }
else if type is 0x06 # undefined-marker
return { type: 'undefined', value: undefined, readLen: i }
else if type is 0x08 # ecma-array-marker
# associative-count (4 bytes) is safe to be ignored, right?
result = parseAMF0ECMAArray buf[i+4..]
return { type: 'array', value: result.value, readLen: i + 4 + result.readLen }
else if type is 0x09 # object-end-marker
return { type: 'object-end-marker', readLen: 3 }
else if type is 0x0a # strict-array-marker
result = parseAMF0StrictArray buf[i..]
return { type: 'strict-array', value: result.value, readLen: i + result.readLen }
else if type is 0x0b # date-marker
time = buf.readDoubleBE i
date = new Date(time)
return { type: 'date', value: date, readLen: i + 10 } # 8 (time) + 2 (time-zone)
else
# TODO: sometimes fails to parse data sent by rtmpdump
throw new Error "Unknown AMF0 data type: #{type}"
createAMF0Data = (data) ->
type = typeof data
buf = null
if type is 'number'
buf = new Buffer 9
buf[0] = 0x00 # number-marker
buf.writeDoubleBE data, 1
else if type is 'boolean'
buf = new Buffer 2
buf[0] = 0x01 # boolean-marker
buf[1] = if data then 0x01 else 0x00
else if type is 'string'
buf = new Buffer 3
buf[0] = 0x02 # string-marker
strBytes = new Buffer data, 'utf8'
strLen = strBytes.length
buf[1] = (strLen >> 8) & 0xff
buf[2] = strLen & 0xff
buf = Buffer.concat [buf, strBytes], 3 + strLen
else if data is null
buf = new Buffer [ 0x05 ] # null-marker
else if type is 'undefined'
buf = new Buffer [ 0x06 ] # undefined-marker
else if data instanceof Date
buf = new Buffer 11
buf[0] = 0x0b # date-marker
buf.writeDoubleBE data.getTime(), 1
# Time-zone should be 0x0000
buf[9] = 0
buf[10] = 0
else if data instanceof Array
buf = new Buffer [ 0x0a ] # strict-array-marker
buf = createAMF0StrictArray data, buf
else if type is 'object'
count = Object.keys(data).length
buf = new Buffer [
# ecma-array-marker
0x08,
# array-count
(count >>> 24) & 0xff,
(count >>> 16) & 0xff,
(count >>> 8) & 0xff,
count & 0xff
]
buf = createAMF0ECMAArray data, buf
else
throw new Error "Unknown data type \"#{type}\" for data #{data}"
buf
createAMF0StrictArray = (arr, buf=null) ->
bufs = []
totalLength = 0
if buf?
bufs.push buf
totalLength += buf.length
# array-count (U32)
arrLen = arr.length
bufs.push new Buffer [
(arrLen >>> 24) & 0xff,
(arrLen >>> 16) & 0xff,
(arrLen >>> 8) & 0xff,
arrLen & 0xff
]
totalLength += 4
for value, i in arr
valueBytes = createAMF0Data value
bufs.push valueBytes
totalLength += valueBytes.length
return Buffer.concat bufs, totalLength
createAMF0Object = (obj) ->
buf = new Buffer [ 0x03 ] # object-marker
return createAMF0ECMAArray obj, buf
createAMF0ECMAArray = (obj, buf=null) ->
bufs = []
totalLength = 0
if buf?
bufs.push buf
totalLength += buf.length
for name, value of obj
nameBytes = new Buffer name, 'utf8'
nameLen = nameBytes.length
nameLenBytes = new Buffer 2
nameLenBytes[0] = (nameLen >> 8) & 0xff
nameLenBytes[1] = nameLen & 0xff
dataBytes = createAMF0Data value
bufs.push nameLenBytes, nameBytes, dataBytes
totalLength += 2 + nameLen + dataBytes.length
# Add object-end-marker
bufs.push new Buffer [0x00, 0x00, 0x09]
totalLength += 3
return Buffer.concat bufs, totalLength
counter = 0
flushRTMPMessages = (stream) ->
if not stream?
logger.error "[rtmp] error: flushRTMPMessages: Invalid stream"
return
if queuedRTMPMessages[stream.id].length < config.rtmpMessageQueueSize
# not enough buffer
return
rtmpMessagesToSend = queuedRTMPMessages[stream.id]
queuedRTMPMessages[stream.id] = []
if rtmpMessagesToSend.length is 0
# nothing to send
return
# mostRecentAVType = queuedRTMPMessages[stream.id][queuedRTMPMessages[stream.id].length-1].avType
# largestIndex = null
# for i in [queuedRTMPMessages[stream.id].length-2..0]
# rtmpMessage = queuedRTMPMessages[stream.id][i]
# if rtmpMessage.avType isnt mostRecentAVType
# largestIndex = i
# break
# if largestIndex is null
# return
#
# rtmpMessagesToSend = queuedRTMPMessages[stream.id][0..largestIndex]
# queuedRTMPMessages[stream.id] = queuedRTMPMessages[stream.id][largestIndex+1..]
allSessions = []
for clientID, session of rtmptSessions
allSessions.push session.rtmpSession
for clientID, session of sessions
allSessions.push session
for session in allSessions
if session.streamId isnt stream.id # The session is not associated with current stream
continue
msgs = null
# If video starts with an inter frame, Flash Player might
# shows images looks like a glitch until the first keyframe.
if session.isWaitingForKeyFrame
if config.rtmpWaitForKeyFrame
if stream.isVideoStarted # has video stream
for rtmpMessage, i in rtmpMessagesToSend
if (rtmpMessage.avType is 'video') and rtmpMessage.isKeyFrame
logger.info "[rtmp:#{session.clientid}] started streaming"
session.isPlaying = true
session.playStartTimestamp = rtmpMessage.originalTimestamp
session.playStartDateTime = Date.now() # TODO: Should we use slower process.hrtime()?
session.isWaitingForKeyFrame = false
msgs = rtmpMessagesToSend[i..]
break
else # audio only
logger.info "[rtmp:#{session.clientid}] started streaming"
session.isPlaying = true
session.playStartTimestamp = rtmpMessagesToSend[0].originalTimestamp
session.playStartDateTime = Date.now()
session.isWaitingForKeyFrame = false
msgs = rtmpMessagesToSend
else # Do not wait for a keyframe
logger.info "[rtmp:#{session.clientid}] started streaming"
session.isPlaying = true
session.playStartTimestamp = rtmpMessagesToSend[0].originalTimestamp
session.playStartDateTime = Date.now()
session.isWaitingForKeyFrame = false
msgs = rtmpMessagesToSend
else
msgs = rtmpMessagesToSend
if not msgs?
continue
if session.isPlaying
for rtmpMessage in msgs
# get milliseconds elapsed since play start
rtmpMessage.timestamp = session.getScaledTimestamp(rtmpMessage.originalTimestamp) % TIMESTAMP_ROUNDOFF
if msgs.length > 1
buf = createRTMPAggregateMessage msgs, session.chunkSize
if DEBUG_OUTGOING_RTMP_PACKETS
logger.info "send RTMP aggregate message: #{buf.length} bytes"
else
buf = createRTMPMessage msgs[0], session.chunkSize
if DEBUG_OUTGOING_RTMP_PACKETS
logger.info "send RTMP message: #{buf.length} bytes"
session.sendData buf
return
# RTMP Message Header used in Aggregate Message
createMessageHeader = (params) ->
payloadLength = params.body.length
if not params.messageTypeID?
logger.warn "[rtmp] warning: createMessageHeader(): messageTypeID is not set"
if not params.timestamp?
logger.warn "[rtmp] warning: createMessageHeader(): timestamp is not set"
if not params.messageStreamID?
logger.warn "[rtmp] warning: createMessageHeader(): messageStreamID is not set"
# 6.1.1. Message Header
return new Buffer [
params.messageTypeID,
# Payload length (3 bytes) big-endian
(payloadLength >> 16) & 0xff,
(payloadLength >> 8) & 0xff,
payloadLength & 0xff,
# Timestamp (4 bytes) big-endian (unusual format; not sure)
(params.timestamp >>> 16) & 0xff,
(params.timestamp >>> 8) & 0xff,
params.timestamp & 0xff,
(params.timestamp >>> 24) & 0xff,
# Stream ID (3 bytes) big-endian
(params.messageStreamID >> 16) & 0xff,
(params.messageStreamID >> 8) & 0xff,
params.messageStreamID & 0xff,
]
# All sub-messages must have the same chunk stream ID
createRTMPAggregateMessage = (rtmpMessages, chunkSize) ->
bufs = []
totalLength = 0
aggregateTimestamp = null
for rtmpMessage in rtmpMessages
if not aggregateTimestamp?
aggregateTimestamp = rtmpMessage.timestamp
header = createMessageHeader rtmpMessage
len = header.length + rtmpMessage.body.length
bufs.push header, rtmpMessage.body, new Buffer [
# Back pointer (UI32)
(len >>> 24) & 0xff,
(len >>> 16) & 0xff,
(len >>> 8) & 0xff,
len & 0xff
]
totalLength += len + 4
aggregateBody = Buffer.concat bufs, totalLength
createRTMPMessage
chunkStreamID: 4
timestamp: aggregateTimestamp
messageTypeID: 22 # Aggregate Message
messageStreamID: 1
body: aggregateBody
, chunkSize
createRTMPType1Message = (params) ->
bodyLength = params.body.length
formatTypeID = 1
if not params.body?
logger.warn "[rtmp] warning: createRTMPType1Message(): body is not set for RTMP message"
if not params.chunkStreamID?
logger.warn "[rtmp] warning: createRTMPType1Message(): chunkStreamID is not set for RTMP message"
if not params.timestampDelta?
logger.warn "[rtmp] warning: createRTMPType1Message(): timestampDelta is not set for RTMP message"
if not params.messageStreamID?
logger.warn "[rtmp] warning: createRTMPType1Message(): messageStreamID is not set for RTMP message"
useExtendedTimestamp = false
if params.timestampDelta >= 0xffffff
useExtendedTimestamp = true
ordinaryTimestampBytes = [ 0xff, 0xff, 0xff ]
else
ordinaryTimestampBytes = [
(params.timestampDelta >> 16) & 0xff,
(params.timestampDelta >> 8) & 0xff,
params.timestampDelta & 0xff,
]
# Header for Type 1 Chunk Message Header
header = new Buffer [
# Format (2 bits), Chunk Stream ID (6 bits)
(formatTypeID << 6) | params.chunkStreamID,
# Timestamp Delta (3 bytes)
ordinaryTimestampBytes[0],
ordinaryTimestampBytes[1],
ordinaryTimestampBytes[2],
# Message Length (3 bytes)
(bodyLength >> 16) & 0xff,
(bodyLength >> 8) & 0xff,
bodyLength & 0xff,
# Message Type ID (1 byte)
params.messageTypeID,
]
if useExtendedTimestamp
extendedTimestamp = new Buffer [
(params.timestampDelta >> 24) & 0xff,
(params.timestampDelta >> 16) & 0xff,
(params.timestampDelta >> 8) & 0xff,
params.timestampDelta & 0xff,
]
header = Buffer.concat [
header, extendedTimestamp
], 12
body = params.body
return Buffer.concat [header, body], 8 + bodyLength
createRTMPMessage = (params, chunkSize=128) ->
bodyLength = params.body.length
# TODO: Use format type ID 1 and 2
formatTypeID = 0
if not params.body?
logger.warn "[rtmp] warning: createRTMPMessage(): body is not set for RTMP message"
if not params.chunkStreamID?
logger.warn "[rtmp] warning: createRTMPMessage(): chunkStreamID is not set for RTMP message"
if not params.timestamp?
logger.warn "[rtmp] warning: createRTMPMessage(): timestamp is not set for RTMP message"
if not params.messageStreamID?
logger.warn "[rtmp] warning: createRTMPMessage(): messageStreamID is not set for RTMP message"
useExtendedTimestamp = false
if params.timestamp >= 0xffffff
useExtendedTimestamp = true
timestamp = [ 0xff, 0xff, 0xff ]
else
timestamp = [
(params.timestamp >> 16) & 0xff,
(params.timestamp >> 8) & 0xff,
params.timestamp & 0xff,
]
bufs = [
# Header for Type 0 Chunk Message Header
new Buffer [
# Format (2 bits), Chunk Stream ID (6 bits)
(formatTypeID << 6) | params.chunkStreamID,
# Timestamp (3 bytes)
timestamp[0],
timestamp[1],
timestamp[2],
# Message Length (3 bytes)
(bodyLength >> 16) & 0xff,
(bodyLength >> 8) & 0xff,
bodyLength & 0xff,
# Message Type ID (1 byte)
params.messageTypeID,
# Message Stream ID (4 bytes) little-endian
params.messageStreamID & 0xff
(params.messageStreamID >>> 8) & 0xff,
(params.messageStreamID >>> 16) & 0xff,
(params.messageStreamID >>> 24) & 0xff,
]
]
totalLength = 12
if useExtendedTimestamp
bufs.push new Buffer [
(params.timestamp >> 24) & 0xff,
(params.timestamp >> 16) & 0xff,
(params.timestamp >> 8) & 0xff,
params.timestamp & 0xff,
]
totalLength += 4
body = params.body
if bodyLength > chunkSize
bufs.push body[0...chunkSize]
totalLength += chunkSize
body = body[chunkSize..]
bodyLength -= chunkSize
# Use Format Type 3 for remaining chunks
type3Header = new Buffer [
(3 << 6) | params.chunkStreamID
]
loop
bodyChunk = body[0...chunkSize]
bodyChunkLen = bodyChunk.length
bufs.push type3Header, bodyChunk
totalLength += 1 + bodyChunkLen
body = body[bodyChunkLen..]
bodyLength -= bodyChunkLen
if bodyLength is 0
break
else
bufs.push body
totalLength += bodyLength
return Buffer.concat bufs, totalLength
createAMF0DataMessage = (params, chunkSize) ->
len = 0
for obj in params.objects
len += obj.length
amf0Bytes = Buffer.concat params.objects, len
return createRTMPMessage
chunkStreamID: params.chunkStreamID
timestamp: params.timestamp
messageTypeID: 0x12 # AMF0 Data
messageStreamID: params.messageStreamID
body: amf0Bytes
, chunkSize
createAMF0CommandMessage = (params, chunkSize) ->
commandBuf = createAMF0Data(params.command)
transactionIDBuf = createAMF0Data(params.transactionID)
len = commandBuf.length + transactionIDBuf.length
for obj in params.objects
len += obj.length
amf0Bytes = Buffer.concat [commandBuf, transactionIDBuf, params.objects...], len
return createRTMPMessage
chunkStreamID: params.chunkStreamID
timestamp: params.timestamp
messageTypeID: 0x14 # AMF0 Command
messageStreamID: params.messageStreamID
body: amf0Bytes
, chunkSize
class RTMPSession
constructor: (socket) ->
logger.debug "[rtmp] created a new session"
@listeners = {}
@state = SESSION_STATE_NEW
@socket = socket
@chunkSize = 128
@receiveChunkSize = 128
@previousChunkMessage = {}
@isPlaying = false
@clientid = generateNewClientID()
@useEncryption = false
@receiveTimestamp = null
@windowAckSize = null
@lastSentAckBytes = 0
@receivedBytes = 0
toString: ->
return "#{@clientid}: addr=#{@socket.remoteAddress} port=#{@socket.remotePort}"
parseVideoMessage: (buf) ->
info = flv.parseVideo buf
nalUnitGlob = null
switch info.videoDataTag.avcPacketType
when flv.AVC_PACKET_TYPE_SEQUENCE_HEADER
# Retain AVC configuration
@avcInfo = info.avcDecoderConfigurationRecord
if @avcInfo.numOfSPS > 1
logger.warn "warn: flv:parseVideo(): numOfSPS is #{numOfSPS} > 1 (may not work)"
if @avcInfo.numOfPPS > 1
logger.warn "warn: flv:parseVideo(): numOfPPS is #{numOfPPS} > 1 (may not work)"
sps = h264.concatWithStartCodePrefix @avcInfo.sps
pps = h264.concatWithStartCodePrefix @avcInfo.pps
nalUnitGlob = Buffer.concat [sps, pps]
when flv.AVC_PACKET_TYPE_NALU
if not @avcInfo?
throw new Error "[rtmp:publish] malformed video data: avcInfo is missing"
# TODO: This must be too heavy and needs better alternative.
nalUnits = flv.splitNALUnits info.nalUnits, @avcInfo.nalUnitLengthSize
nalUnitGlob = h264.concatWithStartCodePrefix nalUnits
when flv.AVC_PACKET_TYPE_EOS
logger.info "[rtmp:#{@clientid}] received EOS from uploading client"
# TODO: Do we have to handle EOS?
else
throw new Error "unknown AVCPacketType: #{flv.AVC_PACKET_TYPE_SEQUENCE_HEADER}"
return {
info: info
nalUnitGlob: nalUnitGlob
}
parseAudioMessage: (buf) ->
info = flv.parseAudio buf
adtsFrame = null
stream = avstreams.get @streamId
if not stream?
throw new Error "[rtmp] Unknown stream: #{@streamId}"
switch info.audioDataTag.aacPacketType
when flv.AAC_PACKET_TYPE_SEQUENCE_HEADER
if info.audioSpecificConfig?
stream.updateConfig
audioSpecificConfig: info.audioSpecificConfig
audioASCInfo: info.ascInfo
else
logger.warn "[rtmp] skipping empty AudioSpecificConfig"
when flv.AAC_PACKET_TYPE_RAW
if not stream.audioASCInfo?
throw new Error "[rtmp:publish] malformed audio data: AudioSpecificConfig is missing"
# TODO: This must be a little heavy and needs better alternative.
adtsHeader = new Buffer aac.createADTSHeader stream.audioASCInfo, info.rawDataBlock.length
adtsFrame = Buffer.concat [ adtsHeader, info.rawDataBlock ]
else
throw new Error "[rtmp:publish] unknown AAC_PACKET_TYPE: #{info.audioDataTag.aacPacketType}"
return {
info: info
adtsFrame: adtsFrame
}
clearTimeout: ->
if @timeoutTimer?
clearTimeout @timeoutTimer
@timeoutTimer = null
scheduleTimeout: ->
if @isTearedDown
return
@clearTimeout()
@lastTimeoutScheduledTime = Date.now()
@timeoutTimer = setTimeout =>
if @isTearedDown
return
if not @timeoutTimer?
return
if Date.now() - @lastTimeoutScheduledTime < config.rtmpSessionTimeoutMs
return
logger.info "[rtmp:#{@clientid}] session timeout"
@teardown()
, config.rtmpSessionTimeoutMs
schedulePing: ->
@lastPingScheduledTime = Date.now()
if @pingTimer?
clearTimeout @pingTimer
@pingTimer = setTimeout =>
if Date.now() - @lastPingScheduledTime < config.rtmpPingTimeoutMs
logger.debug "[rtmp] ping timeout canceled"
@ping()
, config.rtmpPingTimeoutMs
ping: ->
currentTimestamp = @getCurrentTimestamp()
pingRequest = createRTMPMessage
chunkStreamID: 2
timestamp: currentTimestamp
messageTypeID: 0x04 # User Control Message
messageStreamID: 0
body: new Buffer [
# Event Type: 6=PingRequest
0, 6,
# Server Timestamp
(currentTimestamp >> 24) & 0xff,
(currentTimestamp >> 16) & 0xff,
(currentTimestamp >> 8) & 0xff,
currentTimestamp & 0xff
]
@sendData pingRequest
stopPlaying: ->
@isPlaying = false
@isWaitingForKeyFrame = false
teardown: ->
if @isTearedDown
logger.debug "[rtmp] already teared down"
return
@isTearedDown = true
@clearTimeout()
@stopPlaying()
if @cipherIn?
@cipherIn.final()
@cipherIn = null
if @cipherOut?
@cipherOut.final()
@cipherOut = null
try
@socket.end()
catch e
logger.error "[rtmp] socket.end error: #{e}"
@emit 'teardown'
getCurrentTimestamp: ->
return Date.now() - @playStartDateTime
getScaledTimestamp: (timestamp) ->
ts = timestamp - @playStartTimestamp
if ts < 0
ts = 0
return ts
createVideoMessage: (params) ->
params.chunkStreamID = 4
params.messageTypeID = 0x09 # Video Data
params.messageStreamID = 1
return @createAVMessage params
createAudioMessage: (params) ->
params.chunkStreamID = 4
params.messageTypeID = 0x08 # Audio Data
params.messageStreamID = 1
return @createAVMessage params
createAVMessage: (params) ->
thisTimestamp = @getScaledTimestamp params.timestamp
if @lastAVTimestamp? and params.body.length <= @chunkSize
# Use Type 1 if chunking is not needed
params.timestampDelta = (thisTimestamp - @lastAVTimestamp) % TIMESTAMP_ROUNDOFF
msg = createRTMPType1Message params
else
# Use Type 0
msg = createRTMPMessage params, @chunkSize
@lastAVTimestamp = thisTimestamp
return msg
concatenate: (arr) ->
if Buffer.isBuffer arr
return arr
if not (arr instanceof Array)
return
len = 0
for item, i in arr
if item?
len += item.length
else
arr[i] = new Buffer 0
return Buffer.concat arr, len
emit: (event, args...) ->
if not @listeners[event]?
return
for listener in @listeners[event]
listener args...
return
on: (event, listener) ->
if not @listeners[event]?
@listeners[event] = [listener]
else
@listeners[event].push listener
return
removeListener: (event, listener) ->
listeners = @listeners[event]
if not listeners?
return
removedCount = 0
for _listener, i in listeners
if _listener is listener
logger.debug "[rtmp] removed listener for #{event}"
actualIndex = i - removedCount
listeners[actualIndex..actualIndex] = [] # Remove element
removedCount++
return
sendData: (arr) ->
if not arr?
return
if Buffer.isBuffer arr
buf = arr
else
len = 0
for item in arr
len += item.length
buf = Buffer.concat arr, len
if @useEncryption
buf = @encrypt buf
@emit 'data', buf
rejectConnect: (commandMessage, callback) ->
streamBegin0 = createRTMPMessage
chunkStreamID: 2
timestamp: 0
messageTypeID: 0x04 # User Control Message
messageStreamID: 0
body: new Buffer [
# Stream Begin (see 7.1.7. User Control Message Events)
0, 0,
# Stream ID of the stream that became functional
0, 0, 0, 0
]
_error = createAMF0CommandMessage
chunkStreamID: 3
timestamp: 0
messageStreamID: 0
command: '_error'
transactionID: 1
objects: [
createAMF0Data(null),
createAMF0Object({
level: 'error'
code: 'NetConnection.Connect.Rejected'
description: 'Connection failed.'
description: '[ Server.Reject ] : (_defaultRoot_, ) : Invalid application name(/_definst_).'
})
]
close = createAMF0CommandMessage
chunkStreamID: 3
timestamp: 0
messageStreamID: 0
command: 'close'
transactionID: 0
objects: [
createAMF0Data(null)
]
callback null, @concatenate [ streamBegin0, _error, close ]
respondConnect: (commandMessage, callback) ->
app = commandMessage.objects[0].value.app
app = app.replace /\/$/, '' # JW Player adds / at the end
if app isnt config.rtmpApplicationName
logger.warn "[rtmp] requested invalid app name: #{app}"
@rejectConnect commandMessage, callback
return
windowAck = createRTMPMessage
chunkStreamID: 2
timestamp: 0
messageTypeID: 0x05 # Window Acknowledgement Size
messageStreamID: 0
# 0x140000 == 1310720
# 0x2625a0 == 2500000
body: new Buffer [
# Acknowledgement Window Size (4 bytes)
# 0, 0x14, 0, 0
0, 0x26, 0x25, 0xa0
]
setPeerBandwidth = createRTMPMessage
chunkStreamID: 2
timestamp: 0
messageTypeID: 0x06 # Set Peer Bandwidth
messageStreamID: 0
body: new Buffer [
# Window acknowledgement size (4 bytes)
0, 0x26, 0x25, 0xa0,
# Limit Type
0x02
]
streamBegin0 = createRTMPMessage
chunkStreamID: 2
timestamp: 0
messageTypeID: 0x04 # User Control Message
messageStreamID: 0
body: new Buffer [
# Stream Begin (see 7.1.7. User Control Message Events)
0, 0,
# Stream ID of the stream that became functional
0, 0, 0, 0
]
# 7.2.1.1. connect
connectResult = createAMF0CommandMessage
chunkStreamID: 3
timestamp: 0
messageStreamID: 0
command: '_result'
transactionID: 1 # Always 1
objects: [
createAMF0Object({
fmsVer: 'FMS/3,0,4,423'
capabilities: 31
}),
createAMF0Object({
level: 'status'
code: 'NetConnection.Connect.Success'
description: 'Connection succeeded.'
objectEncoding: @objectEncoding ? 0
})
]