-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtsp.js
3431 lines (3299 loc) · 108 KB
/
rtsp.js
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
// Generated by CoffeeScript 2.5.1
(function () {
// RTSP/HTTP/RTMPT hybrid server
// RTSP spec:
// RFC 2326 http://www.ietf.org/rfc/rfc2326.txt
// TODO: clear old sessioncookies
var Bits,
CRLF_CRLF,
DAY_NAMES,
DEBUG_DISABLE_UDP_TRANSPORT,
DEBUG_HTTP_TUNNEL,
DEBUG_OUTGOING_PACKET_DATA,
DEBUG_OUTGOING_RTCP,
DEBUG_RTSP,
DEBUG_RTSP_HEADERS_ONLY,
DEFAULT_SERVER_NAME,
ENABLE_START_PLAYING_FROM_KEYFRAME,
MONTH_NAMES,
RTSPClient,
RTSPServer,
SINGLE_NAL_UNIT_MAX_SIZE,
Sequent,
TAG,
TIMESTAMP_ROUNDOFF,
aac,
api,
avstreams,
config,
crypto,
dgram,
enabledFeatures,
generateNewSessionID,
generateRandom32,
h264,
http,
logger,
net,
os,
pad,
resetStreamParams,
rtp,
sdp,
url,
zeropad;
net = require('net');
dgram = require('dgram');
os = require('os');
crypto = require('crypto');
url = require('url');
Sequent = require('sequent');
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');
enabledFeatures = [];
if (config.enableRTSP) {
enabledFeatures.push('rtsp');
}
if (config.enableHTTP) {
enabledFeatures.push('http');
}
if (config.enableRTMPT) {
enabledFeatures.push('rtmpt');
}
TAG = enabledFeatures.join('/');
// 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_HEADERS_ONLY = 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 = function (columns, num) {
num += '';
while (num.length < columns) {
num = '0' + num;
}
return num;
};
pad = function (digits, n) {
n = n + '';
while (n.length < digits) {
n = '0' + n;
}
return n;
};
// Generate new random session ID
// NOTE: Samsung SC-02B doesn't work with some hex string
generateNewSessionID = function (callback) {
var i, id, j;
id = '';
for (i = j = 0; j <= 7; i = ++j) {
id += parseInt(Math.random() * 9) + 1;
}
return callback(null, id);
};
// Generate random 32 bit unsigned integer.
// Return value is intended to be used as an SSRC identifier.
generateRandom32 = function () {
var md5sum, str;
str =
`${new Date().getTime()}${process.pid}${os.hostname()}` +
(1 + Math.random() * 1000000000);
md5sum = crypto.createHash('md5');
md5sum.update(str);
return md5sum.digest().slice(0, 4).readUInt32BE(0);
};
resetStreamParams = function (stream) {
stream.rtspUploadingClient = null;
stream.videoSequenceNumber = 0;
stream.audioSequenceNumber = 0;
stream.lastVideoRTPTimestamp = null;
stream.lastAudioRTPTimestamp = null;
stream.videoRTPTimestampInterval = Math.round(
90000 / stream.videoFrameRate
);
return (stream.audioRTPTimestampInterval = stream.audioPeriodSize);
};
avstreams.on('update_frame_rate', function (stream, frameRate) {
return (stream.videoRTPTimestampInterval = Math.round(90000 / frameRate));
});
avstreams.on('new', function (stream) {
stream.rtspNumClients = 0;
stream.rtspClients = {};
return resetStreamParams(stream);
});
avstreams.on('reset', function (stream) {
return resetStreamParams(stream);
});
RTSPServer = class RTSPServer {
constructor(opts) {
var ref, ref1;
this.httpHandler = opts.httpHandler;
this.rtmpServer = opts.rtmpServer;
this.rtmptCallback = opts.rtmptCallback;
this.numClients = 0;
this.eventListeners = {};
this.serverName =
(ref = opts != null ? opts.serverName : void 0) != null
? ref
: DEFAULT_SERVER_NAME;
this.port =
(ref1 = opts != null ? opts.port : void 0) != null ? ref1 : 8080;
this.clients = {};
this.httpSessions = {};
this.rtspUploadingClients = {};
this.highestClientID = 0;
this.rtpParser = new rtp.RTPParser();
this.rtpParser.on(
'h264_nal_units',
(streamId, nalUnits, rtpTimestamp) => {
var calculatedPTS, sendTime, stream;
stream = avstreams.get(streamId);
if (stream == null) {
// No matching stream
logger.warn(`warn: No matching stream to id ${streamId}`);
return;
}
if (stream.rtspUploadingClient == null) {
// No uploading client associated with the stream
logger.warn(
`warn: No uploading client associated with the stream ${stream.id}`
);
return;
}
sendTime = this.getVideoSendTimeForUploadingRTPTimestamp(
stream,
rtpTimestamp
);
calculatedPTS =
rtpTimestamp - stream.rtspUploadingClient.videoRTPStartTimestamp;
return this.emit(
'video',
stream,
nalUnits,
calculatedPTS,
calculatedPTS
);
}
);
this.rtpParser.on(
'aac_access_units',
(streamId, accessUnits, rtpTimestamp) => {
var calculatedPTS, sendTime, stream;
stream = avstreams.get(streamId);
if (stream == null) {
// No matching stream
logger.warn(`warn: No matching stream to id ${streamId}`);
return;
}
if (stream.rtspUploadingClient == null) {
// No uploading client associated with the stream
logger.warn(
`warn: No uploading client associated with the stream ${stream.id}`
);
return;
}
sendTime = this.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)
return this.emit(
'audio',
stream,
accessUnits,
calculatedPTS,
calculatedPTS
);
}
);
}
setServerName(name) {
return (this.serverName = name);
}
getNextVideoSequenceNumber(stream) {
var num;
num = stream.videoSequenceNumber + 1;
if (num > 65535) {
num -= 65535;
}
return num;
}
getNextAudioSequenceNumber(stream) {
var num;
num = stream.audioSequenceNumber + 1;
if (num > 65535) {
num -= 65535;
}
return num;
}
// TODO: Adjust RTP timestamp based on play start time
getNextVideoRTPTimestamp(stream) {
if (stream.lastVideoRTPTimestamp != null) {
return stream.lastVideoRTPTimestamp + stream.videoRTPTimestampInterval;
} else {
return 0;
}
}
// TODO: Adjust RTP timestamp based on play start time
getNextAudioRTPTimestamp(stream) {
if (stream.lastAudioRTPTimestamp != null) {
return stream.lastAudioRTPTimestamp + stream.audioRTPTimestampInterval;
} else {
return 0;
}
}
getVideoRTPTimestamp(stream, time) {
return Math.round((time * 90) % TIMESTAMP_ROUNDOFF);
}
getAudioRTPTimestamp(stream, time) {
if (stream.audioClockRate == null) {
throw new Error('audioClockRate is null');
}
return Math.round(
(time * (stream.audioClockRate / 1000)) % TIMESTAMP_ROUNDOFF
);
}
getVideoSendTimeForUploadingRTPTimestamp(stream, rtpTimestamp) {
var ref, rtpDiff, timeDiff, videoTimestampInfo;
videoTimestampInfo =
(ref = stream.rtspUploadingClient) != null
? ref.uploadingTimestampInfo.video
: void 0;
if (videoTimestampInfo != null) {
rtpDiff = rtpTimestamp - videoTimestampInfo.rtpTimestamp; // 90 kHz clock
timeDiff = rtpDiff / 90;
return videoTimestampInfo.time + timeDiff;
} else {
return Date.now();
}
}
getAudioSendTimeForUploadingRTPTimestamp(stream, rtpTimestamp) {
var audioTimestampInfo, ref, rtpDiff, timeDiff;
audioTimestampInfo =
(ref = stream.rtspUploadingClient) != null
? ref.uploadingTimestampInfo.audio
: void 0;
if (audioTimestampInfo != null) {
rtpDiff = rtpTimestamp - audioTimestampInfo.rtpTimestamp;
timeDiff = (rtpDiff * 1000) / stream.audioClockRate;
return audioTimestampInfo.time + timeDiff;
} else {
return Date.now();
}
}
// @public
sendVideoData(stream, nalUnits, pts, dts) {
var i, isLastPacket, isPPSSent, isSPSSent, j, len, nalUnit, nalUnitType;
isSPSSent = false;
isPPSSent = false;
for (i = j = 0, len = nalUnits.length; j < len; i = ++j) {
nalUnit = nalUnits[i];
isLastPacket = i === nalUnits.length - 1;
// detect configuration
nalUnitType = h264.getNALUnitType(nalUnit);
if (
config.dropH264AccessUnitDelimiter &&
nalUnitType === h264.NAL_UNIT_TYPE_ACCESS_UNIT_DELIMITER
) {
// ignore access unit delimiters
continue;
}
if (nalUnitType === h264.NAL_UNIT_TYPE_SPS) {
// 7
isSPSSent = true;
} else if (nalUnitType === h264.NAL_UNIT_TYPE_PPS) {
// 8
isPPSSent = true;
}
// 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 === 5) {
// keyframe
// Compensate SPS/PPS if they are not included in nalUnits
if (!isSPSSent) {
// nal_unit_type 7
if (stream.spsNALUnit != null) {
this.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 (!isPPSSent) {
// nal_unit_type 8
if (stream.ppsNALUnit != null) {
this.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');
}
}
}
this.sendNALUnitOverRTSP(stream, nalUnit, pts, dts, isLastPacket);
}
}
sendNALUnitOverRTSP(stream, nalUnit, pts, dts, marker) {
if (nalUnit.length > SINGLE_NAL_UNIT_MAX_SIZE) {
return this.sendVideoPacketWithFragment(stream, nalUnit, pts, marker); // TODO what about dts?
} else {
return this.sendVideoPacketAsSingleNALUnit(
stream,
nalUnit,
pts,
marker
); // TODO what about dts?
}
}
// @public
sendAudioData(stream, accessUnits, pts, dts) {
var accessUnitLength,
audioHeader,
client,
clientID,
concatRawDataBlock,
frameGroups,
group,
i,
j,
len,
processedFrames,
ref,
rtpBuffer,
rtpData,
rtpTimePerFrame,
timestamp,
ts;
if (stream.audioSampleRate == null) {
throw new Error(
`audio sample rate has not been detected for stream ${stream.id}`
);
}
// timestamp: RTP timestamp in audioClockRate
// pts: PTS in 90 kHz clock
if (stream.audioClockRate !== 90000) {
// given pts is not in 90 kHz clock
timestamp = (pts * stream.audioClockRate) / 90000;
} else {
timestamp = pts;
}
rtpTimePerFrame = 1024;
if (this.numClients === 0) {
return;
}
if (stream.rtspNumClients === 0) {
return;
}
// No clients connected to the stream
frameGroups = rtp.groupAudioFrames(accessUnits);
processedFrames = 0;
for (i = j = 0, len = frameGroups.length; j < len; i = ++j) {
group = frameGroups[i];
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);
ref = stream.rtspClients;
for (clientID in ref) {
client = ref[clientID];
// Append the access unit (rawDataBlock)
rtpBuffer = Buffer.concat(
[Buffer.from(rtpData), concatRawDataBlock],
rtp.RTP_HEADER_LEN + audioHeader.length + accessUnitLength
);
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 === 'GET') {
this.sendDataByTCP(
client.socket,
client.audioTCPDataChannel,
rtpBuffer
);
}
} else {
this.sendDataByTCP(
client.socket,
client.audioTCPDataChannel,
rtpBuffer
);
}
} else {
if (client.clientAudioRTPPort != null) {
this.audioRTPSocket.send(
rtpBuffer,
0,
rtpBuffer.length,
client.clientAudioRTPPort,
client.ip,
function (err, bytes) {
if (err) {
return logger.error(
`[audioRTPSend] error: ${err.message}`
);
}
}
);
}
}
}
}
}
}
sendEOS(stream) {
var buf, client, clientID, ref, results;
ref = stream.rtspClients;
results = [];
for (clientID in ref) {
client = ref[clientID];
logger.debug(
`[${TAG}:client=${clientID}] sending goodbye for stream ${stream.id}`
);
buf = Buffer.from(
rtp.createGoodbye({
ssrcs: [client.videoSSRC]
})
);
if (client.useTCPForVideo) {
if (client.useHTTP) {
if (client.httpClientType === 'GET') {
this.sendDataByTCP(
client.socket,
client.videoTCPControlChannel,
buf
);
}
} else {
this.sendDataByTCP(
client.socket,
client.videoTCPControlChannel,
buf
);
}
} else {
if (client.clientVideoRTCPPort != null) {
this.videoRTCPSocket.send(
buf,
0,
buf.length,
client.clientVideoRTCPPort,
client.ip,
function (err, bytes) {
if (err) {
return logger.error(`[videoRTCPSend] error: ${err.message}`);
}
}
);
}
}
buf = Buffer.from(
rtp.createGoodbye({
ssrcs: [client.audioSSRC]
})
);
if (client.useTCPForAudio) {
if (client.useHTTP) {
if (client.httpClientType === 'GET') {
results.push(
this.sendDataByTCP(
client.socket,
client.audioTCPControlChannel,
buf
)
);
} else {
results.push(void 0);
}
} else {
results.push(
this.sendDataByTCP(
client.socket,
client.audioTCPControlChannel,
buf
)
);
}
} else {
if (client.clientAudioRTCPPort != null) {
results.push(
this.audioRTCPSocket.send(
buf,
0,
buf.length,
client.clientAudioRTCPPort,
client.ip,
function (err, bytes) {
if (err) {
return logger.error(
`[audioRTCPSend] error: ${err.message}`
);
}
}
)
);
} else {
results.push(void 0);
}
}
}
return results;
}
dumpClients() {
var client, clientID, ref;
logger.raw(`[rtsp/http: ${Object.keys(this.clients).length} clients]`);
ref = this.clients;
for (clientID in ref) {
client = ref[clientID];
logger.raw(' ' + client.toString());
}
}
setLivePathConsumer(func) {
return (this.livePathConsumer = func);
}
setAuthenticator(func) {
return (this.authenticator = func);
}
start(opts, callback) {
var ref,
serverPort,
udpAudioControlServer,
udpAudioDataServer,
udpVideoControlServer,
udpVideoDataServer;
serverPort =
(ref = opts != null ? opts.port : void 0) != null ? ref : this.port;
this.videoRTPSocket = dgram.createSocket('udp4');
this.videoRTPSocket.bind(config.videoRTPServerPort);
this.videoRTCPSocket = dgram.createSocket('udp4');
this.videoRTCPSocket.bind(config.videoRTCPServerPort);
this.audioRTPSocket = dgram.createSocket('udp4');
this.audioRTPSocket.bind(config.audioRTPServerPort);
this.audioRTCPSocket = dgram.createSocket('udp4');
this.audioRTCPSocket.bind(config.audioRTCPServerPort);
this.server = net.createServer((c) => {
var id_str;
// New client is connected
this.highestClientID++;
id_str = 'c' + this.highestClientID;
logger.info(`[${TAG}:client=${id_str}] connected`);
return generateNewSessionID((err, sessionID) => {
var client;
if (err) {
throw err;
}
client = this.clients[id_str] = new RTSPClient({
id: id_str,
sessionID: sessionID,
socket: c,
ip: c.remoteAddress
});
this.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', () => {
var _client, addr, e, ref1;
logger.info(`[${TAG}:client=${id_str}] disconnected`);
logger.debug(
`[${TAG}:client=${id_str}] teardown: session=${sessionID}`
);
try {
c.end();
} catch (error) {
e = error;
logger.error(`socket.end() error: ${e}`);
}
delete this.clients[id_str];
this.numClients--;
api.leaveClient(client);
this.stopSendingRTCP(client);
ref1 = this.rtspUploadingClients;
// TODO: Is this fast enough?
for (addr in ref1) {
_client = ref1[addr];
if (_client === client) {
delete this.rtspUploadingClients[addr];
}
}
return this.dumpClients();
});
c.buf = null;
c.on('error', function (err) {
logger.error(`Socket error (${c.clientID}): ${err}`);
return c.destroy();
});
return c.on('data', (data) => {
return this.handleOnData(c, data);
});
});
});
this.server.on('error', function (err) {
return logger.error(`[${TAG}] server error: ${err.message}`);
});
udpVideoDataServer = dgram.createSocket('udp4');
udpVideoDataServer.on('error', function (err) {
logger.error(`[${TAG}] udp video data receiver error: ${err.message}`);
throw err;
});
udpVideoDataServer.on('message', (msg, rinfo) => {
var stream;
stream = this.getStreamByRTSPUDPAddress(
rinfo.address,
rinfo.port,
'video-data'
);
if (stream != null) {
return this.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', function () {
var addr;
addr = udpVideoDataServer.address();
return logger.debug(
`[${TAG}] udp video data receiver is listening on port ${addr.port}`
);
});
udpVideoDataServer.bind(config.rtspVideoDataUDPListenPort);
udpVideoControlServer = dgram.createSocket('udp4');
udpVideoControlServer.on('error', function (err) {
logger.error(
`[${TAG}] udp video control receiver error: ${err.message}`
);
throw err;
});
udpVideoControlServer.on('message', (msg, rinfo) => {
var stream;
stream = this.getStreamByRTSPUDPAddress(
rinfo.address,
rinfo.port,
'video-control'
);
if (stream != null) {
return this.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', function () {
var addr;
addr = udpVideoControlServer.address();
return logger.debug(
`[${TAG}] udp video control receiver is listening on port ${addr.port}`
);
});
udpVideoControlServer.bind(config.rtspVideoControlUDPListenPort);
udpAudioDataServer = dgram.createSocket('udp4');
udpAudioDataServer.on('error', function (err) {
logger.error(`[${TAG}] udp audio data receiver error: ${err.message}`);
throw err;
});
udpAudioDataServer.on('message', (msg, rinfo) => {
var stream;
stream = this.getStreamByRTSPUDPAddress(
rinfo.address,
rinfo.port,
'audio-data'
);
if (stream != null) {
return this.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', function () {
var addr;
addr = udpAudioDataServer.address();
return logger.debug(
`[${TAG}] udp audio data receiver is listening on port ${addr.port}`
);
});
udpAudioDataServer.bind(config.rtspAudioDataUDPListenPort);
udpAudioControlServer = dgram.createSocket('udp4');
udpAudioControlServer.on('error', function (err) {
logger.error(
`[${TAG}] udp audio control receiver error: ${err.message}`
);
throw err;
});
udpAudioControlServer.on('message', (msg, rinfo) => {
var stream;
stream = this.getStreamByRTSPUDPAddress(
rinfo.address,
rinfo.port,
'audio-control'
);
if (stream != null) {
return this.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', function () {
var addr;
addr = udpAudioControlServer.address();
return 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}`);
return this.server.listen(serverPort, '0.0.0.0', 511, () => {
logger.info(`[${TAG}] server started on port ${serverPort}`);
return typeof callback === 'function' ? callback() : void 0;
});
}
stop(callback) {
var ref;
return (ref = this.server) != null ? ref.close(callback) : void 0;
}
on(event, listener) {
if (this.eventListeners[event] != null) {
this.eventListeners[event].push(listener);
} else {
this.eventListeners[event] = [listener];
}
}
emit(event, ...args) {
var j, len, listener, ref;
if (this.eventListeners[event] != null) {
ref = this.eventListeners[event];
for (j = 0, len = ref.length; j < len; j++) {
listener = ref[j];
listener(...args);
}
}
}
// rtsp://localhost:80/live/a -> live/a
// This method returns null if no stream id is extracted from the uri
static getStreamIdFromUri(uri, removeDepthFromEnd = 0) {
var e, pathname, slashPos;
try {
pathname = url.parse(uri).pathname;
} catch (error) {
e = error;
return null;
}
if (pathname != null && pathname.length > 0) {
// Remove leading slash
pathname = pathname.slice(1);
// Remove trailing slash
if (pathname[pathname.length - 1] === '/') {
pathname = pathname.slice(0, +(pathname.length - 2) + 1 || 9e9);
}
// Go up directories if removeDepthFromEnd is specified
while (removeDepthFromEnd > 0) {
slashPos = pathname.lastIndexOf('/');
if (slashPos === -1) {
break;
}
pathname = pathname.slice(0, slashPos);
removeDepthFromEnd--;
}
}
return pathname;
}
getStreamByRTSPUDPAddress(addr, port, channelType) {
var client;
client = this.rtspUploadingClients[addr + ':' + port];
if (client != null) {
return client.uploadingStream;
}
return null;
}
getStreamByUri(uri) {
var streamId;
streamId = RTSPServer.getStreamIdFromUri(uri);
if (streamId != null) {
return avstreams.get(streamId);
} else {
return null;
}
}
sendVideoSenderReport(stream, client) {
var buf, rtpTime, time;
if (stream.timeAtVideoStart == null) {
return;
}
time = new Date().getTime();
rtpTime = this.getVideoRTPTimestamp(
stream,
time - stream.timeAtVideoStart
);
if (DEBUG_OUTGOING_RTCP) {
logger.info(
`video sender report: rtpTime=${rtpTime} time=${time} timeAtVideoStart=${stream.timeAtVideoStart}`
);
}
buf = Buffer.from(
rtp.createSenderReport({
time: time,
rtpTime: rtpTime,
ssrc: client.videoSSRC,
packetCount: client.videoPacketCount,
octetCount: client.videoOctetCount
})
);
if (client.useTCPForVideo) {