-
Notifications
You must be signed in to change notification settings - Fork 211
/
caption-stream.js
1816 lines (1583 loc) · 54.4 KB
/
caption-stream.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
/**
* mux.js
*
* Copyright (c) Brightcove
* Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
*
* Reads in-band caption information from a video elementary
* stream. Captions must follow the CEA-708 standard for injection
* into an MPEG-2 transport streams.
* @see https://en.wikipedia.org/wiki/CEA-708
* @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
*/
'use strict';
// -----------------
// Link To Transport
// -----------------
var Stream = require('../utils/stream');
var cea708Parser = require('../tools/caption-packet-parser');
var CaptionStream = function(options) {
options = options || {};
CaptionStream.prototype.init.call(this);
// parse708captions flag, default to true
this.parse708captions_ = typeof options.parse708captions === 'boolean' ?
options.parse708captions :
true;
this.captionPackets_ = [];
this.ccStreams_ = [
new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
];
if (this.parse708captions_) {
this.cc708Stream_ = new Cea708Stream({captionServices: options.captionServices}); // eslint-disable-line no-use-before-define
}
this.reset();
// forward data and done events from CCs to this CaptionStream
this.ccStreams_.forEach(function(cc) {
cc.on('data', this.trigger.bind(this, 'data'));
cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
cc.on('done', this.trigger.bind(this, 'done'));
}, this);
if (this.parse708captions_) {
this.cc708Stream_.on('data', this.trigger.bind(this, 'data'));
this.cc708Stream_.on('partialdone', this.trigger.bind(this, 'partialdone'));
this.cc708Stream_.on('done', this.trigger.bind(this, 'done'));
}
};
CaptionStream.prototype = new Stream();
CaptionStream.prototype.push = function(event) {
var sei, userData, newCaptionPackets;
// only examine SEI NALs
if (event.nalUnitType !== 'sei_rbsp') {
return;
}
// parse the sei
sei = cea708Parser.parseSei(event.escapedRBSP);
// no payload data, skip
if (!sei.payload) {
return;
}
// ignore everything but user_data_registered_itu_t_t35
if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
return;
}
// parse out the user data payload
userData = cea708Parser.parseUserData(sei);
// ignore unrecognized userData
if (!userData) {
return;
}
// Sometimes, the same segment # will be downloaded twice. To stop the
// caption data from being processed twice, we track the latest dts we've
// received and ignore everything with a dts before that. However, since
// data for a specific dts can be split across packets on either side of
// a segment boundary, we need to make sure we *don't* ignore the packets
// from the *next* segment that have dts === this.latestDts_. By constantly
// tracking the number of packets received with dts === this.latestDts_, we
// know how many should be ignored once we start receiving duplicates.
if (event.dts < this.latestDts_) {
// We've started getting older data, so set the flag.
this.ignoreNextEqualDts_ = true;
return;
} else if ((event.dts === this.latestDts_) && (this.ignoreNextEqualDts_)) {
this.numSameDts_--;
if (!this.numSameDts_) {
// We've received the last duplicate packet, time to start processing again
this.ignoreNextEqualDts_ = false;
}
return;
}
// parse out CC data packets and save them for later
newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
if (this.latestDts_ !== event.dts) {
this.numSameDts_ = 0;
}
this.numSameDts_++;
this.latestDts_ = event.dts;
};
CaptionStream.prototype.flushCCStreams = function(flushType) {
this.ccStreams_.forEach(function(cc) {
return flushType === 'flush' ? cc.flush() : cc.partialFlush();
}, this);
};
CaptionStream.prototype.flushStream = function(flushType) {
// make sure we actually parsed captions before proceeding
if (!this.captionPackets_.length) {
this.flushCCStreams(flushType);
return;
}
// In Chrome, the Array#sort function is not stable so add a
// presortIndex that we can use to ensure we get a stable-sort
this.captionPackets_.forEach(function(elem, idx) {
elem.presortIndex = idx;
});
// sort caption byte-pairs based on their PTS values
this.captionPackets_.sort(function(a, b) {
if (a.pts === b.pts) {
return a.presortIndex - b.presortIndex;
}
return a.pts - b.pts;
});
this.captionPackets_.forEach(function(packet) {
if (packet.type < 2) {
// Dispatch packet to the right Cea608Stream
this.dispatchCea608Packet(packet);
} else {
// Dispatch packet to the Cea708Stream
this.dispatchCea708Packet(packet);
}
}, this);
this.captionPackets_.length = 0;
this.flushCCStreams(flushType);
};
CaptionStream.prototype.flush = function() {
return this.flushStream('flush');
};
// Only called if handling partial data
CaptionStream.prototype.partialFlush = function() {
return this.flushStream('partialFlush');
};
CaptionStream.prototype.reset = function() {
this.latestDts_ = null;
this.ignoreNextEqualDts_ = false;
this.numSameDts_ = 0;
this.activeCea608Channel_ = [null, null];
this.ccStreams_.forEach(function(ccStream) {
ccStream.reset();
});
};
// From the CEA-608 spec:
/*
* When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
* by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
* used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
* and subsequent data should then be processed according to the FCC rules. It may be necessary for the
* line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
* to switch to captioning or Text.
*/
// With that in mind, we ignore any data between an XDS control code and a
// subsequent closed-captioning control code.
CaptionStream.prototype.dispatchCea608Packet = function(packet) {
// NOTE: packet.type is the CEA608 field
if (this.setsTextOrXDSActive(packet)) {
this.activeCea608Channel_[packet.type] = null;
} else if (this.setsChannel1Active(packet)) {
this.activeCea608Channel_[packet.type] = 0;
} else if (this.setsChannel2Active(packet)) {
this.activeCea608Channel_[packet.type] = 1;
}
if (this.activeCea608Channel_[packet.type] === null) {
// If we haven't received anything to set the active channel, or the
// packets are Text/XDS data, discard the data; we don't want jumbled
// captions
return;
}
this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
};
CaptionStream.prototype.setsChannel1Active = function(packet) {
return ((packet.ccData & 0x7800) === 0x1000);
};
CaptionStream.prototype.setsChannel2Active = function(packet) {
return ((packet.ccData & 0x7800) === 0x1800);
};
CaptionStream.prototype.setsTextOrXDSActive = function(packet) {
return ((packet.ccData & 0x7100) === 0x0100) ||
((packet.ccData & 0x78fe) === 0x102a) ||
((packet.ccData & 0x78fe) === 0x182a);
};
CaptionStream.prototype.dispatchCea708Packet = function(packet) {
if (this.parse708captions_) {
this.cc708Stream_.push(packet);
}
};
// ----------------------
// Session to Application
// ----------------------
// This hash maps special and extended character codes to their
// proper Unicode equivalent. The first one-byte key is just a
// non-standard character code. The two-byte keys that follow are
// the extended CEA708 character codes, along with the preceding
// 0x10 extended character byte to distinguish these codes from
// non-extended character codes. Every CEA708 character code that
// is not in this object maps directly to a standard unicode
// character code.
// The transparent space and non-breaking transparent space are
// technically not fully supported since there is no code to
// make them transparent, so they have normal non-transparent
// stand-ins.
// The special closed caption (CC) character isn't a standard
// unicode character, so a fairly similar unicode character was
// chosen in it's place.
var CHARACTER_TRANSLATION_708 = {
0x7f: 0x266a, // ♪
0x1020: 0x20, // Transparent Space
0x1021: 0xa0, // Nob-breaking Transparent Space
0x1025: 0x2026, // …
0x102a: 0x0160, // Š
0x102c: 0x0152, // Œ
0x1030: 0x2588, // █
0x1031: 0x2018, // ‘
0x1032: 0x2019, // ’
0x1033: 0x201c, // “
0x1034: 0x201d, // ”
0x1035: 0x2022, // •
0x1039: 0x2122, // ™
0x103a: 0x0161, // š
0x103c: 0x0153, // œ
0x103d: 0x2120, // ℠
0x103f: 0x0178, // Ÿ
0x1076: 0x215b, // ⅛
0x1077: 0x215c, // ⅜
0x1078: 0x215d, // ⅝
0x1079: 0x215e, // ⅞
0x107a: 0x23d0, // ⏐
0x107b: 0x23a4, // ⎤
0x107c: 0x23a3, // ⎣
0x107d: 0x23af, // ⎯
0x107e: 0x23a6, // ⎦
0x107f: 0x23a1, // ⎡
0x10a0: 0x3138 // ㄸ (CC char)
};
var get708CharFromCode = function(code) {
var newCode = CHARACTER_TRANSLATION_708[code] || code;
if ((code & 0x1000) && code === newCode) {
// Invalid extended code
return '';
}
return String.fromCharCode(newCode);
};
var within708TextBlock = function(b) {
return (0x20 <= b && b <= 0x7f) || (0xa0 <= b && b <= 0xff);
};
var Cea708Window = function(windowNum) {
this.windowNum = windowNum;
this.reset();
};
Cea708Window.prototype.reset = function() {
this.clearText();
this.pendingNewLine = false;
this.winAttr = {};
this.penAttr = {};
this.penLoc = {};
this.penColor = {};
// These default values are arbitrary,
// defineWindow will usually override them
this.visible = 0;
this.rowLock = 0;
this.columnLock = 0;
this.priority = 0;
this.relativePositioning = 0;
this.anchorVertical = 0;
this.anchorHorizontal = 0;
this.anchorPoint = 0;
this.rowCount = 1;
this.virtualRowCount = this.rowCount + 1;
this.columnCount = 41;
this.windowStyle = 0;
this.penStyle = 0;
};
Cea708Window.prototype.getText = function() {
return this.rows.join('\n');
};
Cea708Window.prototype.clearText = function() {
this.rows = [''];
this.rowIdx = 0;
};
Cea708Window.prototype.newLine = function(pts) {
if (this.rows.length >= this.virtualRowCount && typeof this.beforeRowOverflow === 'function') {
this.beforeRowOverflow(pts);
}
if (this.rows.length > 0) {
this.rows.push('');
this.rowIdx++;
}
// Show all virtual rows since there's no visible scrolling
while (this.rows.length > this.virtualRowCount) {
this.rows.shift();
this.rowIdx--;
}
};
Cea708Window.prototype.isEmpty = function() {
if (this.rows.length === 0) {
return true;
} else if (this.rows.length === 1) {
return this.rows[0] === '';
}
return false;
};
Cea708Window.prototype.addText = function(text) {
this.rows[this.rowIdx] += text;
};
Cea708Window.prototype.backspace = function() {
if (!this.isEmpty()) {
var row = this.rows[this.rowIdx];
this.rows[this.rowIdx] = row.substr(0, row.length - 1);
}
};
var Cea708Service = function(serviceNum, encoding, stream) {
this.serviceNum = serviceNum;
this.text = '';
this.currentWindow = new Cea708Window(-1);
this.windows = [];
this.stream = stream;
// Try to setup a TextDecoder if an `encoding` value was provided
if (typeof encoding === 'string') {
this.createTextDecoder(encoding);
}
};
/**
* Initialize service windows
* Must be run before service use
*
* @param {Integer} pts PTS value
* @param {Function} beforeRowOverflow Function to execute before row overflow of a window
*/
Cea708Service.prototype.init = function(pts, beforeRowOverflow) {
this.startPts = pts;
for (var win = 0; win < 8; win++) {
this.windows[win] = new Cea708Window(win);
if (typeof beforeRowOverflow === 'function') {
this.windows[win].beforeRowOverflow = beforeRowOverflow;
}
}
};
/**
* Set current window of service to be affected by commands
*
* @param {Integer} windowNum Window number
*/
Cea708Service.prototype.setCurrentWindow = function(windowNum) {
this.currentWindow = this.windows[windowNum];
};
/**
* Try to create a TextDecoder if it is natively supported
*/
Cea708Service.prototype.createTextDecoder = function(encoding) {
if (typeof TextDecoder === 'undefined') {
this.stream.trigger('log', {
level: 'warn',
message: 'The `encoding` option is unsupported without TextDecoder support'
});
} else {
try {
this.textDecoder_ = new TextDecoder(encoding);
} catch (error) {
this.stream.trigger('log', {
level: 'warn',
message: 'TextDecoder could not be created with ' + encoding + ' encoding. ' + error
});
}
}
}
var Cea708Stream = function(options) {
options = options || {};
Cea708Stream.prototype.init.call(this);
var self = this;
var captionServices = options.captionServices || {};
var captionServiceEncodings = {};
var serviceProps;
// Get service encodings from captionServices option block
Object.keys(captionServices).forEach(serviceName => {
serviceProps = captionServices[serviceName];
if (/^SERVICE/.test(serviceName)) {
captionServiceEncodings[serviceName] = serviceProps.encoding;
}
});
this.serviceEncodings = captionServiceEncodings;
this.current708Packet = null;
this.services = {};
this.push = function(packet) {
if (packet.type === 3) {
// 708 packet start
self.new708Packet();
self.add708Bytes(packet);
} else {
if (self.current708Packet === null) {
// This should only happen at the start of a file if there's no packet start.
self.new708Packet();
}
self.add708Bytes(packet);
}
};
};
Cea708Stream.prototype = new Stream();
/**
* Push current 708 packet, create new 708 packet.
*/
Cea708Stream.prototype.new708Packet = function() {
if (this.current708Packet !== null) {
this.push708Packet();
}
this.current708Packet = {
data: [],
ptsVals: []
};
};
/**
* Add pts and both bytes from packet into current 708 packet.
*/
Cea708Stream.prototype.add708Bytes = function(packet) {
var data = packet.ccData;
var byte0 = data >>> 8;
var byte1 = data & 0xff;
// I would just keep a list of packets instead of bytes, but it isn't clear in the spec
// that service blocks will always line up with byte pairs.
this.current708Packet.ptsVals.push(packet.pts);
this.current708Packet.data.push(byte0);
this.current708Packet.data.push(byte1);
};
/**
* Parse completed 708 packet into service blocks and push each service block.
*/
Cea708Stream.prototype.push708Packet = function() {
var packet708 = this.current708Packet;
var packetData = packet708.data;
var serviceNum = null;
var blockSize = null;
var i = 0;
var b = packetData[i++];
packet708.seq = b >> 6;
packet708.sizeCode = b & 0x3f; // 0b00111111;
for (; i < packetData.length; i++) {
b = packetData[i++];
serviceNum = b >> 5;
blockSize = b & 0x1f; // 0b00011111
if (serviceNum === 7 && blockSize > 0) {
// Extended service num
b = packetData[i++];
serviceNum = b;
}
this.pushServiceBlock(serviceNum, i, blockSize);
if (blockSize > 0) {
i += blockSize - 1;
}
}
};
/**
* Parse service block, execute commands, read text.
*
* Note: While many of these commands serve important purposes,
* many others just parse out the parameters or attributes, but
* nothing is done with them because this is not a full and complete
* implementation of the entire 708 spec.
*
* @param {Integer} serviceNum Service number
* @param {Integer} start Start index of the 708 packet data
* @param {Integer} size Block size
*/
Cea708Stream.prototype.pushServiceBlock = function(serviceNum, start, size) {
var b;
var i = start;
var packetData = this.current708Packet.data;
var service = this.services[serviceNum];
if (!service) {
service = this.initService(serviceNum, i);
}
for (; i < start + size && i < packetData.length; i++) {
b = packetData[i];
if (within708TextBlock(b)) {
i = this.handleText(i, service);
} else if (b === 0x18) {
i = this.multiByteCharacter(i, service);
} else if (b === 0x10) {
i = this.extendedCommands(i, service);
} else if (0x80 <= b && b <= 0x87) {
i = this.setCurrentWindow(i, service);
} else if (0x98 <= b && b <= 0x9f) {
i = this.defineWindow(i, service);
} else if (b === 0x88) {
i = this.clearWindows(i, service);
} else if (b === 0x8c) {
i = this.deleteWindows(i, service);
} else if (b === 0x89) {
i = this.displayWindows(i, service);
} else if (b === 0x8a) {
i = this.hideWindows(i, service);
} else if (b === 0x8b) {
i = this.toggleWindows(i, service);
} else if (b === 0x97) {
i = this.setWindowAttributes(i, service);
} else if (b === 0x90) {
i = this.setPenAttributes(i, service);
} else if (b === 0x91) {
i = this.setPenColor(i, service);
} else if (b === 0x92) {
i = this.setPenLocation(i, service);
} else if (b === 0x8f) {
service = this.reset(i, service);
} else if (b === 0x08) {
// BS: Backspace
service.currentWindow.backspace();
} else if (b === 0x0c) {
// FF: Form feed
service.currentWindow.clearText();
} else if (b === 0x0d) {
// CR: Carriage return
service.currentWindow.pendingNewLine = true;
} else if (b === 0x0e) {
// HCR: Horizontal carriage return
service.currentWindow.clearText();
} else if (b === 0x8d) {
// DLY: Delay, nothing to do
i++;
} else if (b === 0x8e) {
// DLC: Delay cancel, nothing to do
} else if (b === 0x03) {
// ETX: End Text, don't need to do anything
} else if (b === 0x00) {
// Padding
} else {
// Unknown command
}
}
};
/**
* Execute an extended command
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.extendedCommands = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[++i];
if (within708TextBlock(b)) {
i = this.handleText(i, service, {isExtended: true});
} else {
// Unknown command
}
return i;
};
/**
* Get PTS value of a given byte index
*
* @param {Integer} byteIndex Index of the byte
* @return {Integer} PTS
*/
Cea708Stream.prototype.getPts = function(byteIndex) {
// There's 1 pts value per 2 bytes
return this.current708Packet.ptsVals[Math.floor(byteIndex / 2)];
};
/**
* Initializes a service
*
* @param {Integer} serviceNum Service number
* @return {Service} Initialized service object
*/
Cea708Stream.prototype.initService = function(serviceNum, i) {
var serviceName = 'SERVICE' + serviceNum;
var self = this;
var serviceName;
var encoding;
if (serviceName in this.serviceEncodings) {
encoding = this.serviceEncodings[serviceName];
}
this.services[serviceNum] = new Cea708Service(serviceNum, encoding, self);
this.services[serviceNum].init(this.getPts(i), function(pts) {
self.flushDisplayed(pts, self.services[serviceNum]);
});
return this.services[serviceNum];
};
/**
* Execute text writing to current window
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.handleText = function(i, service, options) {
var isExtended = options && options.isExtended;
var isMultiByte = options && options.isMultiByte;
var packetData = this.current708Packet.data;
var extended = isExtended ? 0x1000 : 0x0000;
var currentByte = packetData[i];
var nextByte = packetData[i + 1];
var win = service.currentWindow;
var char;
var charCodeArray;
// Converts an array of bytes to a unicode hex string.
function toHexString(byteArray) {
return byteArray.map((byte) => {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
};
if (isMultiByte) {
charCodeArray = [currentByte, nextByte];
i++;
} else {
charCodeArray = [currentByte];
}
// Use the TextDecoder if one was created for this service
if (service.textDecoder_ && !isExtended) {
char = service.textDecoder_.decode(new Uint8Array(charCodeArray));
} else {
// We assume any multi-byte char without a decoder is unicode.
if (isMultiByte) {
const unicode = toHexString(charCodeArray);
// Takes a unicode hex string and creates a single character.
char = String.fromCharCode(parseInt(unicode, 16));
} else {
char = get708CharFromCode(extended | currentByte);
}
}
if (win.pendingNewLine && !win.isEmpty()) {
win.newLine(this.getPts(i));
}
win.pendingNewLine = false;
win.addText(char);
return i;
};
/**
* Handle decoding of multibyte character
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.multiByteCharacter = function (i, service) {
var packetData = this.current708Packet.data;
var firstByte = packetData[i + 1];
var secondByte = packetData[i + 2];
if (within708TextBlock(firstByte) && within708TextBlock(secondByte)) {
i = this.handleText(++i, service, {isMultiByte: true});
} else {
// Unknown command
}
return i;
};
/**
* Parse and execute the CW# command.
*
* Set the current window.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.setCurrentWindow = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[i];
var windowNum = b & 0x07;
service.setCurrentWindow(windowNum);
return i;
};
/**
* Parse and execute the DF# command.
*
* Define a window and set it as the current window.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.defineWindow = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[i];
var windowNum = b & 0x07;
service.setCurrentWindow(windowNum);
var win = service.currentWindow;
b = packetData[++i];
win.visible = (b & 0x20) >> 5; // v
win.rowLock = (b & 0x10) >> 4; // rl
win.columnLock = (b & 0x08) >> 3; // cl
win.priority = b & 0x07; // p
b = packetData[++i];
win.relativePositioning = (b & 0x80) >> 7; // rp
win.anchorVertical = b & 0x7f; // av
b = packetData[++i];
win.anchorHorizontal = b; // ah
b = packetData[++i];
win.anchorPoint = (b & 0xf0) >> 4; // ap
win.rowCount = b & 0x0f; // rc
b = packetData[++i];
win.columnCount = b & 0x3f; // cc
b = packetData[++i];
win.windowStyle = (b & 0x38) >> 3; // ws
win.penStyle = b & 0x07; // ps
// The spec says there are (rowCount+1) "virtual rows"
win.virtualRowCount = win.rowCount + 1;
return i;
};
/**
* Parse and execute the SWA command.
*
* Set attributes of the current window.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.setWindowAttributes = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[i];
var winAttr = service.currentWindow.winAttr;
b = packetData[++i];
winAttr.fillOpacity = (b & 0xc0) >> 6; // fo
winAttr.fillRed = (b & 0x30) >> 4; // fr
winAttr.fillGreen = (b & 0x0c) >> 2; // fg
winAttr.fillBlue = b & 0x03; // fb
b = packetData[++i];
winAttr.borderType = (b & 0xc0) >> 6; // bt
winAttr.borderRed = (b & 0x30) >> 4; // br
winAttr.borderGreen = (b & 0x0c) >> 2; // bg
winAttr.borderBlue = b & 0x03; // bb
b = packetData[++i];
winAttr.borderType += (b & 0x80) >> 5; // bt
winAttr.wordWrap = (b & 0x40) >> 6; // ww
winAttr.printDirection = (b & 0x30) >> 4; // pd
winAttr.scrollDirection = (b & 0x0c) >> 2; // sd
winAttr.justify = b & 0x03; // j
b = packetData[++i];
winAttr.effectSpeed = (b & 0xf0) >> 4; // es
winAttr.effectDirection = (b & 0x0c) >> 2; // ed
winAttr.displayEffect = b & 0x03; // de
return i;
};
/**
* Gather text from all displayed windows and push a caption to output.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
*/
Cea708Stream.prototype.flushDisplayed = function(pts, service) {
var displayedText = [];
// TODO: Positioning not supported, displaying multiple windows will not necessarily
// display text in the correct order, but sample files so far have not shown any issue.
for (var winId = 0; winId < 8; winId++) {
if (service.windows[winId].visible && !service.windows[winId].isEmpty()) {
displayedText.push(service.windows[winId].getText());
}
}
service.endPts = pts;
service.text = displayedText.join('\n\n');
this.pushCaption(service);
service.startPts = pts;
};
/**
* Push a caption to output if the caption contains text.
*
* @param {Service} service The service object to be affected
*/
Cea708Stream.prototype.pushCaption = function(service) {
if (service.text !== '') {
this.trigger('data', {
startPts: service.startPts,
endPts: service.endPts,
text: service.text,
stream: 'cc708_' + service.serviceNum
});
service.text = '';
service.startPts = service.endPts;
}
};
/**
* Parse and execute the DSW command.
*
* Set visible property of windows based on the parsed bitmask.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.displayWindows = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[++i];
var pts = this.getPts(i);
this.flushDisplayed(pts, service);
for (var winId = 0; winId < 8; winId++) {
if (b & (0x01 << winId)) {
service.windows[winId].visible = 1;
}
}
return i;
};
/**
* Parse and execute the HDW command.
*
* Set visible property of windows based on the parsed bitmask.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.hideWindows = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[++i];
var pts = this.getPts(i);
this.flushDisplayed(pts, service);
for (var winId = 0; winId < 8; winId++) {
if (b & (0x01 << winId)) {
service.windows[winId].visible = 0;
}
}
return i;
};
/**
* Parse and execute the TGW command.
*
* Set visible property of windows based on the parsed bitmask.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.toggleWindows = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[++i];
var pts = this.getPts(i);
this.flushDisplayed(pts, service);
for (var winId = 0; winId < 8; winId++) {
if (b & (0x01 << winId)) {
service.windows[winId].visible ^= 1;
}
}
return i;
};
/**
* Parse and execute the CLW command.
*
* Clear text of windows based on the parsed bitmask.
*
* @param {Integer} i Current index in the 708 packet
* @param {Service} service The service object to be affected
* @return {Integer} New index after parsing
*/
Cea708Stream.prototype.clearWindows = function(i, service) {
var packetData = this.current708Packet.data;
var b = packetData[++i];
var pts = this.getPts(i);
this.flushDisplayed(pts, service);
for (var winId = 0; winId < 8; winId++) {
if (b & (0x01 << winId)) {
service.windows[winId].clearText();
}
}
return i;
};
/**
* Parse and execute the DLW command.