-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathRTSPClient.js
More file actions
828 lines (828 loc) · 39.1 KB
/
RTSPClient.js
File metadata and controls
828 lines (828 loc) · 39.1 KB
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
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const net = require("net");
const tls = require("tls");
const dgram = require("dgram");
const url_1 = require("url");
const events_1 = require("events");
const util_1 = require("./util");
const transform = require("sdp-transform");
const RTPPacket_1 = require("./transports/RTPPacket");
const RTP_AVP = "RTP/AVP";
const RTP_AVPF = "RTP/AVPF"; // Used by AV1. This is RTP with Feedback (via RTCP) to request Keyframes via RTCP
const STATUS_OK = 200;
const STATUS_UNAUTH = 401;
// The WWW_AUTH is of the format
// TOKEN key=value
// TOKEN key1=value1,key2=value2
// TOKEN key1="value1",key2=value2
// RegEx reminder ? = Zero or One item
// * = Zero or More items
// + = 1 or More items
// \s is whitespace. But we need to 'escape the slash', hence \\s (or put the regex in / / characters)
// ?= is a lookahead
// The RegEx has two 'Groups'
//
// Group 1 (finding the Key)
// Look for one or more characters (a..z or A..Z)
// then look for whitespace
// then look for 'equals'
// then look for whitespace
// then look for an optional Quote character
//
// Group 2 (finding the Value) -
// Look for EITHER 'look backwards for a Quote', some characters, 'lookahead for a Quote'
// OR some characters until (by looking ahead) you can see that another key comes next. The lookahead is 'optinal whitespace' 'comma' 'optional whitespace' 'chars' 'optinal whitespace' 'equals'
// OR some characters followed by 'optinal whitespace'
const WWW_AUTH = "WWW-Authenticate";
const WWW_AUTH_REGEX = new RegExp('([a-zA-Z]+)\\s*=\\s*"?((?<=").*?(?=")|.*?(?=\\s*,?\\s*[a-zA-Z]+\\s*=)|.+[^\\s])', "g");
var ReadStates;
(function (ReadStates) {
ReadStates[ReadStates["SEARCHING"] = 0] = "SEARCHING";
ReadStates[ReadStates["READING_RTSP_HEADER"] = 1] = "READING_RTSP_HEADER";
ReadStates[ReadStates["READING_RTSP_PAYLOAD"] = 2] = "READING_RTSP_PAYLOAD";
ReadStates[ReadStates["READING_RAW_PACKET_SIZE"] = 3] = "READING_RAW_PACKET_SIZE";
ReadStates[ReadStates["READING_RAW_PACKET"] = 4] = "READING_RAW_PACKET";
})(ReadStates || (ReadStates = {}));
class RTSPClient extends events_1.EventEmitter {
constructor(username, password, headers) {
super();
this.isConnected = false;
this.closed = false;
this._cSeq = 0;
this._nextFreeInterleavedChannel = 0;
this._nextFreeUDPPort = 5000;
this.readState = ReadStates.SEARCHING;
// Used as a cache for the data stream.
// What's in here is based on current #readState.
this.messageBytes = [];
// Used for parsing RTSP responses,
// Content-Length header in the RTSP message.
this.rtspContentLength = 0;
this.rtspStatusLine = "";
this.rtspHeaders = {};
// Used for parsing RTP/RTCP responses.
this.rtspPacketLength = 0;
this.rtspPacket = Buffer.from("");
this.rtspPacketPointer = 0;
// Used in #_emptyReceiverReport.
this.clientSSRC = (0, util_1.generateSSRC)();
this.tcpSocket = new net.Socket();
this.setupResult = [];
this.ntpBaseDate_ms = new Date("1900/1/1").getTime();
this.username = username;
this.password = password;
this.headers = Object.assign(Object.assign({}, (headers || {})), { "User-Agent": "yellowstone/3.x" });
}
// This manages the lifecycle for the RTSP connection
// over TCP.
//
// Sets #_client.
//
// Handles receiving data & closing port, called during
// #connect.
_netConnect(hostname, port, secure = false) {
return new Promise((resolve, reject) => {
// Set after listeners defined.
const errorListener = (err) => {
client.removeListener("error", errorListener);
reject(err);
};
const postConnectErrorListener = (err) => {
client.removeListener("error", postConnectErrorListener);
this.emit("error", err);
reject(err);
};
const closeListener = () => {
client.removeListener("close", closeListener);
this.emit("close");
this.close(true);
};
const responseListener = (responseName, headers) => {
const name = responseName.split(" ")[0];
if (name.indexOf("RTSP/") === 0) {
return;
}
if (name === "REDIRECT" || name === "ANNOUNCE") {
this.respond("200 OK", { CSeq: headers.CSeq });
}
if (name === "REDIRECT" && headers.Location) {
this.close();
this.connect(headers.Location);
}
};
// rtsp or rtsps(with tls)
let client;
if (secure == false) {
client = net.connect(port, hostname, () => {
this.isConnected = true;
this._client = client;
client.removeListener("error", errorListener);
client.on("error", postConnectErrorListener);
this.on("response", responseListener);
resolve(this);
});
}
else {
const options = {
rejectUnauthorized: false
};
client = tls.connect(port, hostname, options, () => {
console.log("TLS Connection");
this.isConnected = true;
this._client = client;
client.removeListener("error", errorListener);
this.on("response", responseListener);
resolve(this);
});
}
client.on("data", this._onData.bind(this));
client.on("error", errorListener);
client.on("close", closeListener);
this.tcpSocket = client;
});
}
async connect(url, { keepAlive = true, connection = "udp", secure = false, } = {
keepAlive: true,
connection: "udp",
secure: false
}) {
const { hostname, port } = (0, url_1.parse)((this._url = url));
if (!hostname) {
throw new Error("URL parsing error in connect method.");
}
const details = [];
await this._netConnect(hostname, parseInt(port || "554"), secure);
await this.request("OPTIONS");
const describeRes = await this.request("DESCRIBE", {
Accept: "application/sdp",
});
if (!describeRes || !describeRes.mediaHeaders) {
throw new Error("No media headers on DESCRIBE; RTSP server is broken (sanity check)");
}
// For now, only RTP/AVP and RTP/AVPF are supported. (Some RTSPS servers use RTP/SAVP)
const { media } = transform.parse(describeRes.mediaHeaders.join("\r\n"));
// Loop over the Media Streams in the SDP looking for Video or Audio
// In theory the SDP can contain multiple Video and Audio Streams. We only want one of each type
let hasVideo = false;
let hasAudio = false;
let hasMetaData = false;
let hasBackchannel = false;
for (let x = 0; x < media.length; x++) {
let needSetup = false;
let codec = "";
const mediaSource = media[x];
// RFC says "If none of the direction attributes ("sendonly", "recvonly", "inactive", and "sendrecv") are present,
// the "sendrecv" SHOULD be assumed
if (mediaSource.direction == undefined)
mediaSource.direction = "sendrecv"; // Wowza does not send 'direction'
if (mediaSource.type === "video" &&
mediaSource.protocol === RTP_AVP &&
mediaSource.rtp[0].codec === "H264") {
this.emit("log", "H264 Video Stream Found in SDP", "");
if (hasVideo == false) {
needSetup = true;
hasVideo = true;
codec = "H264";
}
}
if (mediaSource.type === "video" &&
mediaSource.protocol === RTP_AVP &&
mediaSource.rtp[0].codec === "H265") {
this.emit("log", "H265 Video Stream Found in SDP", "");
if (hasVideo == false) {
needSetup = true;
hasVideo = true;
codec = "H265";
}
}
if (mediaSource.type === "video" &&
mediaSource.protocol === RTP_AVP &&
mediaSource.rtp[0].codec === "H266") {
this.emit("log", "H266 Video Stream Found in SDP", "");
if (hasVideo == false) {
needSetup = true;
hasVideo = true;
codec = "H266";
}
}
if (mediaSource.type === "video" &&
(mediaSource.protocol === RTP_AVP || mediaSource.protocol === RTP_AVPF) &&
mediaSource.rtp[0].codec === "AV1") {
this.emit("log", "AV1 Video Stream Found in SDP", "");
if (hasVideo == false) {
needSetup = true;
hasVideo = true;
codec = "AV1";
}
}
if (mediaSource.type === "audio" &&
(mediaSource.direction === "recvonly" || mediaSource.direction === "sendrecv") &&
mediaSource.protocol === RTP_AVP &&
mediaSource.rtp[0].codec.toLowerCase() === "mpeg4-generic" && // (RFC examples are lower case. Axis cameras use upper case)
mediaSource.fmtp[0].config.includes("AAC")) {
this.emit("log", "AAC Audio Stream Found in SDP", "");
if (hasAudio == false) {
needSetup = true;
hasAudio = true;
codec = "AAC";
}
}
if (mediaSource.type === "audio" &&
mediaSource.direction === "sendonly" &&
mediaSource.protocol === RTP_AVP) {
this.emit("log", "Audio backchannel Found in SDP", "");
if (hasBackchannel == false) {
needSetup = true;
hasBackchannel = true;
codec = mediaSource.rtp[0].codec;
}
}
if (mediaSource.type === "application" &&
mediaSource.protocol === RTP_AVP &&
mediaSource.rtp[0].codec.toLowerCase() === "vnd.onvif.metadata") {
this.emit("log", "ONVIF Meta Data Found in SDP", "");
if (hasMetaData == false) {
needSetup = true;
hasMetaData = true;
codec = "vnd.onvif.metadata";
}
}
if (mediaSource.type === "application" &&
mediaSource.protocol === RTP_AVP &&
mediaSource.rtp[0].codec.toUpperCase() === "SMPTE336M" // MediaMTX sends in capitals. Looks like the RFC suggests lower case
) {
this.emit("log", "SMPTE336M KLV Data Stream Found in SDP", "");
if (hasMetaData == false) {
needSetup = true;
hasMetaData = true;
codec = "SMPTE336M";
}
}
if (needSetup) {
let streamurl = "";
// The 'control' in the SDP can be a relative or absolute uri
if (mediaSource.control) {
if (mediaSource.control.toLowerCase().startsWith("rtsp://")) {
// absolute path
streamurl = mediaSource.control;
}
else {
// relative path
streamurl = this._url + "/" + mediaSource.control;
}
}
// Perform a SETUP on the streamurl
// either 'udp' RTP/RTCP packets
// or with 'tcp' RTP/TCP packets which are interleaved into the TCP based RTSP socket
let setupRes;
let rtpChannel;
let rtcpChannel;
let rtpReceiver = null; // UDP mode init value
let rtcpReceiver = null; // UDP mode init value
if (connection === "udp") {
// Create a pair of UDP listeners, even numbered port for RTP
// and odd numbered port for RTCP
rtpChannel = this._nextFreeUDPPort;
rtcpChannel = this._nextFreeUDPPort + 1;
this._nextFreeUDPPort += 2;
const rtpPort = rtpChannel;
rtpReceiver = dgram.createSocket("udp4");
rtpReceiver.on("message", (buf, remote) => {
let packet = (0, util_1.parseRTPPacket)(buf);
// Add wall clock time
const detail = this.setupResult.find(item => item.rtpChannel == rtpChannel);
if (detail != undefined)
packet.wallclockTime = this.GetWallClockTime(packet, detail);
this.emit("data", rtpPort, packet.payload, packet);
});
const rtcpPort = rtcpChannel;
rtcpReceiver = dgram.createSocket("udp4");
rtcpReceiver.on("message", (buf, remote) => {
const packet = (0, util_1.parseRTCPPacket)(buf);
// If this is a Sender Report, cache the NTP Wall Clock data
if (packet.packetType == 200 && packet.senderReport != undefined) {
let detail = this.setupResult.find(item => item.rtcpChannel == rtcpChannel);
if (detail != undefined) {
detail.sr_ntpMSW = packet.senderReport.ntpTimestampMSW;
detail.sr_ntpLSW = packet.senderReport.ntpTimestampLSW;
detail.sr_rtptimestamp = packet.senderReport.rtpTimestamp;
}
}
this.emit("controlData", rtcpPort, packet);
const receiver_report = this._emptyReceiverReport();
this._sendUDPData(remote.address, remote.port, receiver_report);
});
// Block until both UDP sockets are open.
await new Promise((resolve) => {
rtpReceiver === null || rtpReceiver === void 0 ? void 0 : rtpReceiver.bind(rtpPort, () => resolve({}));
});
await new Promise((resolve) => {
rtcpReceiver === null || rtcpReceiver === void 0 ? void 0 : rtcpReceiver.bind(rtcpPort, () => resolve({}));
});
const setupHeader = {
Transport: `RTP/AVP;unicast;client_port=${rtpPort}-${rtcpPort}`,
};
if (this._session)
Object.assign(setupHeader, { Session: this._session });
setupRes = await this.request("SETUP", setupHeader, streamurl);
}
else if (connection === "tcp") {
// channel 0, RTP
// channel 1, RTCP
rtpChannel = this._nextFreeInterleavedChannel;
rtcpChannel = this._nextFreeInterleavedChannel + 1;
this._nextFreeInterleavedChannel += 2;
const setupHeader = {
Transport: `RTP/AVP/TCP;interleaved=${rtpChannel}-${rtcpChannel}`,
};
if (this._session)
Object.assign(setupHeader, { Session: this._session }); // not used on first SETUP
setupRes = await this.request("SETUP", setupHeader, streamurl);
}
else {
throw new Error(`Connection parameter to RTSPClient#connect is ${connection}, not udp or tcp!`);
}
if (!setupRes) {
throw new Error("No SETUP response; RTSP server is broken (sanity check)");
}
const { headers } = setupRes;
if (!headers.Transport) {
throw new Error("No Transport header on SETUP; RTSP server is broken (sanity check)");
}
const transport = (0, util_1.parseTransport)(headers.Transport);
if (
// TCP
transport.protocol !== "RTP/AVP/TCP" &&
// UDP
transport.protocol !== "RTP/AVP" &&
// UDP
transport.protocol !== "RTP/AVP/UDP" // Panasonic cameras send this
) {
throw new Error("Only RTSP servers supporting RTP/AVP or RTP/AVP/UDP or RTP/AVP/TCP are supported at this time.");
}
// Patch from zoolyka (Zoltan Hajdu).
// Try to open a hole in the NAT router (to allow incoming UDP packets)
// by send a UDP packet for RTP and RTCP to the remote RTSP server.
// Note, Roger did not have a router that needed this so the feature is untested.
// May be better to change the RTCP message to a Receiver Report, leaving the RTP message as zero bytes
if (connection === "udp" && transport && rtpReceiver && rtcpReceiver) {
rtpReceiver.send(Buffer.from(''), Number(transport.parameters["server_port"].split("-")[0]), hostname);
rtcpReceiver.send(Buffer.from(''), Number(transport.parameters["server_port"].split("-")[1]), hostname);
}
if (headers.Unsupported) {
this._unsupportedExtensions = headers.Unsupported.split(",");
}
if (headers.Session) {
this._session = headers.Session.split(";")[0];
}
const detail = {
codec,
mediaSource,
transport: transport.parameters,
isH264: codec === "H264",
rtpChannel,
rtcpChannel,
};
details.push(detail);
} // end if (needSetup)
} // end for loop, looping over each media stream
if (keepAlive) {
// Start a Timer to send OPTIONS every 20 seconds to keep stream alive
// using the Session ID
this._keepAliveID = setInterval(() => {
this.request("OPTIONS", { Session: this._session });
// this.request("OPTIONS");
}, 20 * 1000);
}
this.setupResult = details;
return details;
}
request(requestName, headersParam = {}, url) {
if (!this._client) {
return Promise.resolve();
}
if (!url) {
url = this._url;
}
const id = ++this._cSeq;
// mutable via string addition
let req = `${requestName} ${url} RTSP/1.0\r\nCSeq: ${id}\r\n`;
const headers = Object.assign(Object.assign({}, this.headers), headersParam);
if (this._authOpions) {
Object.assign(headers, {
Authorization: this._generateAuthString(requestName, url),
});
}
// NOTE:
// If we cache the Authenitcation Type (Direct or Basic) then we could
// re-compute an Authorization Header here and include in the RTSP Command
// This would make connections a faster with fewer round-trips to the RTSP Server
req += Object.entries(headers)
.map(([key, value]) => `${key}: ${value}\r\n`)
.join("");
this.emit("log", req, "C->S");
// Make sure to add an empty line after the request.
this._client.write(`${req}\r\n`);
return new Promise((resolve, reject) => {
const responseHandler = (responseName, resHeaders, mediaHeaders) => {
const firstAnswer = String(resHeaders[""]) || "";
if (firstAnswer.indexOf("401") >= 0 && 'Authorization' in headers) {
// If the RTSP Command we sent included an Authorization and we have 401 error, then reject()
reject(new Error(`Bad RTSP credentials!`));
return;
}
if (resHeaders.CSeq !== id) {
return;
}
this.removeListener("response", responseHandler);
const statusCode = parseInt(responseName.split(" ")[1]);
if (statusCode === STATUS_OK) {
if (mediaHeaders.length > 0) {
resolve({
headers: resHeaders,
mediaHeaders,
});
}
else {
resolve({
headers: resHeaders,
});
}
}
else {
const authHeader = resHeaders[WWW_AUTH];
// We have status code unauthenticated.
if (statusCode === STATUS_UNAUTH && authHeader) {
this._authOpions = {
type: authHeader.split(" ")[0],
algorithm: "MD5", // Default to MD5 if no algorthm is given. Milestone's RTSP server also supports SHA-256 for FIPS
};
// Get auth properties from WWW_AUTH header.
let match = WWW_AUTH_REGEX.exec(authHeader);
while (match != null) {
const prop = match[1];
if (prop == "realm" && match[2]) {
this._authOpions.realm = match[2];
}
if (prop == "nonce" && match[2]) {
this._authOpions.nonce = match[2];
}
if (prop == "algorithm" && match[2]) {
this._authOpions.algorithm = match[2];
}
match = WWW_AUTH_REGEX.exec(authHeader);
}
// Repeat the request, now _authOptions will be detected and the Authorization header will be generated
resolve(this.request(requestName, headers, url));
return;
}
reject(new Error(`Bad RTSP status code ${statusCode}!`));
return;
}
};
this.on("response", responseHandler);
});
}
respond(status, headersParam = {}) {
if (!this._client) {
return;
}
// mutable via string addition
let res = `RTSP/1.0 ${status}\r\n`;
const headers = Object.assign(Object.assign({}, this.headers), headersParam);
res += Object.entries(headers)
.map(([key, value]) => `${key}: ${value}\r\n`)
.join("");
this.emit("log", res, "C->S");
this._client.write(`${res}\r\n`);
}
async play() {
if (!this.isConnected) {
throw new Error("Client is not connected.");
}
await this.request("PLAY", { Session: this._session });
}
async pause() {
if (!this.isConnected) {
throw new Error("Client is not connected.");
}
await this.request("PAUSE", { Session: this._session });
}
async sendAudioBackChannel(audioChunk) {
let rtp, buf;
const bufSize = 160;
while (audioChunk.length > 0) {
if (audioChunk.length > bufSize) {
buf = audioChunk.slice(0, bufSize);
audioChunk = audioChunk.slice(bufSize, audioChunk.length);
}
else {
buf = audioChunk.slice(0, audioChunk.length);
audioChunk = Buffer.from([]);
}
if (!rtp)
rtp = new RTPPacket_1.default(buf);
else
rtp.payload = buf;
// rtp.type = 8;// set động
rtp.time += buf.length;
rtp.seq++;
const bufferLength = Buffer.alloc(2);
bufferLength.writeUInt16BE(rtp.packet.length, 0);
let channelInterleaved = this.setupResult.filter((value) => {
return value.mediaSource.type === 'audio' && value.mediaSource.direction === 'sendonly';
})[0].transport.interleaved;
/* RTSP Interleaved Frame structure
|dollar sign|channel identifier|data length|
|1 Byte |1 Byte |2 Bytes |
*/
channelInterleaved = channelInterleaved.split('-')[0];
let interleavedHeader = Buffer.from([0x24]); // set '$'
interleavedHeader = Buffer.concat([interleavedHeader, Buffer.from([channelInterleaved])]);
interleavedHeader = Buffer.concat([interleavedHeader, bufferLength]);
const dataToSend = Buffer.concat([interleavedHeader, rtp.packet]);
await this._socketWrite(this.tcpSocket, dataToSend);
}
return;
}
async close(isImmediate = false) {
if (this.closed)
return;
this.closed = true;
if (!this._client) {
return;
}
if (!isImmediate) {
await this.request("TEARDOWN", {
Session: this._session,
});
}
this._client.end();
this.removeAllListeners("response");
if (this._keepAliveID != undefined) {
clearInterval(this._keepAliveID);
this._keepAliveID = undefined;
}
this.isConnected = false;
this._cSeq = 0;
}
_onData(data) {
let index = 0;
// $
const PACKET_START = 0x24;
// R
const RTSP_HEADER_START = 0x52;
// /n
const ENDL = 10;
while (index < data.length) {
// read RTP or RTCP packet
if (this.readState == ReadStates.SEARCHING &&
data[index] == PACKET_START) {
this.messageBytes = [data[index]];
index++;
this.readState = ReadStates.READING_RAW_PACKET_SIZE;
}
else if (this.readState == ReadStates.READING_RAW_PACKET_SIZE) {
// accumulate bytes for $, channel and length
this.messageBytes.push(data[index]);
index++;
if (this.messageBytes.length == 4) {
this.rtspPacketLength =
(this.messageBytes[2] << 8) + this.messageBytes[3];
if (this.rtspPacketLength > 0) {
this.rtspPacket = Buffer.alloc(this.rtspPacketLength);
this.rtspPacketPointer = 0;
this.readState = ReadStates.READING_RAW_PACKET;
}
else {
this.readState = ReadStates.SEARCHING;
}
}
}
else if (this.readState == ReadStates.READING_RAW_PACKET) {
this.rtspPacket[this.rtspPacketPointer++] = data[index];
index++;
if (this.rtspPacketPointer == this.rtspPacketLength) {
const packetChannel = this.messageBytes[1];
if ((packetChannel & 0x01) === 0) {
// even number
let packet = (0, util_1.parseRTPPacket)(this.rtspPacket);
// Get the Session Detail
const detail = this.setupResult.find(item => item.rtpChannel == packetChannel);
if (detail != undefined)
packet.wallclockTime = this.GetWallClockTime(packet, detail);
this.emit("data", packetChannel, packet.payload, packet);
}
if ((packetChannel & 0x01) === 1) {
// odd number
const packet = (0, util_1.parseRTCPPacket)(this.rtspPacket);
// If this is a Sender Report, cache the NTP Wall Clock data
if (packet.packetType == 200 && packet.senderReport != undefined) {
let detail = this.setupResult.find(item => item.rtcpChannel == packetChannel);
if (detail != undefined) {
detail.sr_ntpMSW = packet.senderReport.ntpTimestampMSW;
detail.sr_ntpLSW = packet.senderReport.ntpTimestampLSW;
detail.sr_rtptimestamp = packet.senderReport.rtpTimestamp;
}
}
this.emit("controlData", packetChannel, packet);
const receiver_report = this._emptyReceiverReport();
this._sendInterleavedData(packetChannel, receiver_report);
}
this.readState = ReadStates.SEARCHING;
}
// read response data
}
else if (this.readState == ReadStates.SEARCHING &&
data[index] == RTSP_HEADER_START) {
// found the start of a RTSP rtsp_message
this.messageBytes = [data[index]];
index++;
this.readState = ReadStates.READING_RTSP_HEADER;
}
else if (this.readState == ReadStates.READING_RTSP_HEADER) {
// Reading a RTSP message.
// Add character to the messageBytes
// Ignore /r (13) but keep /n (10)
if (data[index] != 13) {
this.messageBytes.push(data[index]);
}
index++;
// if we have two new lines back to back then we have a complete RTSP command,
// note we may still need to read the Content Payload (the body) e.g. the SDP
if (this.messageBytes.length >= 2 &&
this.messageBytes[this.messageBytes.length - 2] == ENDL &&
this.messageBytes[this.messageBytes.length - 1] == ENDL) {
// Parse the Header
const text = String.fromCharCode.apply(null, this.messageBytes);
const lines = text.split("\n");
this.rtspContentLength = 0;
this.rtspStatusLine = lines[0];
this.rtspHeaders = {};
lines.forEach((line) => {
var _a;
const indexOf = line.indexOf(":");
if (indexOf !== line.length - 1) {
const key = line.substring(0, indexOf).trim();
const data = line.substring(indexOf + 1).trim();
if (key == "Session")
this.rtspHeaders[key] = data;
else if (key == "WWW-Authenticate") {
// Handle multiple WWW-Authenticate entries and pick the 'best'
// We prefer 'Digest' over 'Basic'
// We preger 'Digest SHAxxx' over 'Digest MD5' or 'Digest with no algorithm (defaults to MD5) (STILL TODO)
if (key in this.rtspHeaders) {
console.log("Duplicate WWW-Authenticate keys");
if (data.startsWith("Digest") && ((_a = this.rtspHeaders[key]) === null || _a === void 0 ? void 0 : _a.startsWith("Basic"))) {
this.rtspHeaders[key] = data; // Replace Basic with Digest
}
console.log("Keeping WWW-Authenticate: " + this.rtspHeaders[key]);
}
else {
this.rtspHeaders[key] = data;
}
}
else {
// Store the result as either a String type or a Number type
this.rtspHeaders[key] =
data.match(/^[0-9]+$/)
? parseInt(data, 10)
: data;
}
// workaround for buggy Hipcam RealServer/V1.0 camera which returns Content-length and not Content-Length
if (key.toLowerCase() == "content-length") {
this.rtspContentLength = parseInt(data, 10);
}
}
});
// if no content length, there there's no media headers
// emit the message
if (!this.rtspContentLength) {
this.emit("log", text, "S->C");
this.emit("response", this.rtspStatusLine, this.rtspHeaders, []);
this.readState = ReadStates.SEARCHING;
}
else {
this.messageBytes = [];
this.readState = ReadStates.READING_RTSP_PAYLOAD;
}
}
}
else if (this.readState == ReadStates.READING_RTSP_PAYLOAD &&
this.messageBytes.length < this.rtspContentLength) {
// Copy data into the RTSP payload
this.messageBytes.push(data[index]);
index++;
if (this.messageBytes.length == this.rtspContentLength) {
const text = String.fromCharCode.apply(null, this.messageBytes);
const mediaHeaders = text.split("\n");
// Emit the RTSP message
this.emit("log", String.fromCharCode.apply(null, this.messageBytes) + text, "S->C");
this.emit("response", this.rtspStatusLine, this.rtspHeaders, mediaHeaders);
this.readState = ReadStates.SEARCHING;
}
}
else {
// unexpected data
throw new Error("Bug in RTSP data framing, please file an issue with the author with stacktrace.");
}
} // end while
}
_sendInterleavedData(channel, buffer) {
if (!this._client) {
return;
}
const req = `${buffer.length} bytes of interleaved data on channel ${channel}`;
this.emit("log", req, "C->S");
const header = Buffer.alloc(4);
header[0] = 0x24; // ascii $
header[1] = channel;
header[2] = (buffer.length >> 8) & 0xff;
header[3] = (buffer.length >> 0) & 0xff;
const data = Buffer.concat([header, buffer]);
this._client.write(data);
}
_sendUDPData(host, port, buffer) {
const udp = dgram.createSocket("udp4");
udp.send(buffer, 0, buffer.length, port, host, (err, bytes) => {
// TODO: Don't ignore errors.
udp.close();
});
}
_emptyReceiverReport() {
const report = Buffer.alloc(8);
const version = 2;
const paddingBit = 0;
const reportCount = 0; // an empty report
const packetType = 201; // Receiver Report
const length = report.length / 4 - 1; // num 32 bit words minus 1
report[0] = (version << 6) + (paddingBit << 5) + reportCount;
report[1] = packetType;
report[2] = (length >> 8) & 0xff;
report[3] = (length >> 0) & 0xff;
report[4] = (this.clientSSRC >> 24) & 0xff;
report[5] = (this.clientSSRC >> 16) & 0xff;
report[6] = (this.clientSSRC >> 8) & 0xff;
report[7] = (this.clientSSRC >> 0) & 0xff;
return report;
}
async _socketWrite(socket, data) {
return new Promise((resolve, reject) => {
setTimeout(() => {
socket.write(data, (error) => {
if (error) {
reject(error);
}
else {
resolve(undefined);
}
});
}, 20);
});
}
_generateAuthString(requestName, url) {
if (!url) {
url = this._url;
}
let authString = "";
if (!this._authOpions)
return "";
if (this._authOpions.type === "Digest") {
// Digest Authentication
// Select Hash Function, default to MD5
const HashFunction = (this._authOpions.algorithm == "SHA-256" ? util_1.getSHA256Hash : util_1.getMD5Hash);
const ha1 = HashFunction(`${this.username}:${this._authOpions.realm}:${this.password}`);
const ha2 = HashFunction(`${requestName}:${url}`);
const ha3 = HashFunction(`${ha1}:${this._authOpions.nonce}:${ha2}`);
// Some RTSP servers to not accept "algorithm=NNN" in the authString and reject the authentication. So only add algorithm=ZZZZ when not using MD5
if (this._authOpions.algorithm == "MD5")
authString = `Digest username="${this.username}",realm="${this._authOpions.realm}",nonce="${this._authOpions.nonce}",uri="${url}",response="${ha3}"`;
else
authString = `Digest username="${this.username}",realm="${this._authOpions.realm}",nonce="${this._authOpions.nonce}",algorithm=${this._authOpions.algorithm},uri="${url}",response="${ha3}"`;
}
else if (this._authOpions.type === "Basic") {
// Basic Authentication
// https://xkcd.com/538/
const b64 = Buffer.from(`${this.username}:${this.password}`).toString("base64");
authString = `Basic ${b64}`;
}
return authString;
}
// Note we have had a RTP Packet in Yellowstone for many years, but the Audio Backchennal code added another object also called RTPPacket
GetWallClockTime(packet, detail) {
// Add Wall Clock Time
if (detail.sr_ntpMSW != undefined && detail.sr_ntpLSW != undefined && detail.sr_rtptimestamp != undefined && detail.mediaSource.rtp[0].rate != undefined) {
let refTimestampSecs = detail.sr_rtptimestamp / detail.mediaSource.rtp[0].rate; // H264 is 90 kHz clock rate
let packetTimestampSecs = packet.timestamp / detail.mediaSource.rtp[0].rate; // eg 90kHz
let packetTimestampDeltaSecs = packetTimestampSecs - refTimestampSecs;
let refTimestamp = new Date(this.ntpBaseDate_ms + (detail.sr_ntpMSW * 1000) + ((detail.sr_ntpLSW / Math.pow(2, 32)) * 1000));
let wallclockTime = new Date(refTimestamp.getTime() + (packetTimestampDeltaSecs * 1000));
return wallclockTime;
}
// Could not generate a Wall Clock Time
return undefined;
}
}
exports.default = RTSPClient;
//# sourceMappingURL=RTSPClient.js.map