forked from iizukanao/node-rtsp-rtmp-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
rtmp.js
3715 lines (3404 loc) · 117 KB
/
rtmp.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
// 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
import net from 'net';
import url from 'url';
import crypto from 'crypto';
import Sequent from 'sequent';
import rtmp_handshake from './rtmp_handshake';
import codec_utils from './codec_utils';
import config from './config';
import h264 from './h264';
import aac from './aac';
import flv from './flv';
import avstreams from './avstreams';
import logger from './logger';
import Bits from './bits';
// enum
let SESSION_STATE_NEW = 1;
let SESSION_STATE_HANDSHAKE_ONGOING = 2;
let SESSION_STATE_HANDSHAKE_DONE = 3;
let AVC_PACKET_TYPE_SEQUENCE_HEADER = 0;
let AVC_PACKET_TYPE_NALU = 1;
let AVC_PACKET_TYPE_END_OF_SEQUENCE = 2;
let TIMESTAMP_ROUNDOFF = 4294967296; // 32 bits
let DEBUG_INCOMING_STREAM_DATA = false;
let DEBUG_INCOMING_RTMP_PACKETS = false;
let DEBUG_OUTGOING_RTMP_PACKETS = false;
let RTMPT_SEND_REQUEST_BUFFER_SIZE = 10;
// Number of active sessions
let sessionsCount = 0;
// Active sessions
let sessions = {};
// Number of active RTMPT sessions
let rtmptSessionsCount = 0;
// Active RTMPT sessions
let rtmptSessions = {};
// The newest client ID
let clientMaxId = 0;
let queuedRTMPMessages = {};
// Generate a new client ID without collision
let generateNewClientID = function() {
let clientID = generateClientID();
while (sessions[clientID] != null) {
clientID = generateClientID();
}
return clientID;
};
// Generate a new random client ID (like Cookie)
var generateClientID = function() {
let possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
let numPossible = possible.length;
let clientID = '';
for (let i = 0; i <= 7; i++) {
clientID += possible.charAt((Math.random() * numPossible) | 0);
}
return clientID;
};
let parseAcknowledgementMessage = function(buf) {
let sequenceNumber = (buf[0] * Math.pow(256, 3)) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
return {
sequenceNumber
};
};
let convertPTSToMilliseconds = pts => Math.floor(pts / 90);
let createAudioMessage = function(params) {
// TODO: Use type 1/2/3
let audioMessage;
return audioMessage = createRTMPMessage({
chunkStreamID: 4,
timestamp: params.timestamp,
messageTypeID: 0x08, // Audio Data
messageStreamID: 1,
body: params.body
}
, params.chunkSize);
};
let clearQueuedRTMPMessages = function(stream) {
if (queuedRTMPMessages[stream.id] != null) {
return queuedRTMPMessages[stream.id] = [];
}
};
let queueRTMPMessages = function(stream, messages, params) {
for (let message of Array.from(messages)) {
message.originalTimestamp = message.timestamp;
}
if (queuedRTMPMessages[stream.id] != null) {
queuedRTMPMessages[stream.id].push(...messages);
} else {
queuedRTMPMessages[stream.id] = [ ...messages ]; // Prevent copying array as reference
}
return flushRTMPMessages(stream, params);
};
let queueVideoMessage = function(stream, params) {
params.avType = 'video';
params.chunkStreamID = 4;
params.messageTypeID = 0x09; // Video Data
params.messageStreamID = 1;
params.originalTimestamp = params.timestamp;
if (queuedRTMPMessages[stream.id] != null) {
queuedRTMPMessages[stream.id].push(params);
} else {
queuedRTMPMessages[stream.id] = [ params ];
}
return setImmediate(() => flushRTMPMessages(stream));
};
let queueAudioMessage = function(stream, params) {
params.avType = 'audio';
params.chunkStreamID = 4;
params.messageTypeID = 0x08; // Audio Data
params.messageStreamID = 1;
params.originalTimestamp = params.timestamp;
if (queuedRTMPMessages[stream.id] != null) {
queuedRTMPMessages[stream.id].push(params);
} else {
queuedRTMPMessages[stream.id] = [ params ];
}
return setImmediate(() => flushRTMPMessages(stream));
};
let createVideoMessage = function(params) {
// TODO: Use type 1/2/3
let videoMessage;
return videoMessage = createRTMPMessage({
chunkStreamID: 4,
timestamp: params.timestamp,
messageTypeID: 0x09, // Video Data
messageStreamID: 1,
body: params.body
}
, params.chunkSize);
};
let parseUserControlMessage = function(buf) {
let eventType = (buf[0] << 8) + buf[1];
let eventData = buf.slice(2);
let message = {
eventType,
eventData
};
if (eventType === 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;
};
let parseIEEE754Double = function(buf) {
let sign = buf[0] >> 7; // 1 == negative
let exponent = ((buf[0] & 0b1111111) << 4) + (buf[1] >> 4);
exponent -= 1023; // because 1023 means zero
let fraction = 1;
for (let i = 0; i <= 51; i++) {
let byteIndex = 1 + parseInt((i + 4) / 8);
let bitIndex = 7 - ((i + 4) % 8);
let bitValue = (buf[byteIndex] >> bitIndex) & 0b1;
if (bitValue > 0) {
fraction += Math.pow(2, -(i+1));
}
}
let value = fraction * Math.pow(2, exponent);
if (sign === 1) {
value = -value;
}
return value;
};
let parseAMF0StrictArray = function(buf) {
let arr = [];
let len = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
let readLen = 4;
while (--len >= 0) {
let result = parseAMF0Data(buf.slice(readLen));
arr.push(result.value);
readLen += result.readLen;
}
return { value: arr, readLen };
};
let parseAMF0ECMAArray = function(buf) {
// associative-count
let count = (buf[0] << 24) + (buf[1] << 16) + (buf[2] << 8) + buf[3];
let result = parseAMF0Object(buf.slice(4), count);
result.readLen += 4;
return result;
};
var parseAMF0Object = function(buf, maxItems) {
if (maxItems == null) { maxItems = null; }
let obj = {};
let bufLen = buf.length;
let readLen = 0;
let items = 0;
if (((maxItems == null)) || (maxItems > 0)) {
while (readLen < bufLen) {
var name;
let nameLen = (buf[readLen++] << 8) + buf[readLen++];
if (nameLen > 0) { // object-end-marker will follow
name = buf.toString('utf8', readLen, readLen + nameLen);
readLen += nameLen;
} else {
name = null;
}
let result = parseAMF0Data(buf.slice(readLen));
readLen += result.readLen;
if (result.type === 'object-end-marker') {
break;
} else {
items++;
if ((maxItems != null) && (items > maxItems)) {
logger.warn(`warn: illegal AMF0 data: force break because items (${items}) > maxItems (${maxItems})`);
break;
}
}
if (name != null) {
obj[name] = result.value;
} else {
logger.warn(`warn: illegal AMF0 data: object key for value ${result.value} is zero length`);
}
}
}
return { value: obj, readLen };
};
// Do opposite of parseAMF0DataMessage()
let serializeAMF0DataMessage = function(parsedObject) {
let bufs = [];
for (let object of Array.from(parsedObject.objects)) {
bufs.push(createAMF0Data(object.value));
}
return Buffer.concat(bufs);
};
// Decode AMF0 data message buffer into AMF0 packets
let parseAMF0DataMessage = function(buf) {
let amf0Packets = [];
let remainingLen = buf.length;
while (remainingLen > 0) {
let result = parseAMF0Data(buf);
amf0Packets.push(result);
remainingLen -= result.readLen;
buf = buf.slice(result.readLen);
}
return {
objects: amf0Packets
};
};
// Decode buffer into AMF0 packets
let parseAMF0CommandMessage = function(buf) {
let amf0Packets = [];
let remainingLen = buf.length;
while (remainingLen > 0) {
var result;
try {
result = parseAMF0Data(buf);
} catch (e) {
logger.error("[rtmp] error parsing AMF0 command (maybe a bug); buf:");
logger.error(buf);
throw e;
}
amf0Packets.push(result);
remainingLen -= result.readLen;
buf = buf.slice(result.readLen);
}
return {
command: amf0Packets[0].value,
transactionID: amf0Packets[1].value,
objects: amf0Packets.slice(2)
};
};
var parseAMF0Data = function(buf) {
let result, value;
let i = 0;
let type = buf[i++];
if (type === 0x00) { // number-marker
value = buf.readDoubleBE(i);
return { type: 'number', value, readLen: i + 8 };
} else if (type === 0x01) { // boolean-marker
value = buf[i] === 0x00 ? false : true;
return { type: 'boolean', value, readLen: i + 1 };
} else if (type === 0x02) { // string-marker
let strLen = (buf[i++] << 8) + buf[i++];
value = buf.toString('utf8', i, i+strLen);
return { type: 'string', value, readLen: i + strLen };
} else if (type === 0x03) { // object-marker
result = parseAMF0Object(buf.slice(i));
return { type: 'object', value: result.value, readLen: i + result.readLen };
} else if (type === 0x05) { // null-marker
return { type: 'null', value: null, readLen: i };
} else if (type === 0x06) { // undefined-marker
return { type: 'undefined', value: undefined, readLen: i };
} else if (type === 0x08) { // ecma-array-marker
result = parseAMF0ECMAArray(buf.slice(i));
return { type: 'array', value: result.value, readLen: i + result.readLen };
} else if (type === 0x09) { // object-end-marker
return { type: 'object-end-marker', readLen: i };
} else if (type === 0x0a) { // strict-array-marker
result = parseAMF0StrictArray(buf.slice(i));
return { type: 'strict-array', value: result.value, readLen: i + result.readLen };
} else if (type === 0x0b) { // date-marker
let time = buf.readDoubleBE(i);
let date = new Date(time);
return { type: 'date', value: date, readLen: i + 10 }; // 8 (time) + 2 (time-zone)
} else {
throw new Error(`Unknown AMF0 data type: ${type}`);
}
};
var createAMF0Data = function(data) {
let type = typeof data;
let buf = null;
if (type === 'number') {
buf = new Buffer(9);
buf[0] = 0x00; // number-marker
buf.writeDoubleBE(data, 1);
} else if (type === 'boolean') {
buf = new Buffer(2);
buf[0] = 0x01; // boolean-marker
buf[1] = data ? 0x01 : 0x00;
} else if (type === 'string') {
buf = new Buffer(3);
buf[0] = 0x02; // string-marker
let strBytes = new Buffer(data, 'utf8');
let strLen = strBytes.length;
buf[1] = (strLen >> 8) & 0xff;
buf[2] = strLen & 0xff;
buf = Buffer.concat([buf, strBytes], 3 + strLen);
} else if (data === null) {
buf = new Buffer([ 0x05 ]); // null-marker
} else if (type === '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 === 'object') {
buf = createAMF0Object(data);
} else {
throw new Error(`Unknown data type \"${type}\" for data ${data}`);
}
return buf;
};
var createAMF0StrictArray = function(arr, buf) {
if (buf == null) { buf = null; }
let bufs = [];
let totalLength = 0;
if (buf != null) {
bufs.push(buf);
totalLength += buf.length;
}
// array-count (U32)
let arrLen = arr.length;
bufs.push(new Buffer([
(arrLen >>> 24) & 0xff,
(arrLen >>> 16) & 0xff,
(arrLen >>> 8) & 0xff,
arrLen & 0xff
]));
totalLength += 4;
for (let i = 0; i < arr.length; i++) {
let value = arr[i];
let valueBytes = createAMF0Data(value);
bufs.push(valueBytes);
totalLength += valueBytes.length;
}
return Buffer.concat(bufs, totalLength);
};
var createAMF0Object = function(obj) {
let buf = new Buffer([ 0x03 ]); // object-marker
return createAMF0PropertyList(obj, buf);
};
let createAMF0ECMAArray = function(obj) {
let count = Object.keys(obj).length;
let buf = new Buffer([
// ecma-array-marker
0x08,
// array-count
(count >>> 24) & 0xff,
(count >>> 16) & 0xff,
(count >>> 8) & 0xff,
count & 0xff
]);
return createAMF0PropertyList(obj, buf);
};
var createAMF0PropertyList = function(obj, buf) {
if (buf == null) { buf = null; }
let bufs = [];
let totalLength = 0;
if (buf != null) {
bufs.push(buf);
totalLength += buf.length;
}
for (let name in obj) {
let value = obj[name];
let nameBytes = new Buffer(name, 'utf8');
let nameLen = nameBytes.length;
let nameLenBytes = new Buffer(2);
nameLenBytes[0] = (nameLen >> 8) & 0xff;
nameLenBytes[1] = nameLen & 0xff;
let 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);
};
let counter = 0;
var flushRTMPMessages = function(stream, params) {
let i, rtmpMessage, session;
if ((stream == null)) {
logger.error("[rtmp] error: flushRTMPMessages: Invalid stream");
return;
}
if (((params != null ? params.forceFlush : undefined) !== true) &&
(queuedRTMPMessages[stream.id].length < config.rtmpMessageQueueSize)) {
// not enough buffer
return;
}
let rtmpMessagesToSend = queuedRTMPMessages[stream.id];
queuedRTMPMessages[stream.id] = [];
for (i = 0; i < rtmpMessagesToSend.length; i++) {
rtmpMessage = rtmpMessagesToSend[i];
rtmpMessage.index = i;
}
// Move audio before video if the PTS are the same
rtmpMessagesToSend.sort(function(a, b) {
let cmp = a.originalTimestamp - b.originalTimestamp;
if (cmp === 0) {
if (((a.avType == null)) || ((b.avType == null))) {
cmp = 0;
} else if (a.avType === b.avType) {
cmp = 0;
} else if (a.avType === 'audio') { // a=audio b=video
cmp = -1;
} else if (b.avType === 'audio') { // a=video b=audio
cmp = 1;
}
}
if (cmp === 0) {
cmp = a.index - b.index; // keep the original order
}
return cmp;
});
if (rtmpMessagesToSend.length === 0) {
// nothing to send
return;
}
let allSessions = [];
for (var clientID in rtmptSessions) {
session = rtmptSessions[clientID];
allSessions.push(session.rtmpSession);
}
for (clientID in sessions) {
session = sessions[clientID];
allSessions.push(session);
}
for (session of Array.from(allSessions)) {
if ((session.stream != null ? session.stream.id : undefined) !== stream.id) { // The session is not associated with current stream
continue;
}
let 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 (i = 0; i < rtmpMessagesToSend.length; i++) {
rtmpMessage = rtmpMessagesToSend[i];
if ((rtmpMessage.avType === 'video') && rtmpMessage.isKeyFrame) {
logger.info(`[rtmp:client=${session.clientid}] started playing stream ${stream.id}`);
session.startPlaying();
session.playStartTimestamp = rtmpMessage.originalTimestamp;
session.playStartDateTime = Date.now(); // TODO: Should we use slower process.hrtime()?
session.isWaitingForKeyFrame = false;
msgs = rtmpMessagesToSend.slice(i);
break;
}
}
} else { // audio only
logger.info(`[rtmp:client=${session.clientid}] started playing stream ${stream.id}`);
session.startPlaying();
session.playStartTimestamp = rtmpMessagesToSend[0].originalTimestamp;
session.playStartDateTime = Date.now();
session.isWaitingForKeyFrame = false;
msgs = rtmpMessagesToSend;
}
} else { // Do not wait for a keyframe
logger.info(`[rtmp:client=${session.clientid}] started playing stream ${stream.id}`);
session.startPlaying();
session.playStartTimestamp = rtmpMessagesToSend[0].originalTimestamp;
session.playStartDateTime = Date.now();
session.isWaitingForKeyFrame = false;
msgs = rtmpMessagesToSend;
}
} else {
msgs = rtmpMessagesToSend;
}
if ((msgs == null)) {
continue;
}
if (session.isPlaying) {
var buf, filteredMsgs;
for (rtmpMessage of Array.from(msgs)) {
// get milliseconds elapsed since play start
rtmpMessage.timestamp = session.getScaledTimestamp(rtmpMessage.originalTimestamp) % TIMESTAMP_ROUNDOFF;
}
if (session.isResuming) {
// Remove audio messages which are already sent until
// the first video message comes
filteredMsgs = [];
for (i = 0; i < msgs.length; i++) {
rtmpMessage = msgs[i];
if ((rtmpMessage.avType == null)) {
filteredMsgs.push(rtmpMessage);
} else if (rtmpMessage.avType === 'video') {
filteredMsgs.push(...msgs.slice(i));
session.isResuming = false;
break;
} else if (rtmpMessage.timestamp > session.lastSentTimestamp) {
filteredMsgs.push(rtmpMessage);
} else {
logger.debug(`[rtmp:client=${session.clientid}] skipped message (timestamp=${rtmpMessage.timestamp} <= lastSentTimestamp=${session.lastSentTimestamp})`);
}
}
} else {
filteredMsgs = msgs;
}
if (((params != null ? params.hasControlMessage : undefined) !== true) && (filteredMsgs.length > 1)) {
buf = createRTMPAggregateMessage(filteredMsgs, session.chunkSize);
if (DEBUG_OUTGOING_RTMP_PACKETS) {
logger.info(`send RTMP agg msg: ${buf.length} bytes; time=` + filteredMsgs.map(item => `${(item.avType != null ? item.avType[0] : undefined) != null ? (item.avType != null ? item.avType[0] : undefined) : 'other'}${(item.avType === 'video') && item.isKeyFrame ? '(key)' : ''}:${item.timestamp}${(item.avType === 'video') && (item.compositionTime !== 0) ? `(cmp=${item.timestamp+item.compositionTime})` : ''}`).join(','));
}
session.sendData(buf);
} else {
let bufs = [];
for (rtmpMessage of Array.from(filteredMsgs)) {
bufs.push(createRTMPMessage(rtmpMessage, session.chunkSize));
}
buf = Buffer.concat(bufs);
if (DEBUG_OUTGOING_RTMP_PACKETS) {
logger.info(`send RTMP msg: ${buf.length} bytes; time=` + filteredMsgs.map(item => `${(item.avType != null ? item.avType[0] : undefined) != null ? (item.avType != null ? item.avType[0] : undefined) : 'other'}:${item.timestamp}`).join(','));
}
session.sendData(buf);
}
session.lastSentTimestamp = filteredMsgs[filteredMsgs.length-1].timestamp;
}
}
};
// RTMP Message Header used in Aggregate Message
let createMessageHeader = function(params) {
let payloadLength = params.body.length;
if ((params.messageTypeID == null)) {
logger.warn("[rtmp] warning: createMessageHeader(): messageTypeID is not set");
}
if ((params.timestamp == null)) {
logger.warn("[rtmp] warning: createMessageHeader(): timestamp is not set");
}
if ((params.messageStreamID == null)) {
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
var createRTMPAggregateMessage = function(rtmpMessages, chunkSize) {
let bufs = [];
let totalLength = 0;
let aggregateTimestamp = null;
for (let rtmpMessage of Array.from(rtmpMessages)) {
if ((aggregateTimestamp == null)) {
aggregateTimestamp = rtmpMessage.timestamp;
}
let header = createMessageHeader(rtmpMessage);
let 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;
}
let aggregateBody = Buffer.concat(bufs, totalLength);
return createRTMPMessage({
chunkStreamID: 4,
timestamp: aggregateTimestamp,
messageTypeID: 22, // Aggregate Message
messageStreamID: 1,
body: aggregateBody
}
, chunkSize);
};
let createRTMPType1Message = function(params) {
let ordinaryTimestampBytes;
let bodyLength = params.body.length;
let formatTypeID = 1;
if ((params.body == null)) {
logger.warn("[rtmp] warning: createRTMPType1Message(): body is not set for RTMP message");
}
if ((params.chunkStreamID == null)) {
logger.warn("[rtmp] warning: createRTMPType1Message(): chunkStreamID is not set for RTMP message");
}
if ((params.timestampDelta == null)) {
logger.warn("[rtmp] warning: createRTMPType1Message(): timestampDelta is not set for RTMP message");
}
if ((params.messageStreamID == null)) {
logger.warn("[rtmp] warning: createRTMPType1Message(): messageStreamID is not set for RTMP message");
}
let 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
let 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) {
let extendedTimestamp = new Buffer([
(params.timestampDelta >> 24) & 0xff,
(params.timestampDelta >> 16) & 0xff,
(params.timestampDelta >> 8) & 0xff,
params.timestampDelta & 0xff,
]);
header = Buffer.concat([
header, extendedTimestamp
], 12);
}
let { body } = params;
return Buffer.concat([header, body], 8 + bodyLength);
};
var createRTMPMessage = function(params, chunkSize) {
let timestamp;
if (chunkSize == null) { chunkSize = 128; }
let bodyLength = params.body.length;
// TODO: Use format type ID 1 and 2
let formatTypeID = 0;
if ((params.body == null)) {
logger.warn("[rtmp] warning: createRTMPMessage(): body is not set for RTMP message");
}
if ((params.chunkStreamID == null)) {
logger.warn("[rtmp] warning: createRTMPMessage(): chunkStreamID is not set for RTMP message");
}
if ((params.timestamp == null)) {
logger.warn("[rtmp] warning: createRTMPMessage(): timestamp is not set for RTMP message");
}
if ((params.messageStreamID == null)) {
logger.warn("[rtmp] warning: createRTMPMessage(): messageStreamID is not set for RTMP message");
}
let 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,
];
}
let 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,
])
];
let 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;
}
let { body } = params;
if (bodyLength > chunkSize) {
bufs.push(body.slice(0, chunkSize));
totalLength += chunkSize;
body = body.slice(chunkSize);
bodyLength -= chunkSize;
// Use Format Type 3 for remaining chunks
let type3Header = new Buffer([
(3 << 6) | params.chunkStreamID
]);
while (true) {
let bodyChunk = body.slice(0, chunkSize);
let bodyChunkLen = bodyChunk.length;
bufs.push(type3Header, bodyChunk);
totalLength += 1 + bodyChunkLen;
body = body.slice(bodyChunkLen);
bodyLength -= bodyChunkLen;
if (bodyLength === 0) {
break;
}
}
} else {
bufs.push(body);
totalLength += bodyLength;
}
return Buffer.concat(bufs, totalLength);
};
let createAMF0DataMessage = (params, chunkSize) => createRTMPMessage(createAMF0DataMessageParams(params), chunkSize);
var createAMF0DataMessageParams = function(params) {
let len = 0;
for (let obj of Array.from(params.objects)) {
len += obj.length;
}
let amf0Bytes = Buffer.concat(params.objects, len);
return {
chunkStreamID: params.chunkStreamID,
timestamp: params.timestamp,
messageTypeID: 0x12, // AMF0 Data
messageStreamID: params.messageStreamID,
body: amf0Bytes
};
};
let createAMF0CommandMessage = (params, chunkSize) => createRTMPMessage(createAMF0CommandMessageParams(params), chunkSize);
var createAMF0CommandMessageParams = function(params) {
let commandBuf = createAMF0Data(params.command);
let transactionIDBuf = createAMF0Data(params.transactionID);
let len = commandBuf.length + transactionIDBuf.length;
for (let obj of Array.from(params.objects)) {
len += obj.length;
}
let amf0Bytes = Buffer.concat([commandBuf, transactionIDBuf, ...params.objects], len);
return {
chunkStreamID: params.chunkStreamID,
timestamp: params.timestamp,
messageTypeID: 0x14, // AMF0 Command
messageStreamID: params.messageStreamID,
body: amf0Bytes
};
};
class RTMPSession {
constructor(socket) {
logger.debug("[rtmp] created a new session");
this.listeners = {};
this.state = SESSION_STATE_NEW;
this.socket = socket;
this.chunkSize = 128;
this.receiveChunkSize = 128;
this.previousChunkMessage = {};
this.isPlaying = false;
this.clientid = generateNewClientID();
this.useEncryption = false;
this.receiveTimestamp = null;
this.lastSentAckBytes = 0;
this.receivedBytes = 0;
this.stream = null; // AVStream
this.seekedDuringPause = false;
this.lastSentTimestamp = null;
this.isResuming = false;
// Some broadcaster software like Wirecast does not send Window Acknowledgement Size,
// so it seems we have to set a default value.
this.windowAckSize = 2500000;
}
toString() {
return `${this.clientid}: addr=${this.socket.remoteAddress} port=${this.socket.remotePort}`;
}
startPlaying() {
this.isPlaying = true;
return this.isResuming = false;
}
parseVideoMessage(buf) {
let info = flv.parseVideo(buf);
let nalUnitGlob = null;
let isEOS = false;
switch (info.videoDataTag.avcPacketType) {
case flv.AVC_PACKET_TYPE_SEQUENCE_HEADER:
// Retain AVC configuration
this.avcInfo = info.avcDecoderConfigurationRecord;
if (this.avcInfo.numOfSPS > 1) {
logger.warn(`warn: flv:parseVideo(): numOfSPS is ${numOfSPS} > 1 (may not work)`);
}
if (this.avcInfo.numOfPPS > 1) {
logger.warn(`warn: flv:parseVideo(): numOfPPS is ${numOfPPS} > 1 (may not work)`);
}
let sps = h264.concatWithStartCodePrefix(this.avcInfo.sps);
let pps = h264.concatWithStartCodePrefix(this.avcInfo.pps);
nalUnitGlob = Buffer.concat([sps, pps]);
break;
case flv.AVC_PACKET_TYPE_NALU:
if ((this.avcInfo == null)) {
throw new Error("[rtmp:publish] malformed video data: avcInfo is missing");
}
// TODO: This must be too heavy and needs better alternative.
let nalUnits = flv.splitNALUnits(info.nalUnits, this.avcInfo.nalUnitLengthSize);
nalUnitGlob = h264.concatWithStartCodePrefix(nalUnits);
break;
case flv.AVC_PACKET_TYPE_EOS:
isEOS = true;
break;
default:
throw new Error(`unknown AVCPacketType: ${flv.AVC_PACKET_TYPE_SEQUENCE_HEADER}`);
}
return {
info,
nalUnitGlob,
isEOS
};
}
parseAudioMessage(buf) {
let info = flv.parseAudio(buf);
let adtsFrame = null;
let { stream } = this;
if ((stream == null)) {
throw new Error("[rtmp] Stream not set for this session");
}
switch (info.audioDataTag.aacPacketType) {
case flv.AAC_PACKET_TYPE_SEQUENCE_HEADER:
if (info.audioSpecificConfig != null) {
stream.updateConfig({
audioSpecificConfig: info.audioSpecificConfig,
audioASCInfo: info.ascInfo
});
} else {
logger.warn("[rtmp] skipping empty AudioSpecificConfig");
}
break;
case flv.AAC_PACKET_TYPE_RAW:
if ((stream.audioASCInfo == null)) {
logger.error("[rtmp:publish] malformed audio data: AudioSpecificConfig is missing");
}
// TODO: This must be a little heavy and needs better alternative.
let adtsHeader = new Buffer(aac.createADTSHeader(stream.audioASCInfo, info.rawDataBlock.length));
adtsFrame = Buffer.concat([ adtsHeader, info.rawDataBlock ]);
break;
default:
throw new Error(`[rtmp:publish] unknown AAC_PACKET_TYPE: ${info.audioDataTag.aacPacketType}`);
}
return {
info,
adtsFrame
};
}
clearTimeout() {
if (this.timeoutTimer != null) {
clearTimeout(this.timeoutTimer);
return this.timeoutTimer = null;
}
}
scheduleTimeout() {
if (this.isTearedDown) {
return;
}
this.clearTimeout();
this.lastTimeoutScheduledTime = Date.now();
return this.timeoutTimer = setTimeout(() => {
if (this.isTearedDown) {
return;
}
if ((this.timeoutTimer == null)) {
return;
}
if ((Date.now() - this.lastTimeoutScheduledTime) < config.rtmpSessionTimeoutMs) {
return;
}
logger.info(`[rtmp:client=${this.clientid}] session timeout`);
return this.teardown();
}
, config.rtmpSessionTimeoutMs);
}