Source: lib/media/closed_caption_parser.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.media.ClosedCaptionParser');
  7. goog.provide('shaka.media.IClosedCaptionParser');
  8. goog.require('shaka.cea.CeaDecoder');
  9. goog.require('shaka.cea.Mp4CeaParser');
  10. goog.require('shaka.util.BufferUtils');
  11. goog.requireType('shaka.cea.ICaptionDecoder');
  12. goog.requireType('shaka.cea.ICeaParser');
  13. /**
  14. * The IClosedCaptionParser defines the interface to provide all operations for
  15. * parsing the closed captions embedded in Dash videos streams.
  16. * TODO: Remove this interface and move method definitions
  17. * directly to ClosedCaptonParser.
  18. * @interface
  19. */
  20. shaka.media.IClosedCaptionParser = class {
  21. /**
  22. * Initialize the caption parser. This should be called only once.
  23. * @param {BufferSource} initSegment
  24. */
  25. init(initSegment) {}
  26. /**
  27. * Parses embedded CEA closed captions and interacts with the underlying
  28. * CaptionStream, and calls the callback function when there are closed
  29. * captions.
  30. *
  31. * @param {BufferSource} mediaFragment
  32. * @return {!Array<!shaka.cea.ICaptionDecoder.ClosedCaption>}
  33. * An array of parsed closed captions.
  34. */
  35. parseFrom(mediaFragment) {}
  36. /**
  37. * Resets the CaptionStream.
  38. */
  39. reset() {}
  40. };
  41. /**
  42. * Closed Caption Parser provides all operations for parsing the closed captions
  43. * embedded in Dash videos streams.
  44. *
  45. * @implements {shaka.media.IClosedCaptionParser}
  46. * @final
  47. */
  48. shaka.media.ClosedCaptionParser = class {
  49. /** */
  50. constructor() {
  51. /**
  52. * MP4 Parser to extract closed caption packets from H.264 video.
  53. * @private {!shaka.cea.ICeaParser}
  54. */
  55. this.ceaParser_ = new shaka.cea.Mp4CeaParser();
  56. /**
  57. * Decoder for decoding CEA-X08 data from closed caption packets.
  58. * @private {!shaka.cea.ICaptionDecoder}
  59. */
  60. this.ceaDecoder_ = new shaka.cea.CeaDecoder();
  61. }
  62. /**
  63. * @override
  64. */
  65. init(initSegment) {
  66. this.ceaParser_.init(initSegment);
  67. }
  68. /**
  69. * @override
  70. */
  71. parseFrom(mediaFragment) {
  72. // Parse the fragment.
  73. const captionPackets = this.ceaParser_.parse(mediaFragment);
  74. // Extract the caption packets for decoding.
  75. for (const captionPacket of captionPackets) {
  76. const uint8ArrayData =
  77. shaka.util.BufferUtils.toUint8(captionPacket.packet);
  78. if (uint8ArrayData.length > 0) {
  79. this.ceaDecoder_.extract(uint8ArrayData, captionPacket.pts);
  80. }
  81. }
  82. // Decode and return the parsed captions.
  83. return this.ceaDecoder_.decode();
  84. }
  85. /**
  86. * @override
  87. */
  88. reset() {
  89. this.ceaDecoder_.clear();
  90. }
  91. };