forked from iizukanao/node-rtsp-rtmp-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtsp.coffee
1953 lines (1696 loc) · 68.7 KB
/
rtsp.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
# RTSP/HTTP/RTMPT hybrid server
#
# RTSP spec:
# RFC 2326 http://www.ietf.org/rfc/rfc2326.txt
# TODO: clear old sessioncookies
net = require 'net'
dgram = require 'dgram'
os = require 'os'
crypto = require 'crypto'
url = require 'url'
rtp = require './rtp'
sdp = require './sdp'
h264 = require './h264'
aac = require './aac'
http = require './http'
avstreams = require './avstreams'
Bits = require './bits'
logger = require './logger'
config = require './config'
TAG = 'rtsp/http'
# Default server name for RTSP and HTTP responses
DEFAULT_SERVER_NAME = 'node-rtsp-rtmp-server'
# Start playing from keyframe
ENABLE_START_PLAYING_FROM_KEYFRAME = false
# Maximum single NAL unit size
SINGLE_NAL_UNIT_MAX_SIZE = 1358
DAY_NAMES = [
'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'
]
MONTH_NAMES = [
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec',
]
# If true, RTSP requests/response will be printed to the console
DEBUG_RTSP = false
DEBUG_RTSP_ONLY_HEADERS = false
# If true, outgoing video/audio packets are printed to the console
DEBUG_OUTGOING_PACKET_DATA = false
# If true, outgoing RTCP packets (sender reports) are printed to the console
DEBUG_OUTGOING_RTCP = false
# If true, RTSP requests/responses tunneled in HTTP will be
# printed to the console
DEBUG_HTTP_TUNNEL = false
# If true, UDP transport will always be disabled and
# clients will be forced to use TCP transport.
DEBUG_DISABLE_UDP_TRANSPORT = false
# Two CRLFs
CRLF_CRLF = [ 0x0d, 0x0a, 0x0d, 0x0a ]
TIMESTAMP_ROUNDOFF = 4294967296 # 32 bits
if DEBUG_OUTGOING_PACKET_DATA
logger.enableTag 'rtsp:out'
zeropad = (columns, num) ->
num += ''
while num.length < columns
num = '0' + num
num
pad = (digits, n) ->
n = n + ''
while n.length < digits
n = '0' + n
n
# Generate new random session ID
# NOTE: Samsung SC-02B doesn't work with some hex string
generateNewSessionID = (callback) ->
id = ''
for i in [0..7]
id += parseInt(Math.random() * 9) + 1
callback null, id
# Generate random 32 bit unsigned integer.
# Return value is intended to be used as an SSRC identifier.
generateRandom32 = ->
str = "#{new Date().getTime()}#{process.pid}#{os.hostname()}" + \
"#{process.getuid()}#{process.getgid()}" + \
(1 + Math.random() * 1000000000)
md5sum = crypto.createHash 'md5'
md5sum.update str
md5sum.digest()[0..3].readUInt32BE(0)
resetStreamParams = (stream) ->
stream.rtspUploadingClient = null
stream.videoSequenceNumber = 0
stream.audioSequenceNumber = 0
stream.lastVideoRTPTimestamp = null
stream.lastAudioRTPTimestamp = null
stream.videoRTPTimestampInterval = Math.round(90000 / stream.videoFrameRate)
stream.audioRTPTimestampInterval = stream.audioPeriodSize
avstreams.on 'update_frame_rate', (stream, frameRate) ->
stream.videoRTPTimestampInterval = Math.round(90000 / frameRate)
avstreams.on 'new', (stream) ->
stream.rtspNumClients = 0
stream.rtspClients = {}
resetStreamParams stream
avstreams.on 'reset', (stream) ->
resetStreamParams stream
class RTSPServer
constructor: (opts) ->
@httpHandler = opts.httpHandler
@rtmpServer = opts.rtmpServer
@numClients = 0
@eventListeners = {}
@serverName = opts?.serverName ? DEFAULT_SERVER_NAME
@port = opts?.port ? 8080
@clients = {}
@httpSessions = {}
@rtspUploadingClients = {}
@highestClientID = 0
@rtpParser = new rtp.RTPParser
@rtpParser.on 'h264_nal_units', (streamId, nalUnits, rtpTimestamp) =>
stream = avstreams.get streamId
if not stream? # No matching stream
logger.warn "warn: No matching stream to id #{streamId}"
return
if not stream.rtspUploadingClient?
# No uploading client associated with the stream
logger.warn "warn: No uploading client associated with the stream #{stream.id}"
return
sendTime = @getVideoSendTimeForUploadingRTPTimestamp stream, rtpTimestamp
calculatedPTS = rtpTimestamp - stream.rtspUploadingClient.videoRTPStartTimestamp
@emit 'video', stream, nalUnits, calculatedPTS, calculatedPTS
@rtpParser.on 'aac_access_units', (streamId, accessUnits, rtpTimestamp) =>
stream = avstreams.get streamId
if not stream? # No matching stream
logger.warn "warn: No matching stream to id #{streamId}"
return
if not stream.rtspUploadingClient?
# No uploading client associated with the stream
logger.warn "warn: No uploading client associated with the stream #{stream.id}"
return
sendTime = @getAudioSendTimeForUploadingRTPTimestamp stream, rtpTimestamp
calculatedPTS = Math.round (rtpTimestamp - stream.rtspUploadingClient.audioRTPStartTimestamp) * 90000 / stream.audioClockRate
# PTS may not be monotonically increased (it may not be in decoding order)
@emit 'audio', stream, accessUnits, calculatedPTS, calculatedPTS
setServerName: (name) ->
@serverName = name
getNextVideoSequenceNumber: (stream) ->
num = stream.videoSequenceNumber + 1
if num > 65535
num -= 65535
num
getNextAudioSequenceNumber: (stream) ->
num = stream.audioSequenceNumber + 1
if num > 65535
num -= 65535
num
# TODO: Adjust RTP timestamp based on play start time
getNextVideoRTPTimestamp: (stream) ->
if stream.lastVideoRTPTimestamp?
return stream.lastVideoRTPTimestamp + stream.videoRTPTimestampInterval
else
return 0
# TODO: Adjust RTP timestamp based on play start time
getNextAudioRTPTimestamp: (stream) ->
if stream.lastAudioRTPTimestamp?
return stream.lastAudioRTPTimestamp + stream.audioRTPTimestampInterval
else
return 0
getVideoRTPTimestamp: (stream, time) ->
return Math.round time * 90 % TIMESTAMP_ROUNDOFF
getAudioRTPTimestamp: (stream, time) ->
if not stream.audioClockRate?
throw new Error "audioClockRate is null"
return Math.round time * (stream.audioClockRate / 1000) % TIMESTAMP_ROUNDOFF
getVideoSendTimeForUploadingRTPTimestamp: (stream, rtpTimestamp) ->
videoTimestampInfo = stream.rtspUploadingClient?.uploadingTimestampInfo.video
if videoTimestampInfo?
rtpDiff = rtpTimestamp - videoTimestampInfo.rtpTimestamp # 90 kHz clock
timeDiff = rtpDiff / 90
return videoTimestampInfo.time + timeDiff
else
return Date.now()
getAudioSendTimeForUploadingRTPTimestamp: (stream, rtpTimestamp) ->
audioTimestampInfo = stream.rtspUploadingClient?.uploadingTimestampInfo.audio
if audioTimestampInfo?
rtpDiff = rtpTimestamp - audioTimestampInfo.rtpTimestamp
timeDiff = rtpDiff * 1000 / stream.audioClockRate
return audioTimestampInfo.time + timeDiff
else
return Date.now()
# @public
sendVideoData: (stream, nalUnits, pts, dts) ->
isSPSSent = false
isPPSSent = false
for nalUnit, i in nalUnits
isLastPacket = i is nalUnits.length - 1
# detect configuration
nalUnitType = h264.getNALUnitType nalUnit
if config.dropH264AccessUnitDelimiter and
(nalUnitType is h264.NAL_UNIT_TYPE_ACCESS_UNIT_DELIMITER)
# ignore access unit delimiters
continue
if nalUnitType is h264.NAL_UNIT_TYPE_SPS # 7
isSPSSent = true
stream.updateSPS nalUnit
else if nalUnitType is h264.NAL_UNIT_TYPE_PPS # 8
isPPSSent = true
stream.updatePPS nalUnit
# If this is keyframe but SPS and PPS do not exist in the
# same timestamp, we insert them before the keyframe.
# TODO: Send SPS and PPS as an aggregation packet (STAP-A).
if nalUnitType is 5 # keyframe
# Compensate SPS/PPS if they are not included in nalUnits
if not isSPSSent # nal_unit_type 7
if stream.spsNALUnit?
@sendNALUnitOverRTSP stream, stream.spsNALUnit, pts, dts, false
# there is a case where timestamps of two keyframes are identical
# (i.e. nalUnits argument contains multiple keyframes)
isSPSSent = true
else
logger.error "Error: SPS is not set"
if not isPPSSent # nal_unit_type 8
if stream.ppsNALUnit?
@sendNALUnitOverRTSP stream, stream.ppsNALUnit, pts, dts, false
# there is a case where timestamps of two keyframes are identical
# (i.e. nalUnits argument contains multiple keyframes)
isPPSSent = true
else
logger.error "Error: PPS is not set"
@sendNALUnitOverRTSP stream, nalUnit, pts, dts, isLastPacket
return
sendNALUnitOverRTSP: (stream, nalUnit, pts, dts, marker) ->
if nalUnit.length >= SINGLE_NAL_UNIT_MAX_SIZE
@sendVideoPacketWithFragment stream, nalUnit, pts, marker # TODO what about dts?
else
@sendVideoPacketAsSingleNALUnit stream, nalUnit, pts, marker # TODO what about dts?
# @public
sendAudioData: (stream, accessUnits, pts, dts) ->
if not stream.audioSampleRate?
throw new Error "audio sample rate isn't detected"
# timestamp: RTP timestamp in audioClockRate
# pts: PTS in 90 kHz clock
if stream.audioClockRate isnt 90000 # given pts is not in 90 kHz clock
timestamp = pts * stream.audioClockRate / 90000
else
timestamp = pts
rtpTimePerFrame = 1024
if @numClients is 0
return
if stream.rtspNumClients is 0
# No clients connected to the stream
return
frameGroups = rtp.groupAudioFrames accessUnits
processedFrames = 0
for group, i in frameGroups
concatRawDataBlock = Buffer.concat group
if ++stream.audioSequenceNumber > 65535
stream.audioSequenceNumber -= 65535
ts = Math.round((timestamp + rtpTimePerFrame * processedFrames) % TIMESTAMP_ROUNDOFF)
processedFrames += group.length
stream.lastAudioRTPTimestamp = (timestamp + rtpTimePerFrame * processedFrames) % TIMESTAMP_ROUNDOFF
# TODO dts
rtpData = rtp.createRTPHeader
marker: true
payloadType: 96
sequenceNumber: stream.audioSequenceNumber
timestamp: ts
ssrc: null
accessUnitLength = concatRawDataBlock.length
# TODO: maximum size of AAC-hbr is 8191 octets
# TODO: sequence number should start at a random number
audioHeader = rtp.createAudioHeader
accessUnits: group
rtpData = rtpData.concat audioHeader
# Append the access unit (rawDataBlock)
rtpBuffer = Buffer.concat [new Buffer(rtpData), concatRawDataBlock],
rtp.RTP_HEADER_LEN + audioHeader.length + accessUnitLength
for clientID, client of stream.rtspClients
if client.isPlaying
rtp.replaceSSRCInRTP rtpBuffer, client.audioSSRC
client.audioPacketCount++
client.audioOctetCount += accessUnitLength
logger.tag 'rtsp:out', "[rtsp:stream:#{stream.id}] send audio to #{client.id}: ts=#{ts} pts=#{pts}"
if client.useTCPForAudio
if client.useHTTP
if client.httpClientType is 'GET'
@sendDataByTCP client.socket, client.audioTCPDataChannel, rtpBuffer
else
@sendDataByTCP client.socket, client.audioTCPDataChannel, rtpBuffer
else
if client.clientAudioRTPPort?
@audioRTPSocket.send rtpBuffer, 0, rtpBuffer.length, client.clientAudioRTPPort, client.ip, (err, bytes) ->
if err
logger.error "[audioRTPSend] error: #{err.message}"
return
dumpClients: ->
logger.raw "[rtsp/http: #{Object.keys(@clients).length} clients]"
for clientID, client of @clients
logger.raw " " + client.toString()
return
setLivePathConsumer: (func) ->
@livePathConsumer = func
start: (opts, callback) ->
serverPort = opts?.port ? @port
@videoRTPSocket = dgram.createSocket 'udp4'
@videoRTPSocket.bind config.videoRTPServerPort
@videoRTCPSocket = dgram.createSocket 'udp4'
@videoRTCPSocket.bind config.videoRTCPServerPort
@audioRTPSocket = dgram.createSocket 'udp4'
@audioRTPSocket.bind config.audioRTPServerPort
@audioRTCPSocket = dgram.createSocket 'udp4'
@audioRTCPSocket.bind config.audioRTCPServerPort
@server = net.createServer (c) =>
# New client is connected
@highestClientID++
id_str = 'c' + @highestClientID
logger.info "[#{TAG}] client #{id_str} connected"
generateNewSessionID (err, sessionID) =>
throw err if err
client = @clients[id_str] = new RTSPClient
id: id_str
sessionID: sessionID
socket: c
ip: c.remoteAddress
@numClients++
c.setKeepAlive true, 120000
c.clientID = id_str # TODO: Is this safe?
c.isAuthenticated = false
c.requestCount = 0
c.responseCount = 0
c.on 'close', =>
logger.info "[#{TAG}] client #{id_str} is closed"
logger.debug "[client:#{@id}] teardown: session=#{@sessionID}"
try
c.end()
catch e
logger.error "socket.end() error: #{e}"
delete @clients[id_str]
@numClients--
api.leaveClient client
@stopSendingRTCP client
# TODO: Is this fast enough?
for addr, _client of @rtspUploadingClients
if _client is client
delete @rtspUploadingClients[addr]
@dumpClients()
c.buf = null
c.on 'error', (err) ->
logger.error "Socket error (#{c.clientID}): #{err}"
c.destroy()
c.on 'data', (data) =>
@handleOnData c, data
@server.on 'error', (err) ->
logger.error "[#{TAG}] server error: #{err.message}"
udpVideoDataServer = dgram.createSocket 'udp4'
udpVideoDataServer.on 'error', (err) ->
logger.error "[#{TAG}] udp video data receiver error: #{err.message}"
throw err
udpVideoDataServer.on 'message', (msg, rinfo) =>
stream = @getStreamByRTSPUDPAddress rinfo.address, rinfo.port, 'video-data'
if stream?
@onUploadVideoData stream, msg, rinfo
# else
# logger.warn "[#{TAG}] warn: received UDP video data but no existing client found: #{rinfo.address}:#{rinfo.port}"
udpVideoDataServer.on 'listening', ->
addr = udpVideoDataServer.address()
logger.debug "[#{TAG}] udp video data receiver is listening on port #{addr.port}"
udpVideoDataServer.bind config.rtspVideoDataUDPListenPort
udpVideoControlServer = dgram.createSocket 'udp4'
udpVideoControlServer.on 'error', (err) ->
logger.error "[#{TAG}] udp video control receiver error: #{err.message}"
throw err
udpVideoControlServer.on 'message', (msg, rinfo) =>
stream = @getStreamByRTSPUDPAddress rinfo.address, rinfo.port, 'video-control'
if stream?
@onUploadVideoControl stream, msg, rinfo
# else
# logger.warn "[#{TAG}] warn: received UDP video control data but no existing client found: #{rinfo.address}:#{rinfo.port}"
udpVideoControlServer.on 'listening', ->
addr = udpVideoControlServer.address()
logger.debug "[#{TAG}] udp video control receiver is listening on port #{addr.port}"
udpVideoControlServer.bind config.rtspVideoControlUDPListenPort
udpAudioDataServer = dgram.createSocket 'udp4'
udpAudioDataServer.on 'error', (err) ->
logger.error "[#{TAG}] udp audio data receiver error: #{err.message}"
throw err
udpAudioDataServer.on 'message', (msg, rinfo) =>
stream = @getStreamByRTSPUDPAddress rinfo.address, rinfo.port, 'audio-data'
if stream?
@onUploadAudioData stream, msg, rinfo
# else
# logger.warn "[#{TAG}] warn: received UDP audio data but no existing client found: #{rinfo.address}:#{rinfo.port}"
udpAudioDataServer.on 'listening', ->
addr = udpAudioDataServer.address()
logger.debug "[#{TAG}] udp audio data receiver is listening on port #{addr.port}"
udpAudioDataServer.bind config.rtspAudioDataUDPListenPort
udpAudioControlServer = dgram.createSocket 'udp4'
udpAudioControlServer.on 'error', (err) ->
logger.error "[#{TAG}] udp audio control receiver error: #{err.message}"
throw err
udpAudioControlServer.on 'message', (msg, rinfo) =>
stream = @getStreamByRTSPUDPAddress rinfo.address, rinfo.port, 'audio-control'
if stream?
@onUploadAudioControl stream, msg, rinfo
# else
# logger.warn "[#{TAG}] warn: received UDP audio control data but no existing client found: #{rinfo.address}:#{rinfo.port}"
udpAudioControlServer.on 'listening', ->
addr = udpAudioControlServer.address()
logger.debug "[#{TAG}] udp audio control receiver is listening on port #{addr.port}"
udpAudioControlServer.bind config.rtspAudioControlUDPListenPort
logger.debug "[#{TAG}] starting server on port #{serverPort}"
@server.listen serverPort, '0.0.0.0', 511, =>
logger.info "[#{TAG}] server started on port #{serverPort}"
callback?()
stop: (callback) ->
@server?.close callback
on: (event, listener) ->
if @eventListeners[event]?
@eventListeners[event].push listener
else
@eventListeners[event] = [ listener ]
return
emit: (event, args...) ->
if @eventListeners[event]?
for listener in @eventListeners[event]
listener args...
return
@getStreamIdFromUri: (uri) ->
try
pathname = url.parse(uri).pathname
catch e
return null
if pathname.indexOf('/live/') is 0 # starts with /live/
pathname = pathname[6..]
slashPos = pathname.indexOf '/'
if slashPos isnt -1 # remove / and after
pathname = pathname[0...slashPos]
return pathname
getStreamByRTSPUDPAddress: (addr, port, channelType) ->
client = @rtspUploadingClients[addr + ':' + port]
if client?
return client.uploadingStream
return null
getStreamByUri: (uri) ->
streamId = RTSPServer.getStreamIdFromUri uri
if streamId?
return avstreams.get streamId
else
return null
sendVideoSenderReport: (stream, client) ->
if not stream.timeAtVideoStart?
return
time = new Date().getTime()
rtpTime = @getVideoRTPTimestamp stream, time - stream.timeAtVideoStart
if DEBUG_OUTGOING_RTCP
logger.info "video sender report: rtpTime=#{rtpTime} time=#{time} timeAtVideoStart=#{stream.timeAtVideoStart}"
buf = new Buffer rtp.createSenderReport
time: time
rtpTime: rtpTime
ssrc: client.videoSSRC
packetCount: client.videoPacketCount
octetCount: client.videoOctetCount
if client.useTCPForVideo
if client.useHTTP
if client.httpClientType is 'GET'
@sendDataByTCP client.socket, client.videoTCPControlChannel, buf
else
@sendDataByTCP client.socket, client.videoTCPControlChannel, buf
else
if client.clientVideoRTCPPort?
@videoRTCPSocket.send buf, 0, buf.length, client.clientVideoRTCPPort, client.ip, (err, bytes) ->
if err
logger.error "[videoRTCPSend] error: #{err.message}"
sendAudioSenderReport: (stream, client) ->
if not stream.timeAtAudioStart?
return
time = new Date().getTime()
rtpTime = @getAudioRTPTimestamp stream, time - stream.timeAtAudioStart
if DEBUG_OUTGOING_RTCP
logger.info "audio sender report: rtpTime=#{rtpTime} time=#{time} timeAtAudioStart=#{stream.timeAtAudioStart}"
buf = new Buffer rtp.createSenderReport
time: time
rtpTime: rtpTime
ssrc: client.audioSSRC
packetCount: client.audioPacketCount
octetCount: client.audioOctetCount
if client.useTCPForAudio
if client.useHTTP
if client.httpClientType is 'GET'
@sendDataByTCP client.socket, client.audioTCPControlChannel, buf
else
@sendDataByTCP client.socket, client.audioTCPControlChannel, buf
else
if client.clientAudioRTCPPort?
@audioRTCPSocket.send buf, 0, buf.length, client.clientAudioRTCPPort, client.ip, (err, bytes) ->
if err
logger.error "[audioRTCPSend] error: #{err.message}"
stopSendingRTCP: (client) ->
if client.timeoutID?
clearTimeout client.timeoutID
client.timeoutID = null
# Send RTCP sender report packets for audio and video streams
sendSenderReports: (stream, client) ->
if not @clients[client.id]? # client socket is already closed
@stopSendingRTCP client
return
if stream.isAudioStarted
@sendAudioSenderReport stream, client
if stream.isVideoStarted
@sendVideoSenderReport stream, client
client.timeoutID = setTimeout =>
@sendSenderReports stream, client
, config.rtcpSenderReportIntervalMs
startSendingRTCP: (stream, client) ->
@stopSendingRTCP client
@sendSenderReports stream, client
onReceiveVideoRTCP: (buf) ->
# TODO: handle BYE message
onReceiveAudioRTCP: (buf) ->
# TODO: handle BYE message
sendDataByTCP: (socket, channel, rtpBuffer) ->
rtpLen = rtpBuffer.length
tcpHeader = api.createInterleavedHeader
channel: channel
payloadLength: rtpLen
socket.write Buffer.concat [tcpHeader, rtpBuffer],
api.INTERLEAVED_HEADER_LEN + rtpBuffer.length
# Process incoming RTSP data that is tunneled in HTTP POST
handlePOSTData: (client, data='', callback) ->
# Concatenate outstanding base64 string
if client.postBase64Buf?
base64Buf = client.postBase64Buf + data
else
base64Buf = data
if base64Buf.length > 0
# Length of base64-encoded string is always divisible by 4
div = base64Buf.length % 4
if div isnt 0
# extract last div characters
client.postBase64Buf = base64Buf[-div..]
base64Buf = base64Buf[0...-div]
else
client.postBase64Buf = null
# Decode base64-encoded data
decodedBuf = new Buffer(base64Buf, 'base64')
else # no base64 input
decodedBuf = new Buffer []
# Concatenate outstanding buffer
if client.postBuf?
postData = Buffer.concat [client.postBuf, decodedBuf]
client.postBuf = null
else
postData = decodedBuf
if postData.length is 0 # no data to process
callback? null
return
# Will be called before return
processRemainingBuffer = =>
if client.postBase64Buf? or client.postBuf?
@handlePOSTData client, '', callback
else
callback? null
return
# TODO: Do we have to interpret interleaved data here?
if postData[0] is api.INTERLEAVED_SIGN # interleaved data
interleavedData = api.getInterleavedData postData
if not interleavedData?
# not enough buffer for an interleaved data
client.postBuf = postData
callback? null
return
# At this point, postData has enough buffer for this interleaved data.
@onInterleavedRTPPacketFromClient client, interleavedData
if postData.length > interleavedData.totalLength
client.postBuf = client.buf[interleavedData.totalLength..]
processRemainingBuffer()
else
delimiterPos = Bits.searchBytesInArray postData, CRLF_CRLF
if delimiterPos is -1 # not found (not enough buffer)
client.postBuf = postData
callback? null
return
decodedRequest = postData[0...delimiterPos].toString 'utf8'
remainingPostData = postData[delimiterPos+CRLF_CRLF.length..]
req = http.parseRequest decodedRequest
if not req? # parse error
logger.error "Unable to parse request: #{decodedRequest}"
callback? new Error "malformed request"
return
if req.headers['content-length']?
req.contentLength = parseInt req.headers['content-length']
if remainingPostData.length < req.contentLength
# not enough buffer for the body
client.postBuf = postData
callback? null
return
if remainingPostData.length > req.contentLength
req.rawbody = remainingPostData[0...req.contentLength]
client.postBuf = remainingPostData[req.contentLength..]
else # remainingPostData.length == req.contentLength
req.rawbody = remainingPostData
else if remainingPostData.length > 0
client.postBuf = remainingPostData
if DEBUG_HTTP_TUNNEL
logger.info "===request (HTTP tunneled/decoded)==="
process.stdout.write decodedRequest
logger.info "============="
@respond client.socket, req, (err, output) ->
if err
logger.error "[respond] Error: #{err}"
callback? err
return
if DEBUG_HTTP_TUNNEL
logger.info "===response (HTTP tunneled)==="
process.stdout.write output
logger.info "============="
client.getClient.socket.write output
processRemainingBuffer()
# cancelTimeout: (socket) ->
# if socket.timeoutTimer?
# clearTimeout socket.timeoutTimer
#
# scheduleTimeout: (socket) ->
# @cancelTimeout socket
# socket.scheduledTimeoutTime = Date.now() + config.keepaliveTimeoutMs
# socket.timeoutTimer = setTimeout =>
# if not clients[socket.clientID]?
# return
# if Date.now() < socket.scheduledTimeoutTime
# return
# logger.info "keepalive timeout: #{socket.clientID}"
# @teardownClient socket.clientID
# , config.keepaliveTimeoutMs
# Called when the server received an interleaved RTP packet
onInterleavedRTPPacketFromClient: (client, interleavedData) ->
if client.uploadingStream?
stream = client.uploadingStream
# TODO: Support multiple streams
senderInfo =
address: null
port: null
switch interleavedData.channel
when stream.rtspUploadingClient.uploadingChannels.videoData
@onUploadVideoData stream, interleavedData.data, senderInfo
when stream.rtspUploadingClient.uploadingChannels.videoControl
@onUploadVideoControl stream, interleavedData.data, senderInfo
when stream.rtspUploadingClient.uploadingChannels.audioData
@onUploadAudioData stream, interleavedData.data, senderInfo
when stream.rtspUploadingClient.uploadingChannels.audioControl
@onUploadAudioControl stream, interleavedData.data, senderInfo
else
logger.error "Error: unknown interleaved channel: #{interleavedData.channel}"
# Discard incoming RTP packets if the client is not uploading streams
# Called when new data comes from TCP connection
handleOnData: (c, data) ->
id_str = c.clientID
if not @clients[id_str]? # client socket is already closed
logger.error "error: invalid client ID: #{id_str}"
return
client = @clients[id_str]
if client.isSendingPOST
@handlePOSTData client, data.toString 'utf8'
return
if c.buf?
c.buf = Buffer.concat [c.buf, data], c.buf.length + data.length
else
c.buf = data
if c.buf[0] is api.INTERLEAVED_SIGN # dollar sign '$' (RFC 2326 - 10.12)
interleavedData = api.getInterleavedData c.buf
if not interleavedData?
# not enough buffer for an interleaved data
return
# At this point, c.buf has enough buffer for this interleaved data.
if c.buf.length > interleavedData.totalLength
c.buf = c.buf[interleavedData.totalLength..]
else
c.buf = null
@onInterleavedRTPPacketFromClient client, interleavedData
if c.buf?
# Process the remaining buffer
# TODO: Is there more efficient way to do this?
buf = c.buf
c.buf = null
@handleOnData c, buf
return
if c.ongoingRequest?
req = c.ongoingRequest
req.rawbody = Buffer.concat [req.rawbody, data], req.rawbody.length + data.length
if req.rawbody.length < req.contentLength
return
req.socket = c
if req.rawbody.length > req.contentLength
c.buf = req.rawbody[req.contentLength..]
req.rawbody = req.rawbody[0...req.contentLength]
else
c.buf = null
req.body = req.rawbody.toString 'utf8'
if DEBUG_RTSP
logger.info "===RTSP/HTTP request (cont) from #{id_str}==="
if DEBUG_RTSP_ONLY_HEADERS
logger.info "(redacted)"
else
process.stdout.write data.toString 'utf8'
logger.info "=================="
else
bufString = c.buf.toString 'utf8'
if bufString.indexOf('\r\n\r\n') is -1
return
if DEBUG_RTSP
logger.info "===RTSP/HTTP request from #{id_str}==="
if DEBUG_RTSP_ONLY_HEADERS
process.stdout.write bufString.replace(/\r\n\r\n[\s\S]*/, '\n')
else
process.stdout.write bufString
logger.info "=================="
req = http.parseRequest bufString
if not req?
logger.error "Unable to parse request: #{bufString}"
c.buf = null
return
req.rawbody = c.buf[req.headerBytes+4..]
req.socket = c
if req.headers['content-length']?
if req.headers['content-type'] is 'application/x-rtsp-tunnelled'
# If HTTP tunneling is used, we have to ignore content-length.
req.contentLength = 0
else
req.contentLength = parseInt req.headers['content-length']
if req.rawbody.length < req.contentLength
c.ongoingRequest = req
return
if req.rawbody.length > req.contentLength
c.buf = req.rawbody[req.contentLength..]
req.rawbody = req.rawbody[0...req.contentLength]
else
c.buf = null
else
if req.rawbody.length > 0
c.buf = req.rawbody
else
c.buf = null
c.ongoingRequest = null
@respond c, req, (err, output, resultOpts) =>
if err
logger.error "[respond] Error: #{err}"
return
# Write the response
if DEBUG_RTSP
logger.info "===RTSP/HTTP response to #{id_str}==="
if output instanceof Array
for out, i in output
if DEBUG_RTSP
logger.info out
c.write out
else
if DEBUG_RTSP
if DEBUG_RTSP_ONLY_HEADERS
delimPos = Bits.searchBytesInArray output, [ 0x0d, 0x0a, 0x0d, 0x0a ]
if delimPos isnt -1
headerBytes = output[0..delimPos+1]
else
headerBytes = output
process.stdout.write headerBytes
else
process.stdout.write output
c.write output
if DEBUG_RTSP
logger.info "==================="
if resultOpts?.close
# Half-close the socket
c.end()
if c.buf?
# Process the remaining buffer
buf = c.buf
c.buf = null
@handleOnData c, buf
sendVideoPacketWithFragment: (stream, nalUnit, timestamp, marker=true) ->
ts = timestamp % TIMESTAMP_ROUNDOFF
stream.lastVideoRTPTimestamp = ts
if @numClients is 0
return
if stream.rtspNumClients is 0
# No clients connected to the stream
return
nalUnitType = nalUnit[0] & 0x1f
isKeyFrame = nalUnitType is 5
nal_ref_idc = nalUnit[0] & 0b01100000 # skip ">> 5" operation
nalUnit = nalUnit.slice 1
fragmentNumber = 0
while nalUnit.length > SINGLE_NAL_UNIT_MAX_SIZE
if ++stream.videoSequenceNumber > 65535
stream.videoSequenceNumber -= 65535
fragmentNumber++
thisNalUnit = nalUnit.slice 0, SINGLE_NAL_UNIT_MAX_SIZE
nalUnit = nalUnit.slice SINGLE_NAL_UNIT_MAX_SIZE
# TODO: sequence number should start at a random number
rtpData = rtp.createRTPHeader
marker: false
payloadType: 97
sequenceNumber: stream.videoSequenceNumber
timestamp: ts
ssrc: null
rtpData = rtpData.concat rtp.createFragmentationUnitHeader
nal_ref_idc: nal_ref_idc
nal_unit_type: nalUnitType
isStart: fragmentNumber is 1
isEnd: false
# Append NAL unit
thisNalUnitLen = thisNalUnit.length
rtpBuffer = Buffer.concat [new Buffer(rtpData), thisNalUnit],
rtp.RTP_HEADER_LEN + 2 + thisNalUnitLen
for clientID, client of stream.rtspClients
if client.isWaitingForKeyFrame and isKeyFrame
process.stdout.write "KeyFrame"
client.isPlaying = true
client.isWaitingForKeyFrame = false
if client.isPlaying
rtp.replaceSSRCInRTP rtpBuffer, client.videoSSRC
logger.tag 'rtsp:out', "[rtsp:stream:#{stream.id}] send video to #{client.id}: fragment n=#{fragmentNumber} timestamp=#{ts} bytes=#{rtpBuffer.length} marker=false" + (if isKeyFrame then " isKeyFrame=#{isKeyFrame}" else "")
client.videoPacketCount++
client.videoOctetCount += thisNalUnitLen
if client.useTCPForVideo
if client.useHTTP
if client.httpClientType is 'GET'
@sendDataByTCP client.socket, client.videoTCPDataChannel, rtpBuffer
else
@sendDataByTCP client.socket, client.videoTCPDataChannel, rtpBuffer
else
if client.clientVideoRTPPort?
@videoRTPSocket.send rtpBuffer, 0, rtpBuffer.length, client.clientVideoRTPPort, client.ip, (err, bytes) ->
if err
logger.error "[videoRTPSend] error: #{err.message}"
# last packet
if ++stream.videoSequenceNumber > 65535
stream.videoSequenceNumber -= 65535
# TODO: sequence number should be started from a random number
rtpData = rtp.createRTPHeader
marker: marker
payloadType: 97
sequenceNumber: stream.videoSequenceNumber
timestamp: ts
ssrc: null
rtpData = rtpData.concat rtp.createFragmentationUnitHeader
nal_ref_idc: nal_ref_idc
nal_unit_type: nalUnitType
isStart: false
isEnd: true
nalUnitLen = nalUnit.length
rtpBuffer = Buffer.concat [new Buffer(rtpData), nalUnit],
rtp.RTP_HEADER_LEN + 2 + nalUnitLen
for clientID, client of stream.rtspClients
if client.isWaitingForKeyFrame and isKeyFrame
process.stdout.write "KeyFrame"
client.isPlaying = true
client.isWaitingForKeyFrame = false
if client.isPlaying
rtp.replaceSSRCInRTP rtpBuffer, client.videoSSRC
client.videoPacketCount++
client.videoOctetCount += nalUnitLen
logger.tag 'rtsp:out', "[rtsp:stream:#{stream.id}] send video to #{client.id}: fragment-last n=#{fragmentNumber+1} timestamp=#{ts} bytes=#{rtpBuffer.length} marker=#{marker}" + (if isKeyFrame then " isKeyFrame=#{isKeyFrame}" else "")
if client.useTCPForVideo
if client.useHTTP
if client.httpClientType is 'GET'
@sendDataByTCP client.socket, client.videoTCPDataChannel, rtpBuffer
else
@sendDataByTCP client.socket, client.videoTCPDataChannel, rtpBuffer
else
if client.clientVideoRTPPort?
@videoRTPSocket.send rtpBuffer, 0, rtpBuffer.length, client.clientVideoRTPPort, client.ip, (err, bytes) ->
if err
logger.error "[videoRTPSend] error: #{err.message}"