Source: lib/cea/cea_decoder.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.cea.CeaDecoder');
  7. goog.require('shaka.cea.Cea608DataChannel');
  8. goog.require('shaka.cea.Cea708Service');
  9. goog.require('shaka.cea.DtvccPacketBuilder');
  10. goog.require('shaka.cea.ICaptionDecoder');
  11. goog.require('shaka.log');
  12. goog.require('shaka.util.DataViewReader');
  13. goog.require('shaka.util.Error');
  14. goog.requireType('shaka.cea.DtvccPacket');
  15. /**
  16. * CEA-X08 captions decoder. Currently only CEA-608 supported.
  17. * @implements {shaka.cea.ICaptionDecoder}
  18. */
  19. shaka.cea.CeaDecoder = class {
  20. /** */
  21. constructor() {
  22. /**
  23. * An array of CEA-608 closed caption data extracted for decoding.
  24. * @private {!Array<!shaka.cea.Cea608DataChannel.Cea608Packet>}
  25. */
  26. this.cea608DataArray_ = [];
  27. /**
  28. * An array of CEA-708 closed caption data extracted for decoding.
  29. * @private {!Array<!shaka.cea.Cea708Service.Cea708Byte>}
  30. */
  31. this.cea708DataArray_ = [];
  32. /**
  33. * A DTVCC Packet builder for CEA-708 data.
  34. * @private {!shaka.cea.DtvccPacketBuilder}
  35. */
  36. this.dtvccPacketBuilder_ = new shaka.cea.DtvccPacketBuilder();
  37. /**
  38. * Number of consecutive bad frames decoded on CEA-608.
  39. * @private {number}
  40. */
  41. this.badFrames_ = 0;
  42. /**
  43. * A map containing the stream for each mode.
  44. * @private {!Map<string, !shaka.cea.Cea608DataChannel>}
  45. */
  46. this.cea608ModeToStream_ = new Map([
  47. ['CC1', new shaka.cea.Cea608DataChannel(0, 0)], // F1 + C1 -> CC1
  48. ['CC2', new shaka.cea.Cea608DataChannel(0, 1)], // F1 + C2 -> CC2
  49. ['CC3', new shaka.cea.Cea608DataChannel(1, 0)], // F2 + C1 -> CC3
  50. ['CC4', new shaka.cea.Cea608DataChannel(1, 1)], // F2 + C2 -> CC4
  51. ]);
  52. /**
  53. * The current channel that is active on CEA-608 field 1.
  54. * @private {number}
  55. */
  56. this.currentField1Channel_ = 0;
  57. /**
  58. * The current channel that is active on CEA-608 field 2.
  59. * @private {number}
  60. */
  61. this.currentField2Channel_ = 0;
  62. /**
  63. * Map of service number to CEA-708 services, initially empty. Since there
  64. * can be up to 63 services, they are created dynamically only when needed.
  65. * @private {!Map<number, shaka.cea.Cea708Service>}
  66. */
  67. this.serviceNumberToService_ = new Map();
  68. this.reset();
  69. }
  70. /**
  71. * Clears the decoder.
  72. * @override
  73. */
  74. clear() {
  75. this.badFrames_ = 0;
  76. this.cea608DataArray_ = [];
  77. this.cea708DataArray_ = [];
  78. this.dtvccPacketBuilder_.clear();
  79. this.reset();
  80. // Clear all the CEA-708 services.
  81. for (const service of this.serviceNumberToService_.values()) {
  82. service.clear();
  83. }
  84. }
  85. /**
  86. * Resets the decoder.
  87. */
  88. reset() {
  89. this.currentField1Channel_ = 0;
  90. this.currentField2Channel_ = 0;
  91. for (const stream of this.cea608ModeToStream_.values()) {
  92. stream.reset();
  93. }
  94. }
  95. /**
  96. * Extracts closed caption bytes from CEA-X08 packets from the stream based on
  97. * ANSI/SCTE 128 and A/53, Part 4.
  98. * @override
  99. */
  100. extract(userDataSeiMessage, pts) {
  101. const reader = new shaka.util.DataViewReader(
  102. userDataSeiMessage, shaka.util.DataViewReader.Endianness.BIG_ENDIAN);
  103. if (reader.getLength() < shaka.cea.CeaDecoder.MIN_LENGTH) {
  104. return;
  105. }
  106. if (reader.readUint8() !== shaka.cea.CeaDecoder.USA_COUNTRY_CODE) {
  107. return;
  108. }
  109. if (reader.readUint16() !== shaka.cea.CeaDecoder.ATSC_PROVIDER_CODE) {
  110. return;
  111. }
  112. if (reader.readUint32() !== shaka.cea.CeaDecoder.ATSC1_USER_IDENTIFIER) {
  113. return;
  114. }
  115. // user_data_type_code: 0x03 - cc_data()
  116. if (reader.readUint8() !== 0x03) {
  117. return;
  118. }
  119. // 1 bit reserved
  120. // 1 bit process_cc_data_flag
  121. // 1 bit zero_bit
  122. // 5 bits cc_count
  123. const captionData = reader.readUint8();
  124. // If process_cc_data_flag is not set, do not process this data.
  125. if ((captionData & 0x40) === 0) {
  126. return;
  127. }
  128. const count = captionData & 0x1f;
  129. // 8 bits reserved
  130. reader.skip(1);
  131. for (let i = 0; i < count; i++) {
  132. const cc = reader.readUint8();
  133. // When ccValid is 0, the next two bytes should be discarded.
  134. const ccValid = (cc & 0x04) >> 2;
  135. const ccData1 = reader.readUint8();
  136. const ccData2 = reader.readUint8();
  137. if (ccValid) {
  138. const ccType = cc & 0x03;
  139. // Send the packet to the appropriate data array (CEA-608 or CEA-708).
  140. if (ccType === shaka.cea.CeaDecoder.NTSC_CC_FIELD_1 ||
  141. ccType === shaka.cea.CeaDecoder.NTSC_CC_FIELD_2) {
  142. // CEA-608 NTSC (Line 21) Data.
  143. this.cea608DataArray_.push({
  144. pts,
  145. type: ccType,
  146. ccData1,
  147. ccData2,
  148. order: this.cea608DataArray_.length,
  149. });
  150. } else {
  151. // CEA-708 DTVCC Data.
  152. this.cea708DataArray_.push({
  153. pts,
  154. type: ccType,
  155. value: ccData1,
  156. order: this.cea708DataArray_.length,
  157. });
  158. // The second byte should always be labelled as DTVCC packet data.
  159. // Even if this pair was a DTVCC packet start, only the first byte
  160. // contains header info, and the second byte is just packet data.
  161. this.cea708DataArray_.push({
  162. pts,
  163. type: shaka.cea.DtvccPacketBuilder.DTVCC_PACKET_DATA,
  164. value: ccData2,
  165. order: this.cea708DataArray_.length,
  166. });
  167. }
  168. }
  169. }
  170. }
  171. /**
  172. * Decodes extracted closed caption data.
  173. * @override
  174. */
  175. decode() {
  176. /** @type {!Array.<!shaka.cea.ICaptionDecoder.ClosedCaption>} */
  177. const parsedClosedCaptions = [];
  178. // In some versions of Chrome, and other browsers, the default sorting
  179. // algorithm isn't stable. This comparator sorts on presentation
  180. // timestamp, and breaks ties on receive order (position in array).
  181. const stableComparator =
  182. (p1, p2) => (p1.pts - p2.pts) || (p1.order - p2.order);
  183. this.cea608DataArray_.sort(stableComparator);
  184. this.cea708DataArray_.sort(stableComparator);
  185. // CEA-608 packets are just byte pairs. Decode all of them.
  186. for (const cea608Packet of this.cea608DataArray_) {
  187. const parsedClosedCaption = this.decodeCea608_(cea608Packet);
  188. if (parsedClosedCaption) {
  189. parsedClosedCaptions.push(parsedClosedCaption);
  190. }
  191. }
  192. // CEA-708 packets are DTVCC packets composed of many byte pairs. Add all
  193. // byte pairs to the packet builder, and process + clear any ready packets.
  194. for (const cea708Byte of this.cea708DataArray_) {
  195. this.dtvccPacketBuilder_.addByte(cea708Byte);
  196. }
  197. const dtvccPackets = this.dtvccPacketBuilder_.getBuiltPackets();
  198. for (const dtvccPacket of dtvccPackets) {
  199. const closedCaptions = this.decodeCea708_(dtvccPacket);
  200. parsedClosedCaptions.push(...closedCaptions);
  201. }
  202. // Clear all processed data.
  203. this.dtvccPacketBuilder_.clearBuiltPackets();
  204. this.cea608DataArray_ = [];
  205. this.cea708DataArray_ = [];
  206. return parsedClosedCaptions;
  207. }
  208. /**
  209. * Decodes a CEA-608 closed caption packet based on ANSI/CEA-608.
  210. * @param {shaka.cea.Cea608DataChannel.Cea608Packet} ccPacket
  211. * @return {?shaka.cea.ICaptionDecoder.ClosedCaption}
  212. * @private
  213. */
  214. decodeCea608_(ccPacket) {
  215. const fieldNum = ccPacket.type;
  216. // If this packet is a control code, then it also sets the channel.
  217. // For control codes, cc_data_1 has the form |P|0|0|1|C|X|X|X|.
  218. // "C" is the channel bit. It indicates whether to set C2 active.
  219. if (shaka.cea.Cea608DataChannel.isControlCode(ccPacket.ccData1)) {
  220. const channelNum = (ccPacket.ccData1 >> 3) & 0x01; // Get channel bit.
  221. // Change the stream based on the field, and the new channel
  222. if (fieldNum === 0) {
  223. this.currentField1Channel_ = channelNum;
  224. } else {
  225. this.currentField2Channel_ = channelNum;
  226. }
  227. }
  228. // Get the correct stream for this caption packet (CC1, ..., CC4)
  229. const selectedChannel = fieldNum ?
  230. this.currentField2Channel_ : this.currentField1Channel_;
  231. const selectedMode = `CC${((fieldNum << 1) | selectedChannel) + 1}`;
  232. const selectedStream = this.cea608ModeToStream_.get(selectedMode);
  233. // Check for bad frames (bad pairs). This can be two 0xff, two 0x00, or any
  234. // byte of even parity. ccData1 and ccData2 should be uint8 of odd parity.
  235. if ((ccPacket.ccData1 === 0xff && ccPacket.ccData2 === 0xff) ||
  236. (!ccPacket.ccData1 && !ccPacket.ccData2) ||
  237. !this.isOddParity_(ccPacket.ccData1) ||
  238. !this.isOddParity_(ccPacket.ccData2)) {
  239. // Per CEA-608-B C.21, reset the memory after 45 consecutive bad frames.
  240. if (++this.badFrames_ >= 45) {
  241. this.reset();
  242. }
  243. return null;
  244. }
  245. this.badFrames_ = 0;
  246. // Remove the MSB (parity bit).
  247. ccPacket.ccData1 &= 0x7f;
  248. ccPacket.ccData2 &= 0x7f;
  249. // Check for empty captions and skip them.
  250. if (!ccPacket.ccData1 && !ccPacket.ccData2) {
  251. return null;
  252. }
  253. // Process the clean CC data pair.
  254. let parsedClosedCaption = null;
  255. if (shaka.cea.Cea608DataChannel.isControlCode(ccPacket.ccData1)) {
  256. parsedClosedCaption = selectedStream.handleControlCode(ccPacket);
  257. } else {
  258. // Handle as a Basic North American Character.
  259. selectedStream.handleBasicNorthAmericanChar(
  260. ccPacket.ccData1, ccPacket.ccData2);
  261. }
  262. return parsedClosedCaption;
  263. }
  264. /**
  265. * Decodes a CEA-708 DTVCC packet based on ANSI/CTA-708-E.
  266. * @param {shaka.cea.DtvccPacket} dtvccPacket
  267. * @return {!Array<!shaka.cea.ICaptionDecoder.ClosedCaption>}
  268. * @private
  269. */
  270. decodeCea708_(dtvccPacket) {
  271. const parsedClosedCaptions = [];
  272. try {
  273. while (dtvccPacket.hasMoreData()) {
  274. // Process a service block.
  275. const serviceBlockHeader = dtvccPacket.readByte().value;
  276. // First 3 bits are service number, next 5 are block size,
  277. // representing the number of bytes coming in this block
  278. // (discluding a possible extended service block header byte)
  279. let serviceNumber = (serviceBlockHeader & 0xe0) >> 5;
  280. const blockSize = serviceBlockHeader & 0x1f;
  281. if (serviceNumber === /* 0b111 */ 0x07 && blockSize != 0) {
  282. // 2 bits null padding, 6 bits extended service number
  283. const extendedServiceBlockHeader = dtvccPacket.readByte().value;
  284. serviceNumber = extendedServiceBlockHeader & 0x3f;
  285. }
  286. // As per CEA-708-E, service number 0 is invalid, and should be ignored.
  287. if (serviceNumber != 0) {
  288. // If the service doesn't already exist, create it.
  289. if (!this.serviceNumberToService_.has(serviceNumber)) {
  290. const service = new shaka.cea.Cea708Service(serviceNumber);
  291. this.serviceNumberToService_.set(serviceNumber, service);
  292. }
  293. const service = this.serviceNumberToService_.get(serviceNumber);
  294. // Process all control codes.
  295. const startPos = dtvccPacket.getPosition();
  296. // Execute this loop `blockSize` times, to decode the control codes.
  297. while (dtvccPacket.getPosition() - startPos < blockSize) {
  298. const closedCaption = service.handleCea708ControlCode(dtvccPacket);
  299. if (closedCaption) {
  300. parsedClosedCaptions.push(closedCaption);
  301. }
  302. } // position < end of block
  303. } // serviceNumber != 0
  304. } // hasMoreData
  305. } catch (error) {
  306. if (error instanceof shaka.util.Error &&
  307. error.code === shaka.util.Error.Code.BUFFER_READ_OUT_OF_BOUNDS) {
  308. shaka.log.warnOnce('CEA708_INVALID_DATA',
  309. 'Buffer read out of bounds / invalid CEA-708 Data.');
  310. } else {
  311. // This is an unexpected error, and should be rethrown.
  312. throw error;
  313. }
  314. }
  315. return parsedClosedCaptions;
  316. }
  317. /**
  318. * Checks if a byte has odd parity (Odd number of 1s in binary).
  319. * @param {number} byte
  320. * @return {boolean} True if the byte has odd parity.
  321. * @private
  322. */
  323. isOddParity_(byte) {
  324. let parity = 0;
  325. while (byte) {
  326. parity ^= (byte & 1); // toggle parity if low bit is 1
  327. byte >>= 1; // shift away the low bit
  328. }
  329. return parity === 1;
  330. }
  331. };
  332. /**
  333. * itu_t_35_provider_code for ATSC user_data
  334. * @private @const {number}
  335. */
  336. shaka.cea.CeaDecoder.ATSC_PROVIDER_CODE = 0x0031;
  337. /**
  338. * When provider is ATSC user data, the ATSC_user_identifier code
  339. * for ATSC1_data is "GA94" (0x47413934)
  340. * @private @const {number}
  341. */
  342. shaka.cea.CeaDecoder.ATSC1_USER_IDENTIFIER = 0x47413934;
  343. /**
  344. * @private @const {number}
  345. */
  346. shaka.cea.CeaDecoder.NTSC_CC_FIELD_1 = 0;
  347. /**
  348. * @private @const {number}
  349. */
  350. shaka.cea.CeaDecoder.NTSC_CC_FIELD_2 = 1;
  351. /**
  352. * 0xB5 is USA's code (Rec. ITU-T T.35)
  353. * @private @const {number}
  354. */
  355. shaka.cea.CeaDecoder.USA_COUNTRY_CODE = 0xb5;
  356. /**
  357. * Caption packet min length
  358. * Country Code + ATSC_PROVIDER_CODE + ATSC_1_USER_IDENTIFIER + USER_DATA_TYPE
  359. * @private @const {number}
  360. */
  361. shaka.cea.CeaDecoder.MIN_LENGTH = 8;