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