mux-mp4

muxmp4

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.gf.qytechs.cn/scripts/468821/1206201/mux-mp4.js

  1. (function(f){var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.muxjs = f()})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. /**
  3. * mux.js
  4. *
  5. * Copyright (c) Brightcove
  6. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  7. *
  8. * A stream-based aac to mp4 converter. This utility can be used to
  9. * deliver mp4s to a SourceBuffer on platforms that support native
  10. * Media Source Extensions.
  11. */
  12. 'use strict';
  13. var Stream = require(31);
  14. var aacUtils = require(2);
  15.  
  16. // Constants
  17. var AacStream;
  18.  
  19. /**
  20. * Splits an incoming stream of binary data into ADTS and ID3 Frames.
  21. */
  22.  
  23. AacStream = function() {
  24. var
  25. everything = new Uint8Array(),
  26. timeStamp = 0;
  27.  
  28. AacStream.prototype.init.call(this);
  29.  
  30. this.setTimestamp = function(timestamp) {
  31. timeStamp = timestamp;
  32. };
  33.  
  34. this.push = function(bytes) {
  35. var
  36. frameSize = 0,
  37. byteIndex = 0,
  38. bytesLeft,
  39. chunk,
  40. packet,
  41. tempLength;
  42.  
  43. // If there are bytes remaining from the last segment, prepend them to the
  44. // bytes that were pushed in
  45. if (everything.length) {
  46. tempLength = everything.length;
  47. everything = new Uint8Array(bytes.byteLength + tempLength);
  48. everything.set(everything.subarray(0, tempLength));
  49. everything.set(bytes, tempLength);
  50. } else {
  51. everything = bytes;
  52. }
  53.  
  54. while (everything.length - byteIndex >= 3) {
  55. if ((everything[byteIndex] === 'I'.charCodeAt(0)) &&
  56. (everything[byteIndex + 1] === 'D'.charCodeAt(0)) &&
  57. (everything[byteIndex + 2] === '3'.charCodeAt(0))) {
  58.  
  59. // Exit early because we don't have enough to parse
  60. // the ID3 tag header
  61. if (everything.length - byteIndex < 10) {
  62. break;
  63. }
  64.  
  65. // check framesize
  66. frameSize = aacUtils.parseId3TagSize(everything, byteIndex);
  67.  
  68. // Exit early if we don't have enough in the buffer
  69. // to emit a full packet
  70. // Add to byteIndex to support multiple ID3 tags in sequence
  71. if (byteIndex + frameSize > everything.length) {
  72. break;
  73. }
  74. chunk = {
  75. type: 'timed-metadata',
  76. data: everything.subarray(byteIndex, byteIndex + frameSize)
  77. };
  78. this.trigger('data', chunk);
  79. byteIndex += frameSize;
  80. continue;
  81. } else if (((everything[byteIndex] & 0xff) === 0xff) &&
  82. ((everything[byteIndex + 1] & 0xf0) === 0xf0)) {
  83.  
  84. // Exit early because we don't have enough to parse
  85. // the ADTS frame header
  86. if (everything.length - byteIndex < 7) {
  87. break;
  88. }
  89.  
  90. frameSize = aacUtils.parseAdtsSize(everything, byteIndex);
  91.  
  92. // Exit early if we don't have enough in the buffer
  93. // to emit a full packet
  94. if (byteIndex + frameSize > everything.length) {
  95. break;
  96. }
  97.  
  98. packet = {
  99. type: 'audio',
  100. data: everything.subarray(byteIndex, byteIndex + frameSize),
  101. pts: timeStamp,
  102. dts: timeStamp
  103. };
  104. this.trigger('data', packet);
  105. byteIndex += frameSize;
  106. continue;
  107. }
  108. byteIndex++;
  109. }
  110. bytesLeft = everything.length - byteIndex;
  111.  
  112. if (bytesLeft > 0) {
  113. everything = everything.subarray(byteIndex);
  114. } else {
  115. everything = new Uint8Array();
  116. }
  117. };
  118.  
  119. this.reset = function() {
  120. everything = new Uint8Array();
  121. this.trigger('reset');
  122. };
  123.  
  124. this.endTimeline = function() {
  125. everything = new Uint8Array();
  126. this.trigger('endedtimeline');
  127. };
  128. };
  129.  
  130. AacStream.prototype = new Stream();
  131.  
  132. module.exports = AacStream;
  133.  
  134. },{"2":2,"31":31}],2:[function(require,module,exports){
  135. /**
  136. * mux.js
  137. *
  138. * Copyright (c) Brightcove
  139. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  140. *
  141. * Utilities to detect basic properties and metadata about Aac data.
  142. */
  143. 'use strict';
  144.  
  145. var ADTS_SAMPLING_FREQUENCIES = [
  146. 96000,
  147. 88200,
  148. 64000,
  149. 48000,
  150. 44100,
  151. 32000,
  152. 24000,
  153. 22050,
  154. 16000,
  155. 12000,
  156. 11025,
  157. 8000,
  158. 7350
  159. ];
  160.  
  161. var parseId3TagSize = function(header, byteIndex) {
  162. var
  163. returnSize = (header[byteIndex + 6] << 21) |
  164. (header[byteIndex + 7] << 14) |
  165. (header[byteIndex + 8] << 7) |
  166. (header[byteIndex + 9]),
  167. flags = header[byteIndex + 5],
  168. footerPresent = (flags & 16) >> 4;
  169.  
  170. // if we get a negative returnSize clamp it to 0
  171. returnSize = returnSize >= 0 ? returnSize : 0;
  172.  
  173. if (footerPresent) {
  174. return returnSize + 20;
  175. }
  176. return returnSize + 10;
  177. };
  178.  
  179. var getId3Offset = function(data, offset) {
  180. if (data.length - offset < 10 ||
  181. data[offset] !== 'I'.charCodeAt(0) ||
  182. data[offset + 1] !== 'D'.charCodeAt(0) ||
  183. data[offset + 2] !== '3'.charCodeAt(0)) {
  184. return offset;
  185. }
  186.  
  187. offset += parseId3TagSize(data, offset);
  188.  
  189. return getId3Offset(data, offset);
  190. };
  191.  
  192.  
  193. // TODO: use vhs-utils
  194. var isLikelyAacData = function(data) {
  195. var offset = getId3Offset(data, 0);
  196.  
  197. return data.length >= offset + 2 &&
  198. (data[offset] & 0xFF) === 0xFF &&
  199. (data[offset + 1] & 0xF0) === 0xF0 &&
  200. // verify that the 2 layer bits are 0, aka this
  201. // is not mp3 data but aac data.
  202. (data[offset + 1] & 0x16) === 0x10;
  203. };
  204.  
  205. var parseSyncSafeInteger = function(data) {
  206. return (data[0] << 21) |
  207. (data[1] << 14) |
  208. (data[2] << 7) |
  209. (data[3]);
  210. };
  211.  
  212. // return a percent-encoded representation of the specified byte range
  213. // @see http://en.wikipedia.org/wiki/Percent-encoding
  214. var percentEncode = function(bytes, start, end) {
  215. var i, result = '';
  216. for (i = start; i < end; i++) {
  217. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  218. }
  219. return result;
  220. };
  221.  
  222. // return the string representation of the specified byte range,
  223. // interpreted as ISO-8859-1.
  224. var parseIso88591 = function(bytes, start, end) {
  225. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  226. };
  227.  
  228. var parseAdtsSize = function(header, byteIndex) {
  229. var
  230. lowThree = (header[byteIndex + 5] & 0xE0) >> 5,
  231. middle = header[byteIndex + 4] << 3,
  232. highTwo = header[byteIndex + 3] & 0x3 << 11;
  233.  
  234. return (highTwo | middle) | lowThree;
  235. };
  236.  
  237. var parseType = function(header, byteIndex) {
  238. if ((header[byteIndex] === 'I'.charCodeAt(0)) &&
  239. (header[byteIndex + 1] === 'D'.charCodeAt(0)) &&
  240. (header[byteIndex + 2] === '3'.charCodeAt(0))) {
  241. return 'timed-metadata';
  242. } else if ((header[byteIndex] & 0xff === 0xff) &&
  243. ((header[byteIndex + 1] & 0xf0) === 0xf0)) {
  244. return 'audio';
  245. }
  246. return null;
  247. };
  248.  
  249. var parseSampleRate = function(packet) {
  250. var i = 0;
  251.  
  252. while (i + 5 < packet.length) {
  253. if (packet[i] !== 0xFF || (packet[i + 1] & 0xF6) !== 0xF0) {
  254. // If a valid header was not found, jump one forward and attempt to
  255. // find a valid ADTS header starting at the next byte
  256. i++;
  257. continue;
  258. }
  259. return ADTS_SAMPLING_FREQUENCIES[(packet[i + 2] & 0x3c) >>> 2];
  260. }
  261.  
  262. return null;
  263. };
  264.  
  265. var parseAacTimestamp = function(packet) {
  266. var frameStart, frameSize, frame, frameHeader;
  267.  
  268. // find the start of the first frame and the end of the tag
  269. frameStart = 10;
  270. if (packet[5] & 0x40) {
  271. // advance the frame start past the extended header
  272. frameStart += 4; // header size field
  273. frameStart += parseSyncSafeInteger(packet.subarray(10, 14));
  274. }
  275.  
  276. // parse one or more ID3 frames
  277. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  278. do {
  279. // determine the number of bytes in this frame
  280. frameSize = parseSyncSafeInteger(packet.subarray(frameStart + 4, frameStart + 8));
  281. if (frameSize < 1) {
  282. return null;
  283. }
  284. frameHeader = String.fromCharCode(packet[frameStart],
  285. packet[frameStart + 1],
  286. packet[frameStart + 2],
  287. packet[frameStart + 3]);
  288.  
  289. if (frameHeader === 'PRIV') {
  290. frame = packet.subarray(frameStart + 10, frameStart + frameSize + 10);
  291.  
  292. for (var i = 0; i < frame.byteLength; i++) {
  293. if (frame[i] === 0) {
  294. var owner = parseIso88591(frame, 0, i);
  295. if (owner === 'com.apple.streaming.transportStreamTimestamp') {
  296. var d = frame.subarray(i + 1);
  297. var size = ((d[3] & 0x01) << 30) |
  298. (d[4] << 22) |
  299. (d[5] << 14) |
  300. (d[6] << 6) |
  301. (d[7] >>> 2);
  302. size *= 4;
  303. size += d[7] & 0x03;
  304.  
  305. return size;
  306. }
  307. break;
  308. }
  309. }
  310. }
  311.  
  312. frameStart += 10; // advance past the frame header
  313. frameStart += frameSize; // advance past the frame body
  314. } while (frameStart < packet.byteLength);
  315. return null;
  316. };
  317.  
  318. module.exports = {
  319. isLikelyAacData: isLikelyAacData,
  320. parseId3TagSize: parseId3TagSize,
  321. parseAdtsSize: parseAdtsSize,
  322. parseType: parseType,
  323. parseSampleRate: parseSampleRate,
  324. parseAacTimestamp: parseAacTimestamp
  325. };
  326.  
  327. },{}],3:[function(require,module,exports){
  328. /**
  329. * mux.js
  330. *
  331. * Copyright (c) Brightcove
  332. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  333. */
  334. 'use strict';
  335.  
  336. var Stream = require(31);
  337. var ONE_SECOND_IN_TS = require(29).ONE_SECOND_IN_TS;
  338.  
  339. var AdtsStream;
  340.  
  341. var
  342. ADTS_SAMPLING_FREQUENCIES = [
  343. 96000,
  344. 88200,
  345. 64000,
  346. 48000,
  347. 44100,
  348. 32000,
  349. 24000,
  350. 22050,
  351. 16000,
  352. 12000,
  353. 11025,
  354. 8000,
  355. 7350
  356. ];
  357.  
  358. /*
  359. * Accepts a ElementaryStream and emits data events with parsed
  360. * AAC Audio Frames of the individual packets. Input audio in ADTS
  361. * format is unpacked and re-emitted as AAC frames.
  362. *
  363. * @see http://wiki.multimedia.cx/index.php?title=ADTS
  364. * @see http://wiki.multimedia.cx/?title=Understanding_AAC
  365. */
  366. AdtsStream = function(handlePartialSegments) {
  367. var
  368. buffer,
  369. frameNum = 0;
  370.  
  371. AdtsStream.prototype.init.call(this);
  372.  
  373. this.push = function(packet) {
  374. var
  375. i = 0,
  376. frameLength,
  377. protectionSkipBytes,
  378. frameEnd,
  379. oldBuffer,
  380. sampleCount,
  381. adtsFrameDuration;
  382.  
  383. if (!handlePartialSegments) {
  384. frameNum = 0;
  385. }
  386.  
  387. if (packet.type !== 'audio') {
  388. // ignore non-audio data
  389. return;
  390. }
  391.  
  392. // Prepend any data in the buffer to the input data so that we can parse
  393. // aac frames the cross a PES packet boundary
  394. if (buffer) {
  395. oldBuffer = buffer;
  396. buffer = new Uint8Array(oldBuffer.byteLength + packet.data.byteLength);
  397. buffer.set(oldBuffer);
  398. buffer.set(packet.data, oldBuffer.byteLength);
  399. } else {
  400. buffer = packet.data;
  401. }
  402.  
  403. // unpack any ADTS frames which have been fully received
  404. // for details on the ADTS header, see http://wiki.multimedia.cx/index.php?title=ADTS
  405. while (i + 5 < buffer.length) {
  406.  
  407. // Look for the start of an ADTS header..
  408. if ((buffer[i] !== 0xFF) || (buffer[i + 1] & 0xF6) !== 0xF0) {
  409. // If a valid header was not found, jump one forward and attempt to
  410. // find a valid ADTS header starting at the next byte
  411. i++;
  412. continue;
  413. }
  414.  
  415. // The protection skip bit tells us if we have 2 bytes of CRC data at the
  416. // end of the ADTS header
  417. protectionSkipBytes = (~buffer[i + 1] & 0x01) * 2;
  418.  
  419. // Frame length is a 13 bit integer starting 16 bits from the
  420. // end of the sync sequence
  421. frameLength = ((buffer[i + 3] & 0x03) << 11) |
  422. (buffer[i + 4] << 3) |
  423. ((buffer[i + 5] & 0xe0) >> 5);
  424.  
  425. sampleCount = ((buffer[i + 6] & 0x03) + 1) * 1024;
  426. adtsFrameDuration = (sampleCount * ONE_SECOND_IN_TS) /
  427. ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2];
  428.  
  429. frameEnd = i + frameLength;
  430.  
  431. // If we don't have enough data to actually finish this ADTS frame, return
  432. // and wait for more data
  433. if (buffer.byteLength < frameEnd) {
  434. return;
  435. }
  436.  
  437. // Otherwise, deliver the complete AAC frame
  438. this.trigger('data', {
  439. pts: packet.pts + (frameNum * adtsFrameDuration),
  440. dts: packet.dts + (frameNum * adtsFrameDuration),
  441. sampleCount: sampleCount,
  442. audioobjecttype: ((buffer[i + 2] >>> 6) & 0x03) + 1,
  443. channelcount: ((buffer[i + 2] & 1) << 2) |
  444. ((buffer[i + 3] & 0xc0) >>> 6),
  445. samplerate: ADTS_SAMPLING_FREQUENCIES[(buffer[i + 2] & 0x3c) >>> 2],
  446. samplingfrequencyindex: (buffer[i + 2] & 0x3c) >>> 2,
  447. // assume ISO/IEC 14496-12 AudioSampleEntry default of 16
  448. samplesize: 16,
  449. data: buffer.subarray(i + 7 + protectionSkipBytes, frameEnd)
  450. });
  451.  
  452. frameNum++;
  453.  
  454. // If the buffer is empty, clear it and return
  455. if (buffer.byteLength === frameEnd) {
  456. buffer = undefined;
  457. return;
  458. }
  459.  
  460. // Remove the finished frame from the buffer and start the process again
  461. buffer = buffer.subarray(frameEnd);
  462. }
  463. };
  464.  
  465. this.flush = function() {
  466. frameNum = 0;
  467. this.trigger('done');
  468. };
  469.  
  470. this.reset = function() {
  471. buffer = void 0;
  472. this.trigger('reset');
  473. };
  474.  
  475. this.endTimeline = function() {
  476. buffer = void 0;
  477. this.trigger('endedtimeline');
  478. };
  479. };
  480.  
  481. AdtsStream.prototype = new Stream();
  482.  
  483. module.exports = AdtsStream;
  484.  
  485. },{"29":29,"31":31}],4:[function(require,module,exports){
  486. /**
  487. * mux.js
  488. *
  489. * Copyright (c) Brightcove
  490. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  491. */
  492. 'use strict';
  493.  
  494. var Stream = require(31);
  495. var ExpGolomb = require(30);
  496.  
  497. var H264Stream, NalByteStream;
  498. var PROFILES_WITH_OPTIONAL_SPS_DATA;
  499.  
  500. /**
  501. * Accepts a NAL unit byte stream and unpacks the embedded NAL units.
  502. */
  503. NalByteStream = function() {
  504. var
  505. syncPoint = 0,
  506. i,
  507. buffer;
  508. NalByteStream.prototype.init.call(this);
  509.  
  510. /*
  511. * Scans a byte stream and triggers a data event with the NAL units found.
  512. * @param {Object} data Event received from H264Stream
  513. * @param {Uint8Array} data.data The h264 byte stream to be scanned
  514. *
  515. * @see H264Stream.push
  516. */
  517. this.push = function(data) {
  518. var swapBuffer;
  519.  
  520. if (!buffer) {
  521. buffer = data.data;
  522. } else {
  523. swapBuffer = new Uint8Array(buffer.byteLength + data.data.byteLength);
  524. swapBuffer.set(buffer);
  525. swapBuffer.set(data.data, buffer.byteLength);
  526. buffer = swapBuffer;
  527. }
  528. var len = buffer.byteLength;
  529.  
  530. // Rec. ITU-T H.264, Annex B
  531. // scan for NAL unit boundaries
  532.  
  533. // a match looks like this:
  534. // 0 0 1 .. NAL .. 0 0 1
  535. // ^ sync point ^ i
  536. // or this:
  537. // 0 0 1 .. NAL .. 0 0 0
  538. // ^ sync point ^ i
  539.  
  540. // advance the sync point to a NAL start, if necessary
  541. for (; syncPoint < len - 3; syncPoint++) {
  542. if (buffer[syncPoint + 2] === 1) {
  543. // the sync point is properly aligned
  544. i = syncPoint + 5;
  545. break;
  546. }
  547. }
  548.  
  549. while (i < len) {
  550. // look at the current byte to determine if we've hit the end of
  551. // a NAL unit boundary
  552. switch (buffer[i]) {
  553. case 0:
  554. // skip past non-sync sequences
  555. if (buffer[i - 1] !== 0) {
  556. i += 2;
  557. break;
  558. } else if (buffer[i - 2] !== 0) {
  559. i++;
  560. break;
  561. }
  562.  
  563. // deliver the NAL unit if it isn't empty
  564. if (syncPoint + 3 !== i - 2) {
  565. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  566. }
  567.  
  568. // drop trailing zeroes
  569. do {
  570. i++;
  571. } while (buffer[i] !== 1 && i < len);
  572. syncPoint = i - 2;
  573. i += 3;
  574. break;
  575. case 1:
  576. // skip past non-sync sequences
  577. if (buffer[i - 1] !== 0 ||
  578. buffer[i - 2] !== 0) {
  579. i += 3;
  580. break;
  581. }
  582.  
  583. // deliver the NAL unit
  584. this.trigger('data', buffer.subarray(syncPoint + 3, i - 2));
  585. syncPoint = i - 2;
  586. i += 3;
  587. break;
  588. default:
  589. // the current byte isn't a one or zero, so it cannot be part
  590. // of a sync sequence
  591. i += 3;
  592. break;
  593. }
  594. }
  595. // filter out the NAL units that were delivered
  596. buffer = buffer.subarray(syncPoint);
  597. i -= syncPoint;
  598. syncPoint = 0;
  599. };
  600.  
  601. this.reset = function() {
  602. buffer = null;
  603. syncPoint = 0;
  604. this.trigger('reset');
  605. };
  606.  
  607. this.flush = function() {
  608. // deliver the last buffered NAL unit
  609. if (buffer && buffer.byteLength > 3) {
  610. this.trigger('data', buffer.subarray(syncPoint + 3));
  611. }
  612. // reset the stream state
  613. buffer = null;
  614. syncPoint = 0;
  615. this.trigger('done');
  616. };
  617.  
  618. this.endTimeline = function() {
  619. this.flush();
  620. this.trigger('endedtimeline');
  621. };
  622. };
  623. NalByteStream.prototype = new Stream();
  624.  
  625. // values of profile_idc that indicate additional fields are included in the SPS
  626. // see Recommendation ITU-T H.264 (4/2013),
  627. // 7.3.2.1.1 Sequence parameter set data syntax
  628. PROFILES_WITH_OPTIONAL_SPS_DATA = {
  629. 100: true,
  630. 110: true,
  631. 122: true,
  632. 244: true,
  633. 44: true,
  634. 83: true,
  635. 86: true,
  636. 118: true,
  637. 128: true,
  638. 138: true,
  639. 139: true,
  640. 134: true
  641. };
  642.  
  643. /**
  644. * Accepts input from a ElementaryStream and produces H.264 NAL unit data
  645. * events.
  646. */
  647. H264Stream = function() {
  648. var
  649. nalByteStream = new NalByteStream(),
  650. self,
  651. trackId,
  652. currentPts,
  653. currentDts,
  654.  
  655. discardEmulationPreventionBytes,
  656. readSequenceParameterSet,
  657. skipScalingList;
  658.  
  659. H264Stream.prototype.init.call(this);
  660. self = this;
  661.  
  662. /*
  663. * Pushes a packet from a stream onto the NalByteStream
  664. *
  665. * @param {Object} packet - A packet received from a stream
  666. * @param {Uint8Array} packet.data - The raw bytes of the packet
  667. * @param {Number} packet.dts - Decode timestamp of the packet
  668. * @param {Number} packet.pts - Presentation timestamp of the packet
  669. * @param {Number} packet.trackId - The id of the h264 track this packet came from
  670. * @param {('video'|'audio')} packet.type - The type of packet
  671. *
  672. */
  673. this.push = function(packet) {
  674. if (packet.type !== 'video') {
  675. return;
  676. }
  677. trackId = packet.trackId;
  678. currentPts = packet.pts;
  679. currentDts = packet.dts;
  680.  
  681. nalByteStream.push(packet);
  682. };
  683.  
  684. /*
  685. * Identify NAL unit types and pass on the NALU, trackId, presentation and decode timestamps
  686. * for the NALUs to the next stream component.
  687. * Also, preprocess caption and sequence parameter NALUs.
  688. *
  689. * @param {Uint8Array} data - A NAL unit identified by `NalByteStream.push`
  690. * @see NalByteStream.push
  691. */
  692. nalByteStream.on('data', function(data) {
  693. var
  694. event = {
  695. trackId: trackId,
  696. pts: currentPts,
  697. dts: currentDts,
  698. data: data
  699. };
  700.  
  701. switch (data[0] & 0x1f) {
  702. case 0x05:
  703. event.nalUnitType = 'slice_layer_without_partitioning_rbsp_idr';
  704. break;
  705. case 0x06:
  706. event.nalUnitType = 'sei_rbsp';
  707. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  708. break;
  709. case 0x07:
  710. event.nalUnitType = 'seq_parameter_set_rbsp';
  711. event.escapedRBSP = discardEmulationPreventionBytes(data.subarray(1));
  712. event.config = readSequenceParameterSet(event.escapedRBSP);
  713. break;
  714. case 0x08:
  715. event.nalUnitType = 'pic_parameter_set_rbsp';
  716. break;
  717. case 0x09:
  718. event.nalUnitType = 'access_unit_delimiter_rbsp';
  719. break;
  720.  
  721. default:
  722. break;
  723. }
  724. // This triggers data on the H264Stream
  725. self.trigger('data', event);
  726. });
  727. nalByteStream.on('done', function() {
  728. self.trigger('done');
  729. });
  730. nalByteStream.on('partialdone', function() {
  731. self.trigger('partialdone');
  732. });
  733. nalByteStream.on('reset', function() {
  734. self.trigger('reset');
  735. });
  736. nalByteStream.on('endedtimeline', function() {
  737. self.trigger('endedtimeline');
  738. });
  739.  
  740. this.flush = function() {
  741. nalByteStream.flush();
  742. };
  743.  
  744. this.partialFlush = function() {
  745. nalByteStream.partialFlush();
  746. };
  747.  
  748. this.reset = function() {
  749. nalByteStream.reset();
  750. };
  751.  
  752. this.endTimeline = function() {
  753. nalByteStream.endTimeline();
  754. };
  755.  
  756. /**
  757. * Advance the ExpGolomb decoder past a scaling list. The scaling
  758. * list is optionally transmitted as part of a sequence parameter
  759. * set and is not relevant to transmuxing.
  760. * @param count {number} the number of entries in this scaling list
  761. * @param expGolombDecoder {object} an ExpGolomb pointed to the
  762. * start of a scaling list
  763. * @see Recommendation ITU-T H.264, Section 7.3.2.1.1.1
  764. */
  765. skipScalingList = function(count, expGolombDecoder) {
  766. var
  767. lastScale = 8,
  768. nextScale = 8,
  769. j,
  770. deltaScale;
  771.  
  772. for (j = 0; j < count; j++) {
  773. if (nextScale !== 0) {
  774. deltaScale = expGolombDecoder.readExpGolomb();
  775. nextScale = (lastScale + deltaScale + 256) % 256;
  776. }
  777.  
  778. lastScale = (nextScale === 0) ? lastScale : nextScale;
  779. }
  780. };
  781.  
  782. /**
  783. * Expunge any "Emulation Prevention" bytes from a "Raw Byte
  784. * Sequence Payload"
  785. * @param data {Uint8Array} the bytes of a RBSP from a NAL
  786. * unit
  787. * @return {Uint8Array} the RBSP without any Emulation
  788. * Prevention Bytes
  789. */
  790. discardEmulationPreventionBytes = function(data) {
  791. var
  792. length = data.byteLength,
  793. emulationPreventionBytesPositions = [],
  794. i = 1,
  795. newLength, newData;
  796.  
  797. // Find all `Emulation Prevention Bytes`
  798. while (i < length - 2) {
  799. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  800. emulationPreventionBytesPositions.push(i + 2);
  801. i += 2;
  802. } else {
  803. i++;
  804. }
  805. }
  806.  
  807. // If no Emulation Prevention Bytes were found just return the original
  808. // array
  809. if (emulationPreventionBytesPositions.length === 0) {
  810. return data;
  811. }
  812.  
  813. // Create a new array to hold the NAL unit data
  814. newLength = length - emulationPreventionBytesPositions.length;
  815. newData = new Uint8Array(newLength);
  816. var sourceIndex = 0;
  817.  
  818. for (i = 0; i < newLength; sourceIndex++, i++) {
  819. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  820. // Skip this byte
  821. sourceIndex++;
  822. // Remove this position index
  823. emulationPreventionBytesPositions.shift();
  824. }
  825. newData[i] = data[sourceIndex];
  826. }
  827.  
  828. return newData;
  829. };
  830.  
  831. /**
  832. * Read a sequence parameter set and return some interesting video
  833. * properties. A sequence parameter set is the H264 metadata that
  834. * describes the properties of upcoming video frames.
  835. * @param data {Uint8Array} the bytes of a sequence parameter set
  836. * @return {object} an object with configuration parsed from the
  837. * sequence parameter set, including the dimensions of the
  838. * associated video frames.
  839. */
  840. readSequenceParameterSet = function(data) {
  841. var
  842. frameCropLeftOffset = 0,
  843. frameCropRightOffset = 0,
  844. frameCropTopOffset = 0,
  845. frameCropBottomOffset = 0,
  846. sarScale = 1,
  847. expGolombDecoder, profileIdc, levelIdc, profileCompatibility,
  848. chromaFormatIdc, picOrderCntType,
  849. numRefFramesInPicOrderCntCycle, picWidthInMbsMinus1,
  850. picHeightInMapUnitsMinus1,
  851. frameMbsOnlyFlag,
  852. scalingListCount,
  853. sarRatio,
  854. aspectRatioIdc,
  855. i;
  856.  
  857. expGolombDecoder = new ExpGolomb(data);
  858. profileIdc = expGolombDecoder.readUnsignedByte(); // profile_idc
  859. profileCompatibility = expGolombDecoder.readUnsignedByte(); // constraint_set[0-5]_flag
  860. levelIdc = expGolombDecoder.readUnsignedByte(); // level_idc u(8)
  861. expGolombDecoder.skipUnsignedExpGolomb(); // seq_parameter_set_id
  862.  
  863. // some profiles have more optional data we don't need
  864. if (PROFILES_WITH_OPTIONAL_SPS_DATA[profileIdc]) {
  865. chromaFormatIdc = expGolombDecoder.readUnsignedExpGolomb();
  866. if (chromaFormatIdc === 3) {
  867. expGolombDecoder.skipBits(1); // separate_colour_plane_flag
  868. }
  869. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_luma_minus8
  870. expGolombDecoder.skipUnsignedExpGolomb(); // bit_depth_chroma_minus8
  871. expGolombDecoder.skipBits(1); // qpprime_y_zero_transform_bypass_flag
  872. if (expGolombDecoder.readBoolean()) { // seq_scaling_matrix_present_flag
  873. scalingListCount = (chromaFormatIdc !== 3) ? 8 : 12;
  874. for (i = 0; i < scalingListCount; i++) {
  875. if (expGolombDecoder.readBoolean()) { // seq_scaling_list_present_flag[ i ]
  876. if (i < 6) {
  877. skipScalingList(16, expGolombDecoder);
  878. } else {
  879. skipScalingList(64, expGolombDecoder);
  880. }
  881. }
  882. }
  883. }
  884. }
  885.  
  886. expGolombDecoder.skipUnsignedExpGolomb(); // log2_max_frame_num_minus4
  887. picOrderCntType = expGolombDecoder.readUnsignedExpGolomb();
  888.  
  889. if (picOrderCntType === 0) {
  890. expGolombDecoder.readUnsignedExpGolomb(); // log2_max_pic_order_cnt_lsb_minus4
  891. } else if (picOrderCntType === 1) {
  892. expGolombDecoder.skipBits(1); // delta_pic_order_always_zero_flag
  893. expGolombDecoder.skipExpGolomb(); // offset_for_non_ref_pic
  894. expGolombDecoder.skipExpGolomb(); // offset_for_top_to_bottom_field
  895. numRefFramesInPicOrderCntCycle = expGolombDecoder.readUnsignedExpGolomb();
  896. for (i = 0; i < numRefFramesInPicOrderCntCycle; i++) {
  897. expGolombDecoder.skipExpGolomb(); // offset_for_ref_frame[ i ]
  898. }
  899. }
  900.  
  901. expGolombDecoder.skipUnsignedExpGolomb(); // max_num_ref_frames
  902. expGolombDecoder.skipBits(1); // gaps_in_frame_num_value_allowed_flag
  903.  
  904. picWidthInMbsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  905. picHeightInMapUnitsMinus1 = expGolombDecoder.readUnsignedExpGolomb();
  906.  
  907. frameMbsOnlyFlag = expGolombDecoder.readBits(1);
  908. if (frameMbsOnlyFlag === 0) {
  909. expGolombDecoder.skipBits(1); // mb_adaptive_frame_field_flag
  910. }
  911.  
  912. expGolombDecoder.skipBits(1); // direct_8x8_inference_flag
  913. if (expGolombDecoder.readBoolean()) { // frame_cropping_flag
  914. frameCropLeftOffset = expGolombDecoder.readUnsignedExpGolomb();
  915. frameCropRightOffset = expGolombDecoder.readUnsignedExpGolomb();
  916. frameCropTopOffset = expGolombDecoder.readUnsignedExpGolomb();
  917. frameCropBottomOffset = expGolombDecoder.readUnsignedExpGolomb();
  918. }
  919. if (expGolombDecoder.readBoolean()) {
  920. // vui_parameters_present_flag
  921. if (expGolombDecoder.readBoolean()) {
  922. // aspect_ratio_info_present_flag
  923. aspectRatioIdc = expGolombDecoder.readUnsignedByte();
  924. switch (aspectRatioIdc) {
  925. case 1: sarRatio = [1, 1]; break;
  926. case 2: sarRatio = [12, 11]; break;
  927. case 3: sarRatio = [10, 11]; break;
  928. case 4: sarRatio = [16, 11]; break;
  929. case 5: sarRatio = [40, 33]; break;
  930. case 6: sarRatio = [24, 11]; break;
  931. case 7: sarRatio = [20, 11]; break;
  932. case 8: sarRatio = [32, 11]; break;
  933. case 9: sarRatio = [80, 33]; break;
  934. case 10: sarRatio = [18, 11]; break;
  935. case 11: sarRatio = [15, 11]; break;
  936. case 12: sarRatio = [64, 33]; break;
  937. case 13: sarRatio = [160, 99]; break;
  938. case 14: sarRatio = [4, 3]; break;
  939. case 15: sarRatio = [3, 2]; break;
  940. case 16: sarRatio = [2, 1]; break;
  941. case 255: {
  942. sarRatio = [expGolombDecoder.readUnsignedByte() << 8 |
  943. expGolombDecoder.readUnsignedByte(),
  944. expGolombDecoder.readUnsignedByte() << 8 |
  945. expGolombDecoder.readUnsignedByte() ];
  946. break;
  947. }
  948. }
  949. if (sarRatio) {
  950. sarScale = sarRatio[0] / sarRatio[1];
  951. }
  952. }
  953. }
  954. return {
  955. profileIdc: profileIdc,
  956. levelIdc: levelIdc,
  957. profileCompatibility: profileCompatibility,
  958. width: Math.ceil((((picWidthInMbsMinus1 + 1) * 16) - frameCropLeftOffset * 2 - frameCropRightOffset * 2) * sarScale),
  959. height: ((2 - frameMbsOnlyFlag) * (picHeightInMapUnitsMinus1 + 1) * 16) - (frameCropTopOffset * 2) - (frameCropBottomOffset * 2),
  960. sarRatio: sarRatio
  961. };
  962. };
  963.  
  964. };
  965. H264Stream.prototype = new Stream();
  966.  
  967. module.exports = {
  968. H264Stream: H264Stream,
  969. NalByteStream: NalByteStream
  970. };
  971.  
  972. },{"30":30,"31":31}],5:[function(require,module,exports){
  973. // constants
  974. var AUDIO_PROPERTIES = [
  975. 'audioobjecttype',
  976. 'channelcount',
  977. 'samplerate',
  978. 'samplingfrequencyindex',
  979. 'samplesize'
  980. ];
  981.  
  982. module.exports = AUDIO_PROPERTIES;
  983.  
  984. },{}],6:[function(require,module,exports){
  985. var VIDEO_PROPERTIES = [
  986. 'width',
  987. 'height',
  988. 'profileIdc',
  989. 'levelIdc',
  990. 'profileCompatibility',
  991. 'sarRatio'
  992. ];
  993.  
  994.  
  995. module.exports = VIDEO_PROPERTIES;
  996.  
  997. },{}],7:[function(require,module,exports){
  998. /**
  999. * mux.js
  1000. *
  1001. * Copyright (c) Brightcove
  1002. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1003. */
  1004. var highPrefix = [33, 16, 5, 32, 164, 27];
  1005. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  1006. var zeroFill = function(count) {
  1007. var a = [];
  1008. while (count--) {
  1009. a.push(0);
  1010. }
  1011. return a;
  1012. };
  1013.  
  1014. var makeTable = function(metaTable) {
  1015. return Object.keys(metaTable).reduce(function(obj, key) {
  1016. obj[key] = new Uint8Array(metaTable[key].reduce(function(arr, part) {
  1017. return arr.concat(part);
  1018. }, []));
  1019. return obj;
  1020. }, {});
  1021. };
  1022.  
  1023.  
  1024. var silence;
  1025.  
  1026. module.exports = function() {
  1027. if (!silence) {
  1028. // Frames-of-silence to use for filling in missing AAC frames
  1029. var coneOfSilence = {
  1030. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  1031. 88200: [highPrefix, [231], zeroFill(170), [56]],
  1032. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  1033. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  1034. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  1035. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  1036. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  1037. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  1038. 12000: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 253, 128], zeroFill(259), [56]],
  1039. 11025: [lowPrefix, zeroFill(268), [3, 127, 248], zeroFill(268), [6, 255, 240], zeroFill(268), [13, 255, 224], zeroFill(268), [27, 255, 192], zeroFill(268), [55, 175, 128], zeroFill(108), [112]],
  1040. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  1041. };
  1042. silence = makeTable(coneOfSilence);
  1043. }
  1044. return silence;
  1045. };
  1046.  
  1047. },{}],8:[function(require,module,exports){
  1048. /**
  1049. * mux.js
  1050. *
  1051. * Copyright (c) Brightcove
  1052. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1053. *
  1054. * Reads in-band caption information from a video elementary
  1055. * stream. Captions must follow the CEA-708 standard for injection
  1056. * into an MPEG-2 transport streams.
  1057. * @see https://en.wikipedia.org/wiki/CEA-708
  1058. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  1059. */
  1060.  
  1061. 'use strict';
  1062.  
  1063. // -----------------
  1064. // Link To Transport
  1065. // -----------------
  1066.  
  1067. var Stream = require(31);
  1068. var cea708Parser = require(23);
  1069.  
  1070. var CaptionStream = function() {
  1071.  
  1072. CaptionStream.prototype.init.call(this);
  1073.  
  1074. this.captionPackets_ = [];
  1075.  
  1076. this.ccStreams_ = [
  1077. new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  1078. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  1079. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  1080. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  1081. ];
  1082.  
  1083. this.reset();
  1084.  
  1085. // forward data and done events from CCs to this CaptionStream
  1086. this.ccStreams_.forEach(function(cc) {
  1087. cc.on('data', this.trigger.bind(this, 'data'));
  1088. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  1089. cc.on('done', this.trigger.bind(this, 'done'));
  1090. }, this);
  1091.  
  1092. };
  1093.  
  1094. CaptionStream.prototype = new Stream();
  1095. CaptionStream.prototype.push = function(event) {
  1096. var sei, userData, newCaptionPackets;
  1097.  
  1098. // only examine SEI NALs
  1099. if (event.nalUnitType !== 'sei_rbsp') {
  1100. return;
  1101. }
  1102.  
  1103. // parse the sei
  1104. sei = cea708Parser.parseSei(event.escapedRBSP);
  1105.  
  1106. // ignore everything but user_data_registered_itu_t_t35
  1107. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  1108. return;
  1109. }
  1110.  
  1111. // parse out the user data payload
  1112. userData = cea708Parser.parseUserData(sei);
  1113.  
  1114. // ignore unrecognized userData
  1115. if (!userData) {
  1116. return;
  1117. }
  1118.  
  1119. // Sometimes, the same segment # will be downloaded twice. To stop the
  1120. // caption data from being processed twice, we track the latest dts we've
  1121. // received and ignore everything with a dts before that. However, since
  1122. // data for a specific dts can be split across packets on either side of
  1123. // a segment boundary, we need to make sure we *don't* ignore the packets
  1124. // from the *next* segment that have dts === this.latestDts_. By constantly
  1125. // tracking the number of packets received with dts === this.latestDts_, we
  1126. // know how many should be ignored once we start receiving duplicates.
  1127. if (event.dts < this.latestDts_) {
  1128. // We've started getting older data, so set the flag.
  1129. this.ignoreNextEqualDts_ = true;
  1130. return;
  1131. } else if ((event.dts === this.latestDts_) && (this.ignoreNextEqualDts_)) {
  1132. this.numSameDts_--;
  1133. if (!this.numSameDts_) {
  1134. // We've received the last duplicate packet, time to start processing again
  1135. this.ignoreNextEqualDts_ = false;
  1136. }
  1137. return;
  1138. }
  1139.  
  1140. // parse out CC data packets and save them for later
  1141. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  1142. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  1143. if (this.latestDts_ !== event.dts) {
  1144. this.numSameDts_ = 0;
  1145. }
  1146. this.numSameDts_++;
  1147. this.latestDts_ = event.dts;
  1148. };
  1149.  
  1150. CaptionStream.prototype.flushCCStreams = function(flushType) {
  1151. this.ccStreams_.forEach(function(cc) {
  1152. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  1153. }, this);
  1154. };
  1155.  
  1156. CaptionStream.prototype.flushStream = function(flushType) {
  1157. // make sure we actually parsed captions before proceeding
  1158. if (!this.captionPackets_.length) {
  1159. this.flushCCStreams(flushType);
  1160. return;
  1161. }
  1162.  
  1163. // In Chrome, the Array#sort function is not stable so add a
  1164. // presortIndex that we can use to ensure we get a stable-sort
  1165. this.captionPackets_.forEach(function(elem, idx) {
  1166. elem.presortIndex = idx;
  1167. });
  1168.  
  1169. // sort caption byte-pairs based on their PTS values
  1170. this.captionPackets_.sort(function(a, b) {
  1171. if (a.pts === b.pts) {
  1172. return a.presortIndex - b.presortIndex;
  1173. }
  1174. return a.pts - b.pts;
  1175. });
  1176.  
  1177. this.captionPackets_.forEach(function(packet) {
  1178. if (packet.type < 2) {
  1179. // Dispatch packet to the right Cea608Stream
  1180. this.dispatchCea608Packet(packet);
  1181. }
  1182. // this is where an 'else' would go for a dispatching packets
  1183. // to a theoretical Cea708Stream that handles SERVICEn data
  1184. }, this);
  1185.  
  1186. this.captionPackets_.length = 0;
  1187. this.flushCCStreams(flushType);
  1188. };
  1189.  
  1190. CaptionStream.prototype.flush = function() {
  1191. return this.flushStream('flush');
  1192. };
  1193.  
  1194. // Only called if handling partial data
  1195. CaptionStream.prototype.partialFlush = function() {
  1196. return this.flushStream('partialFlush');
  1197. };
  1198.  
  1199. CaptionStream.prototype.reset = function() {
  1200. this.latestDts_ = null;
  1201. this.ignoreNextEqualDts_ = false;
  1202. this.numSameDts_ = 0;
  1203. this.activeCea608Channel_ = [null, null];
  1204. this.ccStreams_.forEach(function(ccStream) {
  1205. ccStream.reset();
  1206. });
  1207. };
  1208.  
  1209. // From the CEA-608 spec:
  1210. /*
  1211. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  1212. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  1213. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  1214. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  1215. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  1216. * to switch to captioning or Text.
  1217. */
  1218. // With that in mind, we ignore any data between an XDS control code and a
  1219. // subsequent closed-captioning control code.
  1220. CaptionStream.prototype.dispatchCea608Packet = function(packet) {
  1221. // NOTE: packet.type is the CEA608 field
  1222. if (this.setsTextOrXDSActive(packet)) {
  1223. this.activeCea608Channel_[packet.type] = null;
  1224. } else if (this.setsChannel1Active(packet)) {
  1225. this.activeCea608Channel_[packet.type] = 0;
  1226. } else if (this.setsChannel2Active(packet)) {
  1227. this.activeCea608Channel_[packet.type] = 1;
  1228. }
  1229. if (this.activeCea608Channel_[packet.type] === null) {
  1230. // If we haven't received anything to set the active channel, or the
  1231. // packets are Text/XDS data, discard the data; we don't want jumbled
  1232. // captions
  1233. return;
  1234. }
  1235. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  1236. };
  1237.  
  1238. CaptionStream.prototype.setsChannel1Active = function(packet) {
  1239. return ((packet.ccData & 0x7800) === 0x1000);
  1240. };
  1241. CaptionStream.prototype.setsChannel2Active = function(packet) {
  1242. return ((packet.ccData & 0x7800) === 0x1800);
  1243. };
  1244. CaptionStream.prototype.setsTextOrXDSActive = function(packet) {
  1245. return ((packet.ccData & 0x7100) === 0x0100) ||
  1246. ((packet.ccData & 0x78fe) === 0x102a) ||
  1247. ((packet.ccData & 0x78fe) === 0x182a);
  1248. };
  1249.  
  1250. // ----------------------
  1251. // Session to Application
  1252. // ----------------------
  1253.  
  1254. // This hash maps non-ASCII, special, and extended character codes to their
  1255. // proper Unicode equivalent. The first keys that are only a single byte
  1256. // are the non-standard ASCII characters, which simply map the CEA608 byte
  1257. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  1258. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  1259. // can be performed regardless of the field and data channel on which the
  1260. // character code was received.
  1261. var CHARACTER_TRANSLATION = {
  1262. 0x2a: 0xe1, // 谩
  1263. 0x5c: 0xe9, // 茅
  1264. 0x5e: 0xed, // 铆
  1265. 0x5f: 0xf3, // 贸
  1266. 0x60: 0xfa, // 煤
  1267. 0x7b: 0xe7, // 莽
  1268. 0x7c: 0xf7, // 梅
  1269. 0x7d: 0xd1, // 脩
  1270. 0x7e: 0xf1, // 帽
  1271. 0x7f: 0x2588, // 鈻�
  1272. 0x0130: 0xae, // 庐
  1273. 0x0131: 0xb0, // 掳
  1274. 0x0132: 0xbd, // 陆
  1275. 0x0133: 0xbf, // 驴
  1276. 0x0134: 0x2122, // 鈩�
  1277. 0x0135: 0xa2, // 垄
  1278. 0x0136: 0xa3, // 拢
  1279. 0x0137: 0x266a, // 鈾�
  1280. 0x0138: 0xe0, // 脿
  1281. 0x0139: 0xa0, //
  1282. 0x013a: 0xe8, // 猫
  1283. 0x013b: 0xe2, // 芒
  1284. 0x013c: 0xea, // 锚
  1285. 0x013d: 0xee, // 卯
  1286. 0x013e: 0xf4, // 么
  1287. 0x013f: 0xfb, // 没
  1288. 0x0220: 0xc1, // 脕
  1289. 0x0221: 0xc9, // 脡
  1290. 0x0222: 0xd3, // 脫
  1291. 0x0223: 0xda, // 脷
  1292. 0x0224: 0xdc, // 脺
  1293. 0x0225: 0xfc, // 眉
  1294. 0x0226: 0x2018, // 鈥�
  1295. 0x0227: 0xa1, // 隆
  1296. 0x0228: 0x2a, // *
  1297. 0x0229: 0x27, // '
  1298. 0x022a: 0x2014, // 鈥�
  1299. 0x022b: 0xa9, // 漏
  1300. 0x022c: 0x2120, // 鈩�
  1301. 0x022d: 0x2022, // 鈥�
  1302. 0x022e: 0x201c, // 鈥�
  1303. 0x022f: 0x201d, // 鈥�
  1304. 0x0230: 0xc0, // 脌
  1305. 0x0231: 0xc2, // 脗
  1306. 0x0232: 0xc7, // 脟
  1307. 0x0233: 0xc8, // 脠
  1308. 0x0234: 0xca, // 脢
  1309. 0x0235: 0xcb, // 脣
  1310. 0x0236: 0xeb, // 毛
  1311. 0x0237: 0xce, // 脦
  1312. 0x0238: 0xcf, // 脧
  1313. 0x0239: 0xef, // 茂
  1314. 0x023a: 0xd4, // 脭
  1315. 0x023b: 0xd9, // 脵
  1316. 0x023c: 0xf9, // 霉
  1317. 0x023d: 0xdb, // 脹
  1318. 0x023e: 0xab, // 芦
  1319. 0x023f: 0xbb, // 禄
  1320. 0x0320: 0xc3, // 脙
  1321. 0x0321: 0xe3, // 茫
  1322. 0x0322: 0xcd, // 脥
  1323. 0x0323: 0xcc, // 脤
  1324. 0x0324: 0xec, // 矛
  1325. 0x0325: 0xd2, // 脪
  1326. 0x0326: 0xf2, // 貌
  1327. 0x0327: 0xd5, // 脮
  1328. 0x0328: 0xf5, // 玫
  1329. 0x0329: 0x7b, // {
  1330. 0x032a: 0x7d, // }
  1331. 0x032b: 0x5c, // \
  1332. 0x032c: 0x5e, // ^
  1333. 0x032d: 0x5f, // _
  1334. 0x032e: 0x7c, // |
  1335. 0x032f: 0x7e, // ~
  1336. 0x0330: 0xc4, // 脛
  1337. 0x0331: 0xe4, // 盲
  1338. 0x0332: 0xd6, // 脰
  1339. 0x0333: 0xf6, // 枚
  1340. 0x0334: 0xdf, // 脽
  1341. 0x0335: 0xa5, // 楼
  1342. 0x0336: 0xa4, // 陇
  1343. 0x0337: 0x2502, // 鈹�
  1344. 0x0338: 0xc5, // 脜
  1345. 0x0339: 0xe5, // 氓
  1346. 0x033a: 0xd8, // 脴
  1347. 0x033b: 0xf8, // 酶
  1348. 0x033c: 0x250c, // 鈹�
  1349. 0x033d: 0x2510, // 鈹�
  1350. 0x033e: 0x2514, // 鈹�
  1351. 0x033f: 0x2518 // 鈹�
  1352. };
  1353.  
  1354. var getCharFromCode = function(code) {
  1355. if (code === null) {
  1356. return '';
  1357. }
  1358. code = CHARACTER_TRANSLATION[code] || code;
  1359. return String.fromCharCode(code);
  1360. };
  1361.  
  1362. // the index of the last row in a CEA-608 display buffer
  1363. var BOTTOM_ROW = 14;
  1364.  
  1365. // This array is used for mapping PACs -> row #, since there's no way of
  1366. // getting it through bit logic.
  1367. var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620,
  1368. 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420];
  1369.  
  1370. // CEA-608 captions are rendered onto a 34x15 matrix of character
  1371. // cells. The "bottom" row is the last element in the outer array.
  1372. var createDisplayBuffer = function() {
  1373. var result = [], i = BOTTOM_ROW + 1;
  1374. while (i--) {
  1375. result.push('');
  1376. }
  1377. return result;
  1378. };
  1379.  
  1380. var Cea608Stream = function(field, dataChannel) {
  1381. Cea608Stream.prototype.init.call(this);
  1382.  
  1383. this.field_ = field || 0;
  1384. this.dataChannel_ = dataChannel || 0;
  1385.  
  1386. this.name_ = 'CC' + (((this.field_ << 1) | this.dataChannel_) + 1);
  1387.  
  1388. this.setConstants();
  1389. this.reset();
  1390.  
  1391. this.push = function(packet) {
  1392. var data, swap, char0, char1, text;
  1393. // remove the parity bits
  1394. data = packet.ccData & 0x7f7f;
  1395.  
  1396. // ignore duplicate control codes; the spec demands they're sent twice
  1397. if (data === this.lastControlCode_) {
  1398. this.lastControlCode_ = null;
  1399. return;
  1400. }
  1401.  
  1402. // Store control codes
  1403. if ((data & 0xf000) === 0x1000) {
  1404. this.lastControlCode_ = data;
  1405. } else if (data !== this.PADDING_) {
  1406. this.lastControlCode_ = null;
  1407. }
  1408.  
  1409. char0 = data >>> 8;
  1410. char1 = data & 0xff;
  1411.  
  1412. if (data === this.PADDING_) {
  1413. return;
  1414.  
  1415. } else if (data === this.RESUME_CAPTION_LOADING_) {
  1416. this.mode_ = 'popOn';
  1417.  
  1418. } else if (data === this.END_OF_CAPTION_) {
  1419. // If an EOC is received while in paint-on mode, the displayed caption
  1420. // text should be swapped to non-displayed memory as if it was a pop-on
  1421. // caption. Because of that, we should explicitly switch back to pop-on
  1422. // mode
  1423. this.mode_ = 'popOn';
  1424. this.clearFormatting(packet.pts);
  1425. // if a caption was being displayed, it's gone now
  1426. this.flushDisplayed(packet.pts);
  1427.  
  1428. // flip memory
  1429. swap = this.displayed_;
  1430. this.displayed_ = this.nonDisplayed_;
  1431. this.nonDisplayed_ = swap;
  1432.  
  1433. // start measuring the time to display the caption
  1434. this.startPts_ = packet.pts;
  1435.  
  1436. } else if (data === this.ROLL_UP_2_ROWS_) {
  1437. this.rollUpRows_ = 2;
  1438. this.setRollUp(packet.pts);
  1439. } else if (data === this.ROLL_UP_3_ROWS_) {
  1440. this.rollUpRows_ = 3;
  1441. this.setRollUp(packet.pts);
  1442. } else if (data === this.ROLL_UP_4_ROWS_) {
  1443. this.rollUpRows_ = 4;
  1444. this.setRollUp(packet.pts);
  1445. } else if (data === this.CARRIAGE_RETURN_) {
  1446. this.clearFormatting(packet.pts);
  1447. this.flushDisplayed(packet.pts);
  1448. this.shiftRowsUp_();
  1449. this.startPts_ = packet.pts;
  1450.  
  1451. } else if (data === this.BACKSPACE_) {
  1452. if (this.mode_ === 'popOn') {
  1453. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  1454. } else {
  1455. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  1456. }
  1457. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  1458. this.flushDisplayed(packet.pts);
  1459. this.displayed_ = createDisplayBuffer();
  1460. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  1461. this.nonDisplayed_ = createDisplayBuffer();
  1462.  
  1463. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  1464. if (this.mode_ !== 'paintOn') {
  1465. // NOTE: This should be removed when proper caption positioning is
  1466. // implemented
  1467. this.flushDisplayed(packet.pts);
  1468. this.displayed_ = createDisplayBuffer();
  1469. }
  1470. this.mode_ = 'paintOn';
  1471. this.startPts_ = packet.pts;
  1472.  
  1473. // Append special characters to caption text
  1474. } else if (this.isSpecialCharacter(char0, char1)) {
  1475. // Bitmask char0 so that we can apply character transformations
  1476. // regardless of field and data channel.
  1477. // Then byte-shift to the left and OR with char1 so we can pass the
  1478. // entire character code to `getCharFromCode`.
  1479. char0 = (char0 & 0x03) << 8;
  1480. text = getCharFromCode(char0 | char1);
  1481. this[this.mode_](packet.pts, text);
  1482. this.column_++;
  1483.  
  1484. // Append extended characters to caption text
  1485. } else if (this.isExtCharacter(char0, char1)) {
  1486. // Extended characters always follow their "non-extended" equivalents.
  1487. // IE if a "猫" is desired, you'll always receive "e猫"; non-compliant
  1488. // decoders are supposed to drop the "猫", while compliant decoders
  1489. // backspace the "e" and insert "猫".
  1490.  
  1491. // Delete the previous character
  1492. if (this.mode_ === 'popOn') {
  1493. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  1494. } else {
  1495. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  1496. }
  1497.  
  1498. // Bitmask char0 so that we can apply character transformations
  1499. // regardless of field and data channel.
  1500. // Then byte-shift to the left and OR with char1 so we can pass the
  1501. // entire character code to `getCharFromCode`.
  1502. char0 = (char0 & 0x03) << 8;
  1503. text = getCharFromCode(char0 | char1);
  1504. this[this.mode_](packet.pts, text);
  1505. this.column_++;
  1506.  
  1507. // Process mid-row codes
  1508. } else if (this.isMidRowCode(char0, char1)) {
  1509. // Attributes are not additive, so clear all formatting
  1510. this.clearFormatting(packet.pts);
  1511.  
  1512. // According to the standard, mid-row codes
  1513. // should be replaced with spaces, so add one now
  1514. this[this.mode_](packet.pts, ' ');
  1515. this.column_++;
  1516.  
  1517. if ((char1 & 0xe) === 0xe) {
  1518. this.addFormatting(packet.pts, ['i']);
  1519. }
  1520.  
  1521. if ((char1 & 0x1) === 0x1) {
  1522. this.addFormatting(packet.pts, ['u']);
  1523. }
  1524.  
  1525. // Detect offset control codes and adjust cursor
  1526. } else if (this.isOffsetControlCode(char0, char1)) {
  1527. // Cursor position is set by indent PAC (see below) in 4-column
  1528. // increments, with an additional offset code of 1-3 to reach any
  1529. // of the 32 columns specified by CEA-608. So all we need to do
  1530. // here is increment the column cursor by the given offset.
  1531. this.column_ += (char1 & 0x03);
  1532.  
  1533. // Detect PACs (Preamble Address Codes)
  1534. } else if (this.isPAC(char0, char1)) {
  1535.  
  1536. // There's no logic for PAC -> row mapping, so we have to just
  1537. // find the row code in an array and use its index :(
  1538. var row = ROWS.indexOf(data & 0x1f20);
  1539.  
  1540. // Configure the caption window if we're in roll-up mode
  1541. if (this.mode_ === 'rollUp') {
  1542. // This implies that the base row is incorrectly set.
  1543. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  1544. // of roll-up rows set.
  1545. if (row - this.rollUpRows_ + 1 < 0) {
  1546. row = this.rollUpRows_ - 1;
  1547. }
  1548.  
  1549. this.setRollUp(packet.pts, row);
  1550. }
  1551.  
  1552. if (row !== this.row_) {
  1553. // formatting is only persistent for current row
  1554. this.clearFormatting(packet.pts);
  1555. this.row_ = row;
  1556. }
  1557. // All PACs can apply underline, so detect and apply
  1558. // (All odd-numbered second bytes set underline)
  1559. if ((char1 & 0x1) && (this.formatting_.indexOf('u') === -1)) {
  1560. this.addFormatting(packet.pts, ['u']);
  1561. }
  1562.  
  1563. if ((data & 0x10) === 0x10) {
  1564. // We've got an indent level code. Each successive even number
  1565. // increments the column cursor by 4, so we can get the desired
  1566. // column position by bit-shifting to the right (to get n/2)
  1567. // and multiplying by 4.
  1568. this.column_ = ((data & 0xe) >> 1) * 4;
  1569. }
  1570.  
  1571. if (this.isColorPAC(char1)) {
  1572. // it's a color code, though we only support white, which
  1573. // can be either normal or italicized. white italics can be
  1574. // either 0x4e or 0x6e depending on the row, so we just
  1575. // bitwise-and with 0xe to see if italics should be turned on
  1576. if ((char1 & 0xe) === 0xe) {
  1577. this.addFormatting(packet.pts, ['i']);
  1578. }
  1579. }
  1580.  
  1581. // We have a normal character in char0, and possibly one in char1
  1582. } else if (this.isNormalChar(char0)) {
  1583. if (char1 === 0x00) {
  1584. char1 = null;
  1585. }
  1586. text = getCharFromCode(char0);
  1587. text += getCharFromCode(char1);
  1588. this[this.mode_](packet.pts, text);
  1589. this.column_ += text.length;
  1590.  
  1591. } // finish data processing
  1592.  
  1593. };
  1594. };
  1595. Cea608Stream.prototype = new Stream();
  1596. // Trigger a cue point that captures the current state of the
  1597. // display buffer
  1598. Cea608Stream.prototype.flushDisplayed = function(pts) {
  1599. var content = this.displayed_
  1600. // remove spaces from the start and end of the string
  1601. .map(function(row) {
  1602. try {
  1603. return row.trim();
  1604. } catch (e) {
  1605. // Ordinarily, this shouldn't happen. However, caption
  1606. // parsing errors should not throw exceptions and
  1607. // break playback.
  1608. // eslint-disable-next-line no-console
  1609. console.error('Skipping malformed caption.');
  1610. return '';
  1611. }
  1612. })
  1613. // combine all text rows to display in one cue
  1614. .join('\n')
  1615. // and remove blank rows from the start and end, but not the middle
  1616. .replace(/^\n+|\n+$/g, '');
  1617.  
  1618. if (content.length) {
  1619. this.trigger('data', {
  1620. startPts: this.startPts_,
  1621. endPts: pts,
  1622. text: content,
  1623. stream: this.name_
  1624. });
  1625. }
  1626. };
  1627.  
  1628. /**
  1629. * Zero out the data, used for startup and on seek
  1630. */
  1631. Cea608Stream.prototype.reset = function() {
  1632. this.mode_ = 'popOn';
  1633. // When in roll-up mode, the index of the last row that will
  1634. // actually display captions. If a caption is shifted to a row
  1635. // with a lower index than this, it is cleared from the display
  1636. // buffer
  1637. this.topRow_ = 0;
  1638. this.startPts_ = 0;
  1639. this.displayed_ = createDisplayBuffer();
  1640. this.nonDisplayed_ = createDisplayBuffer();
  1641. this.lastControlCode_ = null;
  1642.  
  1643. // Track row and column for proper line-breaking and spacing
  1644. this.column_ = 0;
  1645. this.row_ = BOTTOM_ROW;
  1646. this.rollUpRows_ = 2;
  1647.  
  1648. // This variable holds currently-applied formatting
  1649. this.formatting_ = [];
  1650. };
  1651.  
  1652. /**
  1653. * Sets up control code and related constants for this instance
  1654. */
  1655. Cea608Stream.prototype.setConstants = function() {
  1656. // The following attributes have these uses:
  1657. // ext_ : char0 for mid-row codes, and the base for extended
  1658. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  1659. // extended codes)
  1660. // control_: char0 for control codes, except byte-shifted to the
  1661. // left so that we can do this.control_ | CONTROL_CODE
  1662. // offset_: char0 for tab offset codes
  1663. //
  1664. // It's also worth noting that control codes, and _only_ control codes,
  1665. // differ between field 1 and field2. Field 2 control codes are always
  1666. // their field 1 value plus 1. That's why there's the "| field" on the
  1667. // control value.
  1668. if (this.dataChannel_ === 0) {
  1669. this.BASE_ = 0x10;
  1670. this.EXT_ = 0x11;
  1671. this.CONTROL_ = (0x14 | this.field_) << 8;
  1672. this.OFFSET_ = 0x17;
  1673. } else if (this.dataChannel_ === 1) {
  1674. this.BASE_ = 0x18;
  1675. this.EXT_ = 0x19;
  1676. this.CONTROL_ = (0x1c | this.field_) << 8;
  1677. this.OFFSET_ = 0x1f;
  1678. }
  1679.  
  1680. // Constants for the LSByte command codes recognized by Cea608Stream. This
  1681. // list is not exhaustive. For a more comprehensive listing and semantics see
  1682. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  1683. // Padding
  1684. this.PADDING_ = 0x0000;
  1685. // Pop-on Mode
  1686. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  1687. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f;
  1688. // Roll-up Mode
  1689. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  1690. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  1691. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  1692. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d;
  1693. // paint-on mode
  1694. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29;
  1695. // Erasure
  1696. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  1697. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  1698. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  1699. };
  1700.  
  1701. /**
  1702. * Detects if the 2-byte packet data is a special character
  1703. *
  1704. * Special characters have a second byte in the range 0x30 to 0x3f,
  1705. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  1706. * data channel 2).
  1707. *
  1708. * @param {Integer} char0 The first byte
  1709. * @param {Integer} char1 The second byte
  1710. * @return {Boolean} Whether the 2 bytes are an special character
  1711. */
  1712. Cea608Stream.prototype.isSpecialCharacter = function(char0, char1) {
  1713. return (char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f);
  1714. };
  1715.  
  1716. /**
  1717. * Detects if the 2-byte packet data is an extended character
  1718. *
  1719. * Extended characters have a second byte in the range 0x20 to 0x3f,
  1720. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  1721. * 0x1a or 0x1b (for data channel 2).
  1722. *
  1723. * @param {Integer} char0 The first byte
  1724. * @param {Integer} char1 The second byte
  1725. * @return {Boolean} Whether the 2 bytes are an extended character
  1726. */
  1727. Cea608Stream.prototype.isExtCharacter = function(char0, char1) {
  1728. return ((char0 === (this.EXT_ + 1) || char0 === (this.EXT_ + 2)) &&
  1729. (char1 >= 0x20 && char1 <= 0x3f));
  1730. };
  1731.  
  1732. /**
  1733. * Detects if the 2-byte packet is a mid-row code
  1734. *
  1735. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  1736. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  1737. * channel 2).
  1738. *
  1739. * @param {Integer} char0 The first byte
  1740. * @param {Integer} char1 The second byte
  1741. * @return {Boolean} Whether the 2 bytes are a mid-row code
  1742. */
  1743. Cea608Stream.prototype.isMidRowCode = function(char0, char1) {
  1744. return (char0 === this.EXT_ && (char1 >= 0x20 && char1 <= 0x2f));
  1745. };
  1746.  
  1747. /**
  1748. * Detects if the 2-byte packet is an offset control code
  1749. *
  1750. * Offset control codes have a second byte in the range 0x21 to 0x23,
  1751. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  1752. * data channel 2).
  1753. *
  1754. * @param {Integer} char0 The first byte
  1755. * @param {Integer} char1 The second byte
  1756. * @return {Boolean} Whether the 2 bytes are an offset control code
  1757. */
  1758. Cea608Stream.prototype.isOffsetControlCode = function(char0, char1) {
  1759. return (char0 === this.OFFSET_ && (char1 >= 0x21 && char1 <= 0x23));
  1760. };
  1761.  
  1762. /**
  1763. * Detects if the 2-byte packet is a Preamble Address Code
  1764. *
  1765. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  1766. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  1767. * range 0x40 to 0x7f.
  1768. *
  1769. * @param {Integer} char0 The first byte
  1770. * @param {Integer} char1 The second byte
  1771. * @return {Boolean} Whether the 2 bytes are a PAC
  1772. */
  1773. Cea608Stream.prototype.isPAC = function(char0, char1) {
  1774. return (char0 >= this.BASE_ && char0 < (this.BASE_ + 8) &&
  1775. (char1 >= 0x40 && char1 <= 0x7f));
  1776. };
  1777.  
  1778. /**
  1779. * Detects if a packet's second byte is in the range of a PAC color code
  1780. *
  1781. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  1782. * 0x60 to 0x6f.
  1783. *
  1784. * @param {Integer} char1 The second byte
  1785. * @return {Boolean} Whether the byte is a color PAC
  1786. */
  1787. Cea608Stream.prototype.isColorPAC = function(char1) {
  1788. return ((char1 >= 0x40 && char1 <= 0x4f) || (char1 >= 0x60 && char1 <= 0x7f));
  1789. };
  1790.  
  1791. /**
  1792. * Detects if a single byte is in the range of a normal character
  1793. *
  1794. * Normal text bytes are in the range 0x20 to 0x7f.
  1795. *
  1796. * @param {Integer} char The byte
  1797. * @return {Boolean} Whether the byte is a normal character
  1798. */
  1799. Cea608Stream.prototype.isNormalChar = function(char) {
  1800. return (char >= 0x20 && char <= 0x7f);
  1801. };
  1802.  
  1803. /**
  1804. * Configures roll-up
  1805. *
  1806. * @param {Integer} pts Current PTS
  1807. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  1808. * a new position
  1809. */
  1810. Cea608Stream.prototype.setRollUp = function(pts, newBaseRow) {
  1811. // Reset the base row to the bottom row when switching modes
  1812. if (this.mode_ !== 'rollUp') {
  1813. this.row_ = BOTTOM_ROW;
  1814. this.mode_ = 'rollUp';
  1815. // Spec says to wipe memories when switching to roll-up
  1816. this.flushDisplayed(pts);
  1817. this.nonDisplayed_ = createDisplayBuffer();
  1818. this.displayed_ = createDisplayBuffer();
  1819. }
  1820.  
  1821. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  1822. // move currently displayed captions (up or down) to the new base row
  1823. for (var i = 0; i < this.rollUpRows_; i++) {
  1824. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  1825. this.displayed_[this.row_ - i] = '';
  1826. }
  1827. }
  1828.  
  1829. if (newBaseRow === undefined) {
  1830. newBaseRow = this.row_;
  1831. }
  1832.  
  1833. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  1834. };
  1835.  
  1836. // Adds the opening HTML tag for the passed character to the caption text,
  1837. // and keeps track of it for later closing
  1838. Cea608Stream.prototype.addFormatting = function(pts, format) {
  1839. this.formatting_ = this.formatting_.concat(format);
  1840. var text = format.reduce(function(text, format) {
  1841. return text + '<' + format + '>';
  1842. }, '');
  1843. this[this.mode_](pts, text);
  1844. };
  1845.  
  1846. // Adds HTML closing tags for current formatting to caption text and
  1847. // clears remembered formatting
  1848. Cea608Stream.prototype.clearFormatting = function(pts) {
  1849. if (!this.formatting_.length) {
  1850. return;
  1851. }
  1852. var text = this.formatting_.reverse().reduce(function(text, format) {
  1853. return text + '</' + format + '>';
  1854. }, '');
  1855. this.formatting_ = [];
  1856. this[this.mode_](pts, text);
  1857. };
  1858.  
  1859. // Mode Implementations
  1860. Cea608Stream.prototype.popOn = function(pts, text) {
  1861. var baseRow = this.nonDisplayed_[this.row_];
  1862.  
  1863. // buffer characters
  1864. baseRow += text;
  1865. this.nonDisplayed_[this.row_] = baseRow;
  1866. };
  1867.  
  1868. Cea608Stream.prototype.rollUp = function(pts, text) {
  1869. var baseRow = this.displayed_[this.row_];
  1870.  
  1871. baseRow += text;
  1872. this.displayed_[this.row_] = baseRow;
  1873.  
  1874. };
  1875.  
  1876. Cea608Stream.prototype.shiftRowsUp_ = function() {
  1877. var i;
  1878. // clear out inactive rows
  1879. for (i = 0; i < this.topRow_; i++) {
  1880. this.displayed_[i] = '';
  1881. }
  1882. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  1883. this.displayed_[i] = '';
  1884. }
  1885. // shift displayed rows up
  1886. for (i = this.topRow_; i < this.row_; i++) {
  1887. this.displayed_[i] = this.displayed_[i + 1];
  1888. }
  1889. // clear out the bottom row
  1890. this.displayed_[this.row_] = '';
  1891. };
  1892.  
  1893. Cea608Stream.prototype.paintOn = function(pts, text) {
  1894. var baseRow = this.displayed_[this.row_];
  1895.  
  1896. baseRow += text;
  1897. this.displayed_[this.row_] = baseRow;
  1898. };
  1899.  
  1900. // exports
  1901. module.exports = {
  1902. CaptionStream: CaptionStream,
  1903. Cea608Stream: Cea608Stream
  1904. };
  1905.  
  1906. },{"23":23,"31":31}],9:[function(require,module,exports){
  1907. /**
  1908. * mux.js
  1909. *
  1910. * Copyright (c) Brightcove
  1911. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1912. *
  1913. * A stream-based mp2t to mp4 converter. This utility can be used to
  1914. * deliver mp4s to a SourceBuffer on platforms that support native
  1915. * Media Source Extensions.
  1916. */
  1917. 'use strict';
  1918. var Stream = require(31),
  1919. CaptionStream = require(8),
  1920. StreamTypes = require(11),
  1921. TimestampRolloverStream = require(12).TimestampRolloverStream;
  1922.  
  1923. // object types
  1924. var TransportPacketStream, TransportParseStream, ElementaryStream;
  1925.  
  1926. // constants
  1927. var
  1928. MP2T_PACKET_LENGTH = 188, // bytes
  1929. SYNC_BYTE = 0x47;
  1930.  
  1931. /**
  1932. * Splits an incoming stream of binary data into MPEG-2 Transport
  1933. * Stream packets.
  1934. */
  1935. TransportPacketStream = function() {
  1936. var
  1937. buffer = new Uint8Array(MP2T_PACKET_LENGTH),
  1938. bytesInBuffer = 0;
  1939.  
  1940. TransportPacketStream.prototype.init.call(this);
  1941.  
  1942. // Deliver new bytes to the stream.
  1943.  
  1944. /**
  1945. * Split a stream of data into M2TS packets
  1946. **/
  1947. this.push = function(bytes) {
  1948. var
  1949. startIndex = 0,
  1950. endIndex = MP2T_PACKET_LENGTH,
  1951. everything;
  1952.  
  1953. // If there are bytes remaining from the last segment, prepend them to the
  1954. // bytes that were pushed in
  1955. if (bytesInBuffer) {
  1956. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  1957. everything.set(buffer.subarray(0, bytesInBuffer));
  1958. everything.set(bytes, bytesInBuffer);
  1959. bytesInBuffer = 0;
  1960. } else {
  1961. everything = bytes;
  1962. }
  1963.  
  1964. // While we have enough data for a packet
  1965. while (endIndex < everything.byteLength) {
  1966. // Look for a pair of start and end sync bytes in the data..
  1967. if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
  1968. // We found a packet so emit it and jump one whole packet forward in
  1969. // the stream
  1970. this.trigger('data', everything.subarray(startIndex, endIndex));
  1971. startIndex += MP2T_PACKET_LENGTH;
  1972. endIndex += MP2T_PACKET_LENGTH;
  1973. continue;
  1974. }
  1975. // If we get here, we have somehow become de-synchronized and we need to step
  1976. // forward one byte at a time until we find a pair of sync bytes that denote
  1977. // a packet
  1978. startIndex++;
  1979. endIndex++;
  1980. }
  1981.  
  1982. // If there was some data left over at the end of the segment that couldn't
  1983. // possibly be a whole packet, keep it because it might be the start of a packet
  1984. // that continues in the next segment
  1985. if (startIndex < everything.byteLength) {
  1986. buffer.set(everything.subarray(startIndex), 0);
  1987. bytesInBuffer = everything.byteLength - startIndex;
  1988. }
  1989. };
  1990.  
  1991. /**
  1992. * Passes identified M2TS packets to the TransportParseStream to be parsed
  1993. **/
  1994. this.flush = function() {
  1995. // If the buffer contains a whole packet when we are being flushed, emit it
  1996. // and empty the buffer. Otherwise hold onto the data because it may be
  1997. // important for decoding the next segment
  1998. if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
  1999. this.trigger('data', buffer);
  2000. bytesInBuffer = 0;
  2001. }
  2002. this.trigger('done');
  2003. };
  2004.  
  2005. this.endTimeline = function() {
  2006. this.flush();
  2007. this.trigger('endedtimeline');
  2008. };
  2009.  
  2010. this.reset = function() {
  2011. bytesInBuffer = 0;
  2012. this.trigger('reset');
  2013. };
  2014. };
  2015. TransportPacketStream.prototype = new Stream();
  2016.  
  2017. /**
  2018. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  2019. * forms of the individual transport stream packets.
  2020. */
  2021. TransportParseStream = function() {
  2022. var parsePsi, parsePat, parsePmt, self;
  2023. TransportParseStream.prototype.init.call(this);
  2024. self = this;
  2025.  
  2026. this.packetsWaitingForPmt = [];
  2027. this.programMapTable = undefined;
  2028.  
  2029. parsePsi = function(payload, psi) {
  2030. var offset = 0;
  2031.  
  2032. // PSI packets may be split into multiple sections and those
  2033. // sections may be split into multiple packets. If a PSI
  2034. // section starts in this packet, the payload_unit_start_indicator
  2035. // will be true and the first byte of the payload will indicate
  2036. // the offset from the current position to the start of the
  2037. // section.
  2038. if (psi.payloadUnitStartIndicator) {
  2039. offset += payload[offset] + 1;
  2040. }
  2041.  
  2042. if (psi.type === 'pat') {
  2043. parsePat(payload.subarray(offset), psi);
  2044. } else {
  2045. parsePmt(payload.subarray(offset), psi);
  2046. }
  2047. };
  2048.  
  2049. parsePat = function(payload, pat) {
  2050. pat.section_number = payload[7]; // eslint-disable-line camelcase
  2051. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  2052.  
  2053. // skip the PSI header and parse the first PMT entry
  2054. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  2055. pat.pmtPid = self.pmtPid;
  2056. };
  2057.  
  2058. /**
  2059. * Parse out the relevant fields of a Program Map Table (PMT).
  2060. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  2061. * packet. The first byte in this array should be the table_id
  2062. * field.
  2063. * @param pmt {object} the object that should be decorated with
  2064. * fields parsed from the PMT.
  2065. */
  2066. parsePmt = function(payload, pmt) {
  2067. var sectionLength, tableEnd, programInfoLength, offset;
  2068.  
  2069. // PMTs can be sent ahead of the time when they should actually
  2070. // take effect. We don't believe this should ever be the case
  2071. // for HLS but we'll ignore "forward" PMT declarations if we see
  2072. // them. Future PMT declarations have the current_next_indicator
  2073. // set to zero.
  2074. if (!(payload[5] & 0x01)) {
  2075. return;
  2076. }
  2077.  
  2078. // overwrite any existing program map table
  2079. self.programMapTable = {
  2080. video: null,
  2081. audio: null,
  2082. 'timed-metadata': {}
  2083. };
  2084.  
  2085. // the mapping table ends at the end of the current section
  2086. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  2087. tableEnd = 3 + sectionLength - 4;
  2088.  
  2089. // to determine where the table is, we have to figure out how
  2090. // long the program info descriptors are
  2091. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11];
  2092.  
  2093. // advance the offset to the first entry in the mapping table
  2094. offset = 12 + programInfoLength;
  2095. while (offset < tableEnd) {
  2096. var streamType = payload[offset];
  2097. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2];
  2098.  
  2099. // only map a single elementary_pid for audio and video stream types
  2100. // TODO: should this be done for metadata too? for now maintain behavior of
  2101. // multiple metadata streams
  2102. if (streamType === StreamTypes.H264_STREAM_TYPE &&
  2103. self.programMapTable.video === null) {
  2104. self.programMapTable.video = pid;
  2105. } else if (streamType === StreamTypes.ADTS_STREAM_TYPE &&
  2106. self.programMapTable.audio === null) {
  2107. self.programMapTable.audio = pid;
  2108. } else if (streamType === StreamTypes.METADATA_STREAM_TYPE) {
  2109. // map pid to stream type for metadata streams
  2110. self.programMapTable['timed-metadata'][pid] = streamType;
  2111. }
  2112.  
  2113. // move to the next table entry
  2114. // skip past the elementary stream descriptors, if present
  2115. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  2116. }
  2117.  
  2118. // record the map on the packet as well
  2119. pmt.programMapTable = self.programMapTable;
  2120. };
  2121.  
  2122. /**
  2123. * Deliver a new MP2T packet to the next stream in the pipeline.
  2124. */
  2125. this.push = function(packet) {
  2126. var
  2127. result = {},
  2128. offset = 4;
  2129.  
  2130. result.payloadUnitStartIndicator = !!(packet[1] & 0x40);
  2131.  
  2132. // pid is a 13-bit field starting at the last bit of packet[1]
  2133. result.pid = packet[1] & 0x1f;
  2134. result.pid <<= 8;
  2135. result.pid |= packet[2];
  2136.  
  2137. // if an adaption field is present, its length is specified by the
  2138. // fifth byte of the TS packet header. The adaptation field is
  2139. // used to add stuffing to PES packets that don't fill a complete
  2140. // TS packet, and to specify some forms of timing and control data
  2141. // that we do not currently use.
  2142. if (((packet[3] & 0x30) >>> 4) > 0x01) {
  2143. offset += packet[offset] + 1;
  2144. }
  2145.  
  2146. // parse the rest of the packet based on the type
  2147. if (result.pid === 0) {
  2148. result.type = 'pat';
  2149. parsePsi(packet.subarray(offset), result);
  2150. this.trigger('data', result);
  2151. } else if (result.pid === this.pmtPid) {
  2152. result.type = 'pmt';
  2153. parsePsi(packet.subarray(offset), result);
  2154. this.trigger('data', result);
  2155.  
  2156. // if there are any packets waiting for a PMT to be found, process them now
  2157. while (this.packetsWaitingForPmt.length) {
  2158. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  2159. }
  2160. } else if (this.programMapTable === undefined) {
  2161. // When we have not seen a PMT yet, defer further processing of
  2162. // PES packets until one has been parsed
  2163. this.packetsWaitingForPmt.push([packet, offset, result]);
  2164. } else {
  2165. this.processPes_(packet, offset, result);
  2166. }
  2167. };
  2168.  
  2169. this.processPes_ = function(packet, offset, result) {
  2170. // set the appropriate stream type
  2171. if (result.pid === this.programMapTable.video) {
  2172. result.streamType = StreamTypes.H264_STREAM_TYPE;
  2173. } else if (result.pid === this.programMapTable.audio) {
  2174. result.streamType = StreamTypes.ADTS_STREAM_TYPE;
  2175. } else {
  2176. // if not video or audio, it is timed-metadata or unknown
  2177. // if unknown, streamType will be undefined
  2178. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  2179. }
  2180.  
  2181. result.type = 'pes';
  2182. result.data = packet.subarray(offset);
  2183. this.trigger('data', result);
  2184. };
  2185. };
  2186. TransportParseStream.prototype = new Stream();
  2187. TransportParseStream.STREAM_TYPES = {
  2188. h264: 0x1b,
  2189. adts: 0x0f
  2190. };
  2191.  
  2192. /**
  2193. * Reconsistutes program elementary stream (PES) packets from parsed
  2194. * transport stream packets. That is, if you pipe an
  2195. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  2196. * events will be events which capture the bytes for individual PES
  2197. * packets plus relevant metadata that has been extracted from the
  2198. * container.
  2199. */
  2200. ElementaryStream = function() {
  2201. var
  2202. self = this,
  2203. // PES packet fragments
  2204. video = {
  2205. data: [],
  2206. size: 0
  2207. },
  2208. audio = {
  2209. data: [],
  2210. size: 0
  2211. },
  2212. timedMetadata = {
  2213. data: [],
  2214. size: 0
  2215. },
  2216. programMapTable,
  2217. parsePes = function(payload, pes) {
  2218. var ptsDtsFlags;
  2219.  
  2220. // get the packet length, this will be 0 for video
  2221. pes.packetLength = 6 + ((payload[4] << 8) | payload[5]);
  2222.  
  2223. // find out if this packets starts a new keyframe
  2224. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0;
  2225. // PES packets may be annotated with a PTS value, or a PTS value
  2226. // and a DTS value. Determine what combination of values is
  2227. // available to work with.
  2228. ptsDtsFlags = payload[7];
  2229.  
  2230. // PTS and DTS are normally stored as a 33-bit number. Javascript
  2231. // performs all bitwise operations on 32-bit integers but javascript
  2232. // supports a much greater range (52-bits) of integer using standard
  2233. // mathematical operations.
  2234. // We construct a 31-bit value using bitwise operators over the 31
  2235. // most significant bits and then multiply by 4 (equal to a left-shift
  2236. // of 2) before we add the final 2 least significant bits of the
  2237. // timestamp (equal to an OR.)
  2238. if (ptsDtsFlags & 0xC0) {
  2239. // the PTS and DTS are not written out directly. For information
  2240. // on how they are encoded, see
  2241. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  2242. pes.pts = (payload[9] & 0x0E) << 27 |
  2243. (payload[10] & 0xFF) << 20 |
  2244. (payload[11] & 0xFE) << 12 |
  2245. (payload[12] & 0xFF) << 5 |
  2246. (payload[13] & 0xFE) >>> 3;
  2247. pes.pts *= 4; // Left shift by 2
  2248. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  2249. pes.dts = pes.pts;
  2250. if (ptsDtsFlags & 0x40) {
  2251. pes.dts = (payload[14] & 0x0E) << 27 |
  2252. (payload[15] & 0xFF) << 20 |
  2253. (payload[16] & 0xFE) << 12 |
  2254. (payload[17] & 0xFF) << 5 |
  2255. (payload[18] & 0xFE) >>> 3;
  2256. pes.dts *= 4; // Left shift by 2
  2257. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  2258. }
  2259. }
  2260. // the data section starts immediately after the PES header.
  2261. // pes_header_data_length specifies the number of header bytes
  2262. // that follow the last byte of the field.
  2263. pes.data = payload.subarray(9 + payload[8]);
  2264. },
  2265. /**
  2266. * Pass completely parsed PES packets to the next stream in the pipeline
  2267. **/
  2268. flushStream = function(stream, type, forceFlush) {
  2269. var
  2270. packetData = new Uint8Array(stream.size),
  2271. event = {
  2272. type: type
  2273. },
  2274. i = 0,
  2275. offset = 0,
  2276. packetFlushable = false,
  2277. fragment;
  2278.  
  2279. // do nothing if there is not enough buffered data for a complete
  2280. // PES header
  2281. if (!stream.data.length || stream.size < 9) {
  2282. return;
  2283. }
  2284. event.trackId = stream.data[0].pid;
  2285.  
  2286. // reassemble the packet
  2287. for (i = 0; i < stream.data.length; i++) {
  2288. fragment = stream.data[i];
  2289.  
  2290. packetData.set(fragment.data, offset);
  2291. offset += fragment.data.byteLength;
  2292. }
  2293.  
  2294. // parse assembled packet's PES header
  2295. parsePes(packetData, event);
  2296.  
  2297. // non-video PES packets MUST have a non-zero PES_packet_length
  2298. // check that there is enough stream data to fill the packet
  2299. packetFlushable = type === 'video' || event.packetLength <= stream.size;
  2300.  
  2301. // flush pending packets if the conditions are right
  2302. if (forceFlush || packetFlushable) {
  2303. stream.size = 0;
  2304. stream.data.length = 0;
  2305. }
  2306.  
  2307. // only emit packets that are complete. this is to avoid assembling
  2308. // incomplete PES packets due to poor segmentation
  2309. if (packetFlushable) {
  2310. self.trigger('data', event);
  2311. }
  2312. };
  2313.  
  2314. ElementaryStream.prototype.init.call(this);
  2315.  
  2316. /**
  2317. * Identifies M2TS packet types and parses PES packets using metadata
  2318. * parsed from the PMT
  2319. **/
  2320. this.push = function(data) {
  2321. ({
  2322. pat: function() {
  2323. // we have to wait for the PMT to arrive as well before we
  2324. // have any meaningful metadata
  2325. },
  2326. pes: function() {
  2327. var stream, streamType;
  2328.  
  2329. switch (data.streamType) {
  2330. case StreamTypes.H264_STREAM_TYPE:
  2331. stream = video;
  2332. streamType = 'video';
  2333. break;
  2334. case StreamTypes.ADTS_STREAM_TYPE:
  2335. stream = audio;
  2336. streamType = 'audio';
  2337. break;
  2338. case StreamTypes.METADATA_STREAM_TYPE:
  2339. stream = timedMetadata;
  2340. streamType = 'timed-metadata';
  2341. break;
  2342. default:
  2343. // ignore unknown stream types
  2344. return;
  2345. }
  2346.  
  2347. // if a new packet is starting, we can flush the completed
  2348. // packet
  2349. if (data.payloadUnitStartIndicator) {
  2350. flushStream(stream, streamType, true);
  2351. }
  2352.  
  2353. // buffer this fragment until we are sure we've received the
  2354. // complete payload
  2355. stream.data.push(data);
  2356. stream.size += data.data.byteLength;
  2357. },
  2358. pmt: function() {
  2359. var
  2360. event = {
  2361. type: 'metadata',
  2362. tracks: []
  2363. };
  2364.  
  2365. programMapTable = data.programMapTable;
  2366.  
  2367. // translate audio and video streams to tracks
  2368. if (programMapTable.video !== null) {
  2369. event.tracks.push({
  2370. timelineStartInfo: {
  2371. baseMediaDecodeTime: 0
  2372. },
  2373. id: +programMapTable.video,
  2374. codec: 'avc',
  2375. type: 'video'
  2376. });
  2377. }
  2378. if (programMapTable.audio !== null) {
  2379. event.tracks.push({
  2380. timelineStartInfo: {
  2381. baseMediaDecodeTime: 0
  2382. },
  2383. id: +programMapTable.audio,
  2384. codec: 'adts',
  2385. type: 'audio'
  2386. });
  2387. }
  2388.  
  2389. self.trigger('data', event);
  2390. }
  2391. })[data.type]();
  2392. };
  2393.  
  2394. this.reset = function() {
  2395. video.size = 0;
  2396. video.data.length = 0;
  2397. audio.size = 0;
  2398. audio.data.length = 0;
  2399. this.trigger('reset');
  2400. };
  2401.  
  2402. /**
  2403. * Flush any remaining input. Video PES packets may be of variable
  2404. * length. Normally, the start of a new video packet can trigger the
  2405. * finalization of the previous packet. That is not possible if no
  2406. * more video is forthcoming, however. In that case, some other
  2407. * mechanism (like the end of the file) has to be employed. When it is
  2408. * clear that no additional data is forthcoming, calling this method
  2409. * will flush the buffered packets.
  2410. */
  2411. this.flushStreams_ = function() {
  2412. // !!THIS ORDER IS IMPORTANT!!
  2413. // video first then audio
  2414. flushStream(video, 'video');
  2415. flushStream(audio, 'audio');
  2416. flushStream(timedMetadata, 'timed-metadata');
  2417. };
  2418.  
  2419. this.flush = function() {
  2420. this.flushStreams_();
  2421. this.trigger('done');
  2422. };
  2423. };
  2424. ElementaryStream.prototype = new Stream();
  2425.  
  2426. var m2ts = {
  2427. PAT_PID: 0x0000,
  2428. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
  2429. TransportPacketStream: TransportPacketStream,
  2430. TransportParseStream: TransportParseStream,
  2431. ElementaryStream: ElementaryStream,
  2432. TimestampRolloverStream: TimestampRolloverStream,
  2433. CaptionStream: CaptionStream.CaptionStream,
  2434. Cea608Stream: CaptionStream.Cea608Stream,
  2435. MetadataStream: require(10)
  2436. };
  2437.  
  2438. for (var type in StreamTypes) {
  2439. if (StreamTypes.hasOwnProperty(type)) {
  2440. m2ts[type] = StreamTypes[type];
  2441. }
  2442. }
  2443.  
  2444. module.exports = m2ts;
  2445.  
  2446. },{"10":10,"11":11,"12":12,"31":31,"8":8}],10:[function(require,module,exports){
  2447. /**
  2448. * mux.js
  2449. *
  2450. * Copyright (c) Brightcove
  2451. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2452. *
  2453. * Accepts program elementary stream (PES) data events and parses out
  2454. * ID3 metadata from them, if present.
  2455. * @see http://id3.org/id3v2.3.0
  2456. */
  2457. 'use strict';
  2458. var
  2459. Stream = require(31),
  2460. StreamTypes = require(11),
  2461. // return a percent-encoded representation of the specified byte range
  2462. // @see http://en.wikipedia.org/wiki/Percent-encoding
  2463. percentEncode = function(bytes, start, end) {
  2464. var i, result = '';
  2465. for (i = start; i < end; i++) {
  2466. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  2467. }
  2468. return result;
  2469. },
  2470. // return the string representation of the specified byte range,
  2471. // interpreted as UTf-8.
  2472. parseUtf8 = function(bytes, start, end) {
  2473. return decodeURIComponent(percentEncode(bytes, start, end));
  2474. },
  2475. // return the string representation of the specified byte range,
  2476. // interpreted as ISO-8859-1.
  2477. parseIso88591 = function(bytes, start, end) {
  2478. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  2479. },
  2480. parseSyncSafeInteger = function(data) {
  2481. return (data[0] << 21) |
  2482. (data[1] << 14) |
  2483. (data[2] << 7) |
  2484. (data[3]);
  2485. },
  2486. tagParsers = {
  2487. TXXX: function(tag) {
  2488. var i;
  2489. if (tag.data[0] !== 3) {
  2490. // ignore frames with unrecognized character encodings
  2491. return;
  2492. }
  2493.  
  2494. for (i = 1; i < tag.data.length; i++) {
  2495. if (tag.data[i] === 0) {
  2496. // parse the text fields
  2497. tag.description = parseUtf8(tag.data, 1, i);
  2498. // do not include the null terminator in the tag value
  2499. tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
  2500. break;
  2501. }
  2502. }
  2503. tag.data = tag.value;
  2504. },
  2505. WXXX: function(tag) {
  2506. var i;
  2507. if (tag.data[0] !== 3) {
  2508. // ignore frames with unrecognized character encodings
  2509. return;
  2510. }
  2511.  
  2512. for (i = 1; i < tag.data.length; i++) {
  2513. if (tag.data[i] === 0) {
  2514. // parse the description and URL fields
  2515. tag.description = parseUtf8(tag.data, 1, i);
  2516. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  2517. break;
  2518. }
  2519. }
  2520. },
  2521. PRIV: function(tag) {
  2522. var i;
  2523.  
  2524. for (i = 0; i < tag.data.length; i++) {
  2525. if (tag.data[i] === 0) {
  2526. // parse the description and URL fields
  2527. tag.owner = parseIso88591(tag.data, 0, i);
  2528. break;
  2529. }
  2530. }
  2531. tag.privateData = tag.data.subarray(i + 1);
  2532. tag.data = tag.privateData;
  2533. }
  2534. },
  2535. MetadataStream;
  2536.  
  2537. MetadataStream = function(options) {
  2538. var
  2539. settings = {
  2540. debug: !!(options && options.debug),
  2541.  
  2542. // the bytes of the program-level descriptor field in MP2T
  2543. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  2544. // program element descriptors"
  2545. descriptor: options && options.descriptor
  2546. },
  2547. // the total size in bytes of the ID3 tag being parsed
  2548. tagSize = 0,
  2549. // tag data that is not complete enough to be parsed
  2550. buffer = [],
  2551. // the total number of bytes currently in the buffer
  2552. bufferSize = 0,
  2553. i;
  2554.  
  2555. MetadataStream.prototype.init.call(this);
  2556.  
  2557. // calculate the text track in-band metadata track dispatch type
  2558. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  2559. this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16);
  2560. if (settings.descriptor) {
  2561. for (i = 0; i < settings.descriptor.length; i++) {
  2562. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  2563. }
  2564. }
  2565.  
  2566. this.push = function(chunk) {
  2567. var tag, frameStart, frameSize, frame, i, frameHeader;
  2568. if (chunk.type !== 'timed-metadata') {
  2569. return;
  2570. }
  2571.  
  2572. // if data_alignment_indicator is set in the PES header,
  2573. // we must have the start of a new ID3 tag. Assume anything
  2574. // remaining in the buffer was malformed and throw it out
  2575. if (chunk.dataAlignmentIndicator) {
  2576. bufferSize = 0;
  2577. buffer.length = 0;
  2578. }
  2579.  
  2580. // ignore events that don't look like ID3 data
  2581. if (buffer.length === 0 &&
  2582. (chunk.data.length < 10 ||
  2583. chunk.data[0] !== 'I'.charCodeAt(0) ||
  2584. chunk.data[1] !== 'D'.charCodeAt(0) ||
  2585. chunk.data[2] !== '3'.charCodeAt(0))) {
  2586. if (settings.debug) {
  2587. // eslint-disable-next-line no-console
  2588. console.log('Skipping unrecognized metadata packet');
  2589. }
  2590. return;
  2591. }
  2592.  
  2593. // add this chunk to the data we've collected so far
  2594.  
  2595. buffer.push(chunk);
  2596. bufferSize += chunk.data.byteLength;
  2597.  
  2598. // grab the size of the entire frame from the ID3 header
  2599. if (buffer.length === 1) {
  2600. // the frame size is transmitted as a 28-bit integer in the
  2601. // last four bytes of the ID3 header.
  2602. // The most significant bit of each byte is dropped and the
  2603. // results concatenated to recover the actual value.
  2604. tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10));
  2605.  
  2606. // ID3 reports the tag size excluding the header but it's more
  2607. // convenient for our comparisons to include it
  2608. tagSize += 10;
  2609. }
  2610.  
  2611. // if the entire frame has not arrived, wait for more data
  2612. if (bufferSize < tagSize) {
  2613. return;
  2614. }
  2615.  
  2616. // collect the entire frame so it can be parsed
  2617. tag = {
  2618. data: new Uint8Array(tagSize),
  2619. frames: [],
  2620. pts: buffer[0].pts,
  2621. dts: buffer[0].dts
  2622. };
  2623. for (i = 0; i < tagSize;) {
  2624. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  2625. i += buffer[0].data.byteLength;
  2626. bufferSize -= buffer[0].data.byteLength;
  2627. buffer.shift();
  2628. }
  2629.  
  2630. // find the start of the first frame and the end of the tag
  2631. frameStart = 10;
  2632. if (tag.data[5] & 0x40) {
  2633. // advance the frame start past the extended header
  2634. frameStart += 4; // header size field
  2635. frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14));
  2636.  
  2637. // clip any padding off the end
  2638. tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
  2639. }
  2640.  
  2641. // parse one or more ID3 frames
  2642. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  2643. do {
  2644. // determine the number of bytes in this frame
  2645. frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  2646. if (frameSize < 1) {
  2647. // eslint-disable-next-line no-console
  2648. return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
  2649. }
  2650. frameHeader = String.fromCharCode(tag.data[frameStart],
  2651. tag.data[frameStart + 1],
  2652. tag.data[frameStart + 2],
  2653. tag.data[frameStart + 3]);
  2654.  
  2655.  
  2656. frame = {
  2657. id: frameHeader,
  2658. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  2659. };
  2660. frame.key = frame.id;
  2661. if (tagParsers[frame.id]) {
  2662. tagParsers[frame.id](frame);
  2663.  
  2664. // handle the special PRIV frame used to indicate the start
  2665. // time for raw AAC data
  2666. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  2667. var
  2668. d = frame.data,
  2669. size = ((d[3] & 0x01) << 30) |
  2670. (d[4] << 22) |
  2671. (d[5] << 14) |
  2672. (d[6] << 6) |
  2673. (d[7] >>> 2);
  2674.  
  2675. size *= 4;
  2676. size += d[7] & 0x03;
  2677. frame.timeStamp = size;
  2678. // in raw AAC, all subsequent data will be timestamped based
  2679. // on the value of this frame
  2680. // we couldn't have known the appropriate pts and dts before
  2681. // parsing this ID3 tag so set those values now
  2682. if (tag.pts === undefined && tag.dts === undefined) {
  2683. tag.pts = frame.timeStamp;
  2684. tag.dts = frame.timeStamp;
  2685. }
  2686. this.trigger('timestamp', frame);
  2687. }
  2688. }
  2689. tag.frames.push(frame);
  2690.  
  2691. frameStart += 10; // advance past the frame header
  2692. frameStart += frameSize; // advance past the frame body
  2693. } while (frameStart < tagSize);
  2694. this.trigger('data', tag);
  2695. };
  2696. };
  2697. MetadataStream.prototype = new Stream();
  2698.  
  2699. module.exports = MetadataStream;
  2700.  
  2701. },{"11":11,"31":31}],11:[function(require,module,exports){
  2702. /**
  2703. * mux.js
  2704. *
  2705. * Copyright (c) Brightcove
  2706. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2707. */
  2708. 'use strict';
  2709.  
  2710. module.exports = {
  2711. H264_STREAM_TYPE: 0x1B,
  2712. ADTS_STREAM_TYPE: 0x0F,
  2713. METADATA_STREAM_TYPE: 0x15
  2714. };
  2715.  
  2716. },{}],12:[function(require,module,exports){
  2717. /**
  2718. * mux.js
  2719. *
  2720. * Copyright (c) Brightcove
  2721. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2722. *
  2723. * Accepts program elementary stream (PES) data events and corrects
  2724. * decode and presentation time stamps to account for a rollover
  2725. * of the 33 bit value.
  2726. */
  2727.  
  2728. 'use strict';
  2729.  
  2730. var Stream = require(31);
  2731.  
  2732. var MAX_TS = 8589934592;
  2733.  
  2734. var RO_THRESH = 4294967296;
  2735.  
  2736. var TYPE_SHARED = 'shared';
  2737.  
  2738. var handleRollover = function(value, reference) {
  2739. var direction = 1;
  2740.  
  2741. if (value > reference) {
  2742. // If the current timestamp value is greater than our reference timestamp and we detect a
  2743. // timestamp rollover, this means the roll over is happening in the opposite direction.
  2744. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  2745. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  2746. // rollover point. In loading this segment, the timestamp values will be very large,
  2747. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  2748. // the time stamp to be `value - 2^33`.
  2749. direction = -1;
  2750. }
  2751.  
  2752. // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  2753. // cause an incorrect adjustment.
  2754. while (Math.abs(reference - value) > RO_THRESH) {
  2755. value += (direction * MAX_TS);
  2756. }
  2757.  
  2758. return value;
  2759. };
  2760.  
  2761. var TimestampRolloverStream = function(type) {
  2762. var lastDTS, referenceDTS;
  2763.  
  2764. TimestampRolloverStream.prototype.init.call(this);
  2765.  
  2766. // The "shared" type is used in cases where a stream will contain muxed
  2767. // video and audio. We could use `undefined` here, but having a string
  2768. // makes debugging a little clearer.
  2769. this.type_ = type || TYPE_SHARED;
  2770.  
  2771. this.push = function(data) {
  2772.  
  2773. // Any "shared" rollover streams will accept _all_ data. Otherwise,
  2774. // streams will only accept data that matches their type.
  2775. if (this.type_ !== TYPE_SHARED && data.type !== this.type_) {
  2776. return;
  2777. }
  2778.  
  2779. if (referenceDTS === undefined) {
  2780. referenceDTS = data.dts;
  2781. }
  2782.  
  2783. data.dts = handleRollover(data.dts, referenceDTS);
  2784. data.pts = handleRollover(data.pts, referenceDTS);
  2785.  
  2786. lastDTS = data.dts;
  2787.  
  2788. this.trigger('data', data);
  2789. };
  2790.  
  2791. this.flush = function() {
  2792. referenceDTS = lastDTS;
  2793. this.trigger('done');
  2794. };
  2795.  
  2796. this.endTimeline = function() {
  2797. this.flush();
  2798. this.trigger('endedtimeline');
  2799. };
  2800.  
  2801. this.discontinuity = function() {
  2802. referenceDTS = void 0;
  2803. lastDTS = void 0;
  2804. };
  2805.  
  2806. this.reset = function() {
  2807. this.discontinuity();
  2808. this.trigger('reset');
  2809. };
  2810. };
  2811.  
  2812. TimestampRolloverStream.prototype = new Stream();
  2813.  
  2814. module.exports = {
  2815. TimestampRolloverStream: TimestampRolloverStream,
  2816. handleRollover: handleRollover
  2817. };
  2818.  
  2819. },{"31":31}],13:[function(require,module,exports){
  2820. /**
  2821. * mux.js
  2822. *
  2823. * Copyright (c) Brightcove
  2824. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2825. */
  2826. var coneOfSilence = require(7);
  2827. var clock = require(29);
  2828.  
  2829. /**
  2830. * Sum the `byteLength` properties of the data in each AAC frame
  2831. */
  2832. var sumFrameByteLengths = function(array) {
  2833. var
  2834. i,
  2835. currentObj,
  2836. sum = 0;
  2837.  
  2838. // sum the byteLength's all each nal unit in the frame
  2839. for (i = 0; i < array.length; i++) {
  2840. currentObj = array[i];
  2841. sum += currentObj.data.byteLength;
  2842. }
  2843.  
  2844. return sum;
  2845. };
  2846.  
  2847. // Possibly pad (prefix) the audio track with silence if appending this track
  2848. // would lead to the introduction of a gap in the audio buffer
  2849. var prefixWithSilence = function(
  2850. track,
  2851. frames,
  2852. audioAppendStartTs,
  2853. videoBaseMediaDecodeTime
  2854. ) {
  2855. var
  2856. baseMediaDecodeTimeTs,
  2857. frameDuration = 0,
  2858. audioGapDuration = 0,
  2859. audioFillFrameCount = 0,
  2860. audioFillDuration = 0,
  2861. silentFrame,
  2862. i,
  2863. firstFrame;
  2864.  
  2865. if (!frames.length) {
  2866. return;
  2867. }
  2868.  
  2869. baseMediaDecodeTimeTs =
  2870. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate);
  2871. // determine frame clock duration based on sample rate, round up to avoid overfills
  2872. frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  2873.  
  2874. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  2875. // insert the shortest possible amount (audio gap or audio to video gap)
  2876. audioGapDuration =
  2877. baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime);
  2878. // number of full frames in the audio gap
  2879. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  2880. audioFillDuration = audioFillFrameCount * frameDuration;
  2881. }
  2882.  
  2883. // don't attempt to fill gaps smaller than a single frame or larger
  2884. // than a half second
  2885. if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
  2886. return;
  2887. }
  2888.  
  2889. silentFrame = coneOfSilence()[track.samplerate];
  2890.  
  2891. if (!silentFrame) {
  2892. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  2893. // from the content instead
  2894. silentFrame = frames[0].data;
  2895. }
  2896.  
  2897. for (i = 0; i < audioFillFrameCount; i++) {
  2898. firstFrame = frames[0];
  2899.  
  2900. frames.splice(0, 0, {
  2901. data: silentFrame,
  2902. dts: firstFrame.dts - frameDuration,
  2903. pts: firstFrame.pts - frameDuration
  2904. });
  2905. }
  2906.  
  2907. track.baseMediaDecodeTime -=
  2908. Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
  2909. };
  2910.  
  2911. // If the audio segment extends before the earliest allowed dts
  2912. // value, remove AAC frames until starts at or after the earliest
  2913. // allowed DTS so that we don't end up with a negative baseMedia-
  2914. // DecodeTime for the audio track
  2915. var trimAdtsFramesByEarliestDts = function(adtsFrames, track, earliestAllowedDts) {
  2916. if (track.minSegmentDts >= earliestAllowedDts) {
  2917. return adtsFrames;
  2918. }
  2919.  
  2920. // We will need to recalculate the earliest segment Dts
  2921. track.minSegmentDts = Infinity;
  2922.  
  2923. return adtsFrames.filter(function(currentFrame) {
  2924. // If this is an allowed frame, keep it and record it's Dts
  2925. if (currentFrame.dts >= earliestAllowedDts) {
  2926. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  2927. track.minSegmentPts = track.minSegmentDts;
  2928. return true;
  2929. }
  2930. // Otherwise, discard it
  2931. return false;
  2932. });
  2933. };
  2934.  
  2935. // generate the track's raw mdat data from an array of frames
  2936. var generateSampleTable = function(frames) {
  2937. var
  2938. i,
  2939. currentFrame,
  2940. samples = [];
  2941.  
  2942. for (i = 0; i < frames.length; i++) {
  2943. currentFrame = frames[i];
  2944. samples.push({
  2945. size: currentFrame.data.byteLength,
  2946. duration: 1024 // For AAC audio, all samples contain 1024 samples
  2947. });
  2948. }
  2949. return samples;
  2950. };
  2951.  
  2952. // generate the track's sample table from an array of frames
  2953. var concatenateFrameData = function(frames) {
  2954. var
  2955. i,
  2956. currentFrame,
  2957. dataOffset = 0,
  2958. data = new Uint8Array(sumFrameByteLengths(frames));
  2959.  
  2960. for (i = 0; i < frames.length; i++) {
  2961. currentFrame = frames[i];
  2962.  
  2963. data.set(currentFrame.data, dataOffset);
  2964. dataOffset += currentFrame.data.byteLength;
  2965. }
  2966. return data;
  2967. };
  2968.  
  2969. module.exports = {
  2970. prefixWithSilence: prefixWithSilence,
  2971. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  2972. generateSampleTable: generateSampleTable,
  2973. concatenateFrameData: concatenateFrameData
  2974. };
  2975.  
  2976. },{"29":29,"7":7}],14:[function(require,module,exports){
  2977. /**
  2978. * mux.js
  2979. *
  2980. * Copyright (c) Brightcove
  2981. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2982. *
  2983. * Reads in-band CEA-708 captions out of FMP4 segments.
  2984. * @see https://en.wikipedia.org/wiki/CEA-708
  2985. */
  2986. 'use strict';
  2987.  
  2988. var discardEmulationPreventionBytes = require(23).discardEmulationPreventionBytes;
  2989. var CaptionStream = require(8).CaptionStream;
  2990. var findBox = require(15);
  2991. var parseTfdt = require(25);
  2992. var parseTrun = require(27);
  2993. var parseTfhd = require(26);
  2994.  
  2995. /**
  2996. * Maps an offset in the mdat to a sample based on the the size of the samples.
  2997. * Assumes that `parseSamples` has been called first.
  2998. *
  2999. * @param {Number} offset - The offset into the mdat
  3000. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  3001. * @return {?Object} The matching sample, or null if no match was found.
  3002. *
  3003. * @see ISO-BMFF-12/2015, Section 8.8.8
  3004. **/
  3005. var mapToSample = function(offset, samples) {
  3006. var approximateOffset = offset;
  3007.  
  3008. for (var i = 0; i < samples.length; i++) {
  3009. var sample = samples[i];
  3010.  
  3011. if (approximateOffset < sample.size) {
  3012. return sample;
  3013. }
  3014.  
  3015. approximateOffset -= sample.size;
  3016. }
  3017.  
  3018. return null;
  3019. };
  3020.  
  3021. /**
  3022. * Finds SEI nal units contained in a Media Data Box.
  3023. * Assumes that `parseSamples` has been called first.
  3024. *
  3025. * @param {Uint8Array} avcStream - The bytes of the mdat
  3026. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  3027. * @param {Number} trackId - The trackId of this video track
  3028. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  3029. * The contents of the seiNal should match what is expected by
  3030. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  3031. *
  3032. * @see ISO-BMFF-12/2015, Section 8.1.1
  3033. * @see Rec. ITU-T H.264, 7.3.2.3.1
  3034. **/
  3035. var findSeiNals = function(avcStream, samples, trackId) {
  3036. var
  3037. avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  3038. result = [],
  3039. seiNal,
  3040. i,
  3041. length,
  3042. lastMatchedSample;
  3043.  
  3044. for (i = 0; i + 4 < avcStream.length; i += length) {
  3045. length = avcView.getUint32(i);
  3046. i += 4;
  3047.  
  3048. // Bail if this doesn't appear to be an H264 stream
  3049. if (length <= 0) {
  3050. continue;
  3051. }
  3052.  
  3053. switch (avcStream[i] & 0x1F) {
  3054. case 0x06:
  3055. var data = avcStream.subarray(i + 1, i + 1 + length);
  3056. var matchingSample = mapToSample(i, samples);
  3057.  
  3058. seiNal = {
  3059. nalUnitType: 'sei_rbsp',
  3060. size: length,
  3061. data: data,
  3062. escapedRBSP: discardEmulationPreventionBytes(data),
  3063. trackId: trackId
  3064. };
  3065.  
  3066. if (matchingSample) {
  3067. seiNal.pts = matchingSample.pts;
  3068. seiNal.dts = matchingSample.dts;
  3069. lastMatchedSample = matchingSample;
  3070. } else if (lastMatchedSample) {
  3071. // If a matching sample cannot be found, use the last
  3072. // sample's values as they should be as close as possible
  3073. seiNal.pts = lastMatchedSample.pts;
  3074. seiNal.dts = lastMatchedSample.dts;
  3075. } else {
  3076. // eslint-disable-next-line no-console
  3077. console.log("We've encountered a nal unit without data. See mux.js#233.");
  3078. break;
  3079. }
  3080.  
  3081. result.push(seiNal);
  3082. break;
  3083. default:
  3084. break;
  3085. }
  3086. }
  3087.  
  3088. return result;
  3089. };
  3090.  
  3091. /**
  3092. * Parses sample information out of Track Run Boxes and calculates
  3093. * the absolute presentation and decode timestamps of each sample.
  3094. *
  3095. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  3096. * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
  3097. @see ISO-BMFF-12/2015, Section 8.8.12
  3098. * @param {Object} tfhd - The parsed Track Fragment Header
  3099. * @see inspect.parseTfhd
  3100. * @return {Object[]} the parsed samples
  3101. *
  3102. * @see ISO-BMFF-12/2015, Section 8.8.8
  3103. **/
  3104. var parseSamples = function(truns, baseMediaDecodeTime, tfhd) {
  3105. var currentDts = baseMediaDecodeTime;
  3106. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  3107. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  3108. var trackId = tfhd.trackId;
  3109. var allSamples = [];
  3110.  
  3111. truns.forEach(function(trun) {
  3112. // Note: We currently do not parse the sample table as well
  3113. // as the trun. It's possible some sources will require this.
  3114. // moov > trak > mdia > minf > stbl
  3115. var trackRun = parseTrun(trun);
  3116. var samples = trackRun.samples;
  3117.  
  3118. samples.forEach(function(sample) {
  3119. if (sample.duration === undefined) {
  3120. sample.duration = defaultSampleDuration;
  3121. }
  3122. if (sample.size === undefined) {
  3123. sample.size = defaultSampleSize;
  3124. }
  3125. sample.trackId = trackId;
  3126. sample.dts = currentDts;
  3127. if (sample.compositionTimeOffset === undefined) {
  3128. sample.compositionTimeOffset = 0;
  3129. }
  3130. sample.pts = currentDts + sample.compositionTimeOffset;
  3131.  
  3132. currentDts += sample.duration;
  3133. });
  3134.  
  3135. allSamples = allSamples.concat(samples);
  3136. });
  3137.  
  3138. return allSamples;
  3139. };
  3140.  
  3141. /**
  3142. * Parses out caption nals from an FMP4 segment's video tracks.
  3143. *
  3144. * @param {Uint8Array} segment - The bytes of a single segment
  3145. * @param {Number} videoTrackId - The trackId of a video track in the segment
  3146. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  3147. * a list of seiNals found in that track
  3148. **/
  3149. var parseCaptionNals = function(segment, videoTrackId) {
  3150. // To get the samples
  3151. var trafs = findBox(segment, ['moof', 'traf']);
  3152. // To get SEI NAL units
  3153. var mdats = findBox(segment, ['mdat']);
  3154. var captionNals = {};
  3155. var mdatTrafPairs = [];
  3156.  
  3157. // Pair up each traf with a mdat as moofs and mdats are in pairs
  3158. mdats.forEach(function(mdat, index) {
  3159. var matchingTraf = trafs[index];
  3160. mdatTrafPairs.push({
  3161. mdat: mdat,
  3162. traf: matchingTraf
  3163. });
  3164. });
  3165.  
  3166. mdatTrafPairs.forEach(function(pair) {
  3167. var mdat = pair.mdat;
  3168. var traf = pair.traf;
  3169. var tfhd = findBox(traf, ['tfhd']);
  3170. // Exactly 1 tfhd per traf
  3171. var headerInfo = parseTfhd(tfhd[0]);
  3172. var trackId = headerInfo.trackId;
  3173. var tfdt = findBox(traf, ['tfdt']);
  3174. // Either 0 or 1 tfdt per traf
  3175. var baseMediaDecodeTime = (tfdt.length > 0) ? parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
  3176. var truns = findBox(traf, ['trun']);
  3177. var samples;
  3178. var seiNals;
  3179.  
  3180. // Only parse video data for the chosen video track
  3181. if (videoTrackId === trackId && truns.length > 0) {
  3182. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  3183.  
  3184. seiNals = findSeiNals(mdat, samples, trackId);
  3185.  
  3186. if (!captionNals[trackId]) {
  3187. captionNals[trackId] = [];
  3188. }
  3189.  
  3190. captionNals[trackId] = captionNals[trackId].concat(seiNals);
  3191. }
  3192. });
  3193.  
  3194. return captionNals;
  3195. };
  3196.  
  3197. /**
  3198. * Parses out inband captions from an MP4 container and returns
  3199. * caption objects that can be used by WebVTT and the TextTrack API.
  3200. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  3201. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  3202. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  3203. *
  3204. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  3205. * @param {Number} trackId - The id of the video track to parse
  3206. * @param {Number} timescale - The timescale for the video track from the init segment
  3207. *
  3208. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  3209. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  3210. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  3211. * @return {String} parsedCaptions[].text - The visible content of the caption
  3212. **/
  3213. var parseEmbeddedCaptions = function(segment, trackId, timescale) {
  3214. var seiNals;
  3215.  
  3216. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  3217. if (trackId === null) {
  3218. return null;
  3219. }
  3220.  
  3221. seiNals = parseCaptionNals(segment, trackId);
  3222.  
  3223. return {
  3224. seiNals: seiNals[trackId],
  3225. timescale: timescale
  3226. };
  3227. };
  3228.  
  3229. /**
  3230. * Converts SEI NALUs into captions that can be used by video.js
  3231. **/
  3232. var CaptionParser = function() {
  3233. var isInitialized = false;
  3234. var captionStream;
  3235.  
  3236. // Stores segments seen before trackId and timescale are set
  3237. var segmentCache;
  3238. // Stores video track ID of the track being parsed
  3239. var trackId;
  3240. // Stores the timescale of the track being parsed
  3241. var timescale;
  3242. // Stores captions parsed so far
  3243. var parsedCaptions;
  3244. // Stores whether we are receiving partial data or not
  3245. var parsingPartial;
  3246.  
  3247. /**
  3248. * A method to indicate whether a CaptionParser has been initalized
  3249. * @returns {Boolean}
  3250. **/
  3251. this.isInitialized = function() {
  3252. return isInitialized;
  3253. };
  3254.  
  3255. /**
  3256. * Initializes the underlying CaptionStream, SEI NAL parsing
  3257. * and management, and caption collection
  3258. **/
  3259. this.init = function(options) {
  3260. captionStream = new CaptionStream();
  3261. isInitialized = true;
  3262. parsingPartial = options ? options.isPartial : false;
  3263.  
  3264. // Collect dispatched captions
  3265. captionStream.on('data', function(event) {
  3266. // Convert to seconds in the source's timescale
  3267. event.startTime = event.startPts / timescale;
  3268. event.endTime = event.endPts / timescale;
  3269.  
  3270. parsedCaptions.captions.push(event);
  3271. parsedCaptions.captionStreams[event.stream] = true;
  3272. });
  3273. };
  3274.  
  3275. /**
  3276. * Determines if a new video track will be selected
  3277. * or if the timescale changed
  3278. * @return {Boolean}
  3279. **/
  3280. this.isNewInit = function(videoTrackIds, timescales) {
  3281. if ((videoTrackIds && videoTrackIds.length === 0) ||
  3282. (timescales && typeof timescales === 'object' &&
  3283. Object.keys(timescales).length === 0)) {
  3284. return false;
  3285. }
  3286.  
  3287. return trackId !== videoTrackIds[0] ||
  3288. timescale !== timescales[trackId];
  3289. };
  3290.  
  3291. /**
  3292. * Parses out SEI captions and interacts with underlying
  3293. * CaptionStream to return dispatched captions
  3294. *
  3295. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  3296. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  3297. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  3298. * @see parseEmbeddedCaptions
  3299. * @see m2ts/caption-stream.js
  3300. **/
  3301. this.parse = function(segment, videoTrackIds, timescales) {
  3302. var parsedData;
  3303.  
  3304. if (!this.isInitialized()) {
  3305. return null;
  3306.  
  3307. // This is not likely to be a video segment
  3308. } else if (!videoTrackIds || !timescales) {
  3309. return null;
  3310.  
  3311. } else if (this.isNewInit(videoTrackIds, timescales)) {
  3312. // Use the first video track only as there is no
  3313. // mechanism to switch to other video tracks
  3314. trackId = videoTrackIds[0];
  3315. timescale = timescales[trackId];
  3316.  
  3317. // If an init segment has not been seen yet, hold onto segment
  3318. // data until we have one.
  3319. // the ISO-BMFF spec says that trackId can't be zero, but there's some broken content out there
  3320. } else if (trackId === null || !timescale) {
  3321. segmentCache.push(segment);
  3322. return null;
  3323. }
  3324.  
  3325. // Now that a timescale and trackId is set, parse cached segments
  3326. while (segmentCache.length > 0) {
  3327. var cachedSegment = segmentCache.shift();
  3328.  
  3329. this.parse(cachedSegment, videoTrackIds, timescales);
  3330. }
  3331.  
  3332. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  3333.  
  3334. if (parsedData === null || !parsedData.seiNals) {
  3335. return null;
  3336. }
  3337.  
  3338. this.pushNals(parsedData.seiNals);
  3339. // Force the parsed captions to be dispatched
  3340. this.flushStream();
  3341.  
  3342. return parsedCaptions;
  3343. };
  3344.  
  3345. /**
  3346. * Pushes SEI NALUs onto CaptionStream
  3347. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  3348. * Assumes that `parseCaptionNals` has been called first
  3349. * @see m2ts/caption-stream.js
  3350. **/
  3351. this.pushNals = function(nals) {
  3352. if (!this.isInitialized() || !nals || nals.length === 0) {
  3353. return null;
  3354. }
  3355.  
  3356. nals.forEach(function(nal) {
  3357. captionStream.push(nal);
  3358. });
  3359. };
  3360.  
  3361. /**
  3362. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  3363. * @see m2ts/caption-stream.js
  3364. **/
  3365. this.flushStream = function() {
  3366. if (!this.isInitialized()) {
  3367. return null;
  3368. }
  3369.  
  3370. if (!parsingPartial) {
  3371. captionStream.flush();
  3372. } else {
  3373. captionStream.partialFlush();
  3374. }
  3375. };
  3376.  
  3377. /**
  3378. * Reset caption buckets for new data
  3379. **/
  3380. this.clearParsedCaptions = function() {
  3381. parsedCaptions.captions = [];
  3382. parsedCaptions.captionStreams = {};
  3383. };
  3384.  
  3385. /**
  3386. * Resets underlying CaptionStream
  3387. * @see m2ts/caption-stream.js
  3388. **/
  3389. this.resetCaptionStream = function() {
  3390. if (!this.isInitialized()) {
  3391. return null;
  3392. }
  3393.  
  3394. captionStream.reset();
  3395. };
  3396.  
  3397. /**
  3398. * Convenience method to clear all captions flushed from the
  3399. * CaptionStream and still being parsed
  3400. * @see m2ts/caption-stream.js
  3401. **/
  3402. this.clearAllCaptions = function() {
  3403. this.clearParsedCaptions();
  3404. this.resetCaptionStream();
  3405. };
  3406.  
  3407. /**
  3408. * Reset caption parser
  3409. **/
  3410. this.reset = function() {
  3411. segmentCache = [];
  3412. trackId = null;
  3413. timescale = null;
  3414.  
  3415. if (!parsedCaptions) {
  3416. parsedCaptions = {
  3417. captions: [],
  3418. // CC1, CC2, CC3, CC4
  3419. captionStreams: {}
  3420. };
  3421. } else {
  3422. this.clearParsedCaptions();
  3423. }
  3424.  
  3425. this.resetCaptionStream();
  3426. };
  3427.  
  3428. this.reset();
  3429. };
  3430.  
  3431. module.exports = CaptionParser;
  3432.  
  3433. },{"15":15,"23":23,"25":25,"26":26,"27":27,"8":8}],15:[function(require,module,exports){
  3434. var toUnsigned = require(28).toUnsigned;
  3435. var parseType = require(19);
  3436.  
  3437. var findBox = function(data, path) {
  3438. var results = [],
  3439. i, size, type, end, subresults;
  3440.  
  3441. if (!path.length) {
  3442. // short-circuit the search for empty paths
  3443. return null;
  3444. }
  3445.  
  3446. for (i = 0; i < data.byteLength;) {
  3447. size = toUnsigned(data[i] << 24 |
  3448. data[i + 1] << 16 |
  3449. data[i + 2] << 8 |
  3450. data[i + 3]);
  3451.  
  3452. type = parseType(data.subarray(i + 4, i + 8));
  3453.  
  3454. end = size > 1 ? i + size : data.byteLength;
  3455.  
  3456. if (type === path[0]) {
  3457. if (path.length === 1) {
  3458. // this is the end of the path and we've found the box we were
  3459. // looking for
  3460. results.push(data.subarray(i + 8, end));
  3461. } else {
  3462. // recursively search for the next box along the path
  3463. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  3464. if (subresults.length) {
  3465. results = results.concat(subresults);
  3466. }
  3467. }
  3468. }
  3469. i = end;
  3470. }
  3471.  
  3472. // we've finished searching all of data
  3473. return results;
  3474. };
  3475.  
  3476. module.exports = findBox;
  3477.  
  3478.  
  3479. },{"19":19,"28":28}],16:[function(require,module,exports){
  3480. /**
  3481. * mux.js
  3482. *
  3483. * Copyright (c) Brightcove
  3484. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3485. */
  3486. // Convert an array of nal units into an array of frames with each frame being
  3487. // composed of the nal units that make up that frame
  3488. // Also keep track of cummulative data about the frame from the nal units such
  3489. // as the frame duration, starting pts, etc.
  3490. var groupNalsIntoFrames = function(nalUnits) {
  3491. var
  3492. i,
  3493. currentNal,
  3494. currentFrame = [],
  3495. frames = [];
  3496.  
  3497. // TODO added for LHLS, make sure this is OK
  3498. frames.byteLength = 0;
  3499. frames.nalCount = 0;
  3500. frames.duration = 0;
  3501.  
  3502. currentFrame.byteLength = 0;
  3503.  
  3504. for (i = 0; i < nalUnits.length; i++) {
  3505. currentNal = nalUnits[i];
  3506.  
  3507. // Split on 'aud'-type nal units
  3508. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  3509. // Since the very first nal unit is expected to be an AUD
  3510. // only push to the frames array when currentFrame is not empty
  3511. if (currentFrame.length) {
  3512. currentFrame.duration = currentNal.dts - currentFrame.dts;
  3513. // TODO added for LHLS, make sure this is OK
  3514. frames.byteLength += currentFrame.byteLength;
  3515. frames.nalCount += currentFrame.length;
  3516. frames.duration += currentFrame.duration;
  3517. frames.push(currentFrame);
  3518. }
  3519. currentFrame = [currentNal];
  3520. currentFrame.byteLength = currentNal.data.byteLength;
  3521. currentFrame.pts = currentNal.pts;
  3522. currentFrame.dts = currentNal.dts;
  3523. } else {
  3524. // Specifically flag key frames for ease of use later
  3525. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  3526. currentFrame.keyFrame = true;
  3527. }
  3528. currentFrame.duration = currentNal.dts - currentFrame.dts;
  3529. currentFrame.byteLength += currentNal.data.byteLength;
  3530. currentFrame.push(currentNal);
  3531. }
  3532. }
  3533.  
  3534. // For the last frame, use the duration of the previous frame if we
  3535. // have nothing better to go on
  3536. if (frames.length &&
  3537. (!currentFrame.duration ||
  3538. currentFrame.duration <= 0)) {
  3539. currentFrame.duration = frames[frames.length - 1].duration;
  3540. }
  3541.  
  3542. // Push the final frame
  3543. // TODO added for LHLS, make sure this is OK
  3544. frames.byteLength += currentFrame.byteLength;
  3545. frames.nalCount += currentFrame.length;
  3546. frames.duration += currentFrame.duration;
  3547.  
  3548. frames.push(currentFrame);
  3549. return frames;
  3550. };
  3551.  
  3552. // Convert an array of frames into an array of Gop with each Gop being composed
  3553. // of the frames that make up that Gop
  3554. // Also keep track of cummulative data about the Gop from the frames such as the
  3555. // Gop duration, starting pts, etc.
  3556. var groupFramesIntoGops = function(frames) {
  3557. var
  3558. i,
  3559. currentFrame,
  3560. currentGop = [],
  3561. gops = [];
  3562.  
  3563. // We must pre-set some of the values on the Gop since we
  3564. // keep running totals of these values
  3565. currentGop.byteLength = 0;
  3566. currentGop.nalCount = 0;
  3567. currentGop.duration = 0;
  3568. currentGop.pts = frames[0].pts;
  3569. currentGop.dts = frames[0].dts;
  3570.  
  3571. // store some metadata about all the Gops
  3572. gops.byteLength = 0;
  3573. gops.nalCount = 0;
  3574. gops.duration = 0;
  3575. gops.pts = frames[0].pts;
  3576. gops.dts = frames[0].dts;
  3577.  
  3578. for (i = 0; i < frames.length; i++) {
  3579. currentFrame = frames[i];
  3580.  
  3581. if (currentFrame.keyFrame) {
  3582. // Since the very first frame is expected to be an keyframe
  3583. // only push to the gops array when currentGop is not empty
  3584. if (currentGop.length) {
  3585. gops.push(currentGop);
  3586. gops.byteLength += currentGop.byteLength;
  3587. gops.nalCount += currentGop.nalCount;
  3588. gops.duration += currentGop.duration;
  3589. }
  3590.  
  3591. currentGop = [currentFrame];
  3592. currentGop.nalCount = currentFrame.length;
  3593. currentGop.byteLength = currentFrame.byteLength;
  3594. currentGop.pts = currentFrame.pts;
  3595. currentGop.dts = currentFrame.dts;
  3596. currentGop.duration = currentFrame.duration;
  3597. } else {
  3598. currentGop.duration += currentFrame.duration;
  3599. currentGop.nalCount += currentFrame.length;
  3600. currentGop.byteLength += currentFrame.byteLength;
  3601. currentGop.push(currentFrame);
  3602. }
  3603. }
  3604.  
  3605. if (gops.length && currentGop.duration <= 0) {
  3606. currentGop.duration = gops[gops.length - 1].duration;
  3607. }
  3608. gops.byteLength += currentGop.byteLength;
  3609. gops.nalCount += currentGop.nalCount;
  3610. gops.duration += currentGop.duration;
  3611.  
  3612. // push the final Gop
  3613. gops.push(currentGop);
  3614. return gops;
  3615. };
  3616.  
  3617. /*
  3618. * Search for the first keyframe in the GOPs and throw away all frames
  3619. * until that keyframe. Then extend the duration of the pulled keyframe
  3620. * and pull the PTS and DTS of the keyframe so that it covers the time
  3621. * range of the frames that were disposed.
  3622. *
  3623. * @param {Array} gops video GOPs
  3624. * @returns {Array} modified video GOPs
  3625. */
  3626. var extendFirstKeyFrame = function(gops) {
  3627. var currentGop;
  3628.  
  3629. if (!gops[0][0].keyFrame && gops.length > 1) {
  3630. // Remove the first GOP
  3631. currentGop = gops.shift();
  3632.  
  3633. gops.byteLength -= currentGop.byteLength;
  3634. gops.nalCount -= currentGop.nalCount;
  3635.  
  3636. // Extend the first frame of what is now the
  3637. // first gop to cover the time period of the
  3638. // frames we just removed
  3639. gops[0][0].dts = currentGop.dts;
  3640. gops[0][0].pts = currentGop.pts;
  3641. gops[0][0].duration += currentGop.duration;
  3642. }
  3643.  
  3644. return gops;
  3645. };
  3646.  
  3647. /**
  3648. * Default sample object
  3649. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  3650. */
  3651. var createDefaultSample = function() {
  3652. return {
  3653. size: 0,
  3654. flags: {
  3655. isLeading: 0,
  3656. dependsOn: 1,
  3657. isDependedOn: 0,
  3658. hasRedundancy: 0,
  3659. degradationPriority: 0,
  3660. isNonSyncSample: 1
  3661. }
  3662. };
  3663. };
  3664.  
  3665. /*
  3666. * Collates information from a video frame into an object for eventual
  3667. * entry into an MP4 sample table.
  3668. *
  3669. * @param {Object} frame the video frame
  3670. * @param {Number} dataOffset the byte offset to position the sample
  3671. * @return {Object} object containing sample table info for a frame
  3672. */
  3673. var sampleForFrame = function(frame, dataOffset) {
  3674. var sample = createDefaultSample();
  3675.  
  3676. sample.dataOffset = dataOffset;
  3677. sample.compositionTimeOffset = frame.pts - frame.dts;
  3678. sample.duration = frame.duration;
  3679. sample.size = 4 * frame.length; // Space for nal unit size
  3680. sample.size += frame.byteLength;
  3681.  
  3682. if (frame.keyFrame) {
  3683. sample.flags.dependsOn = 2;
  3684. sample.flags.isNonSyncSample = 0;
  3685. }
  3686.  
  3687. return sample;
  3688. };
  3689.  
  3690. // generate the track's sample table from an array of gops
  3691. var generateSampleTable = function(gops, baseDataOffset) {
  3692. var
  3693. h, i,
  3694. sample,
  3695. currentGop,
  3696. currentFrame,
  3697. dataOffset = baseDataOffset || 0,
  3698. samples = [];
  3699.  
  3700. for (h = 0; h < gops.length; h++) {
  3701. currentGop = gops[h];
  3702.  
  3703. for (i = 0; i < currentGop.length; i++) {
  3704. currentFrame = currentGop[i];
  3705.  
  3706. sample = sampleForFrame(currentFrame, dataOffset);
  3707.  
  3708. dataOffset += sample.size;
  3709.  
  3710. samples.push(sample);
  3711. }
  3712. }
  3713. return samples;
  3714. };
  3715.  
  3716. // generate the track's raw mdat data from an array of gops
  3717. var concatenateNalData = function(gops) {
  3718. var
  3719. h, i, j,
  3720. currentGop,
  3721. currentFrame,
  3722. currentNal,
  3723. dataOffset = 0,
  3724. nalsByteLength = gops.byteLength,
  3725. numberOfNals = gops.nalCount,
  3726. totalByteLength = nalsByteLength + 4 * numberOfNals,
  3727. data = new Uint8Array(totalByteLength),
  3728. view = new DataView(data.buffer);
  3729.  
  3730. // For each Gop..
  3731. for (h = 0; h < gops.length; h++) {
  3732. currentGop = gops[h];
  3733.  
  3734. // For each Frame..
  3735. for (i = 0; i < currentGop.length; i++) {
  3736. currentFrame = currentGop[i];
  3737.  
  3738. // For each NAL..
  3739. for (j = 0; j < currentFrame.length; j++) {
  3740. currentNal = currentFrame[j];
  3741.  
  3742. view.setUint32(dataOffset, currentNal.data.byteLength);
  3743. dataOffset += 4;
  3744. data.set(currentNal.data, dataOffset);
  3745. dataOffset += currentNal.data.byteLength;
  3746. }
  3747. }
  3748. }
  3749. return data;
  3750. };
  3751.  
  3752. // generate the track's sample table from a frame
  3753. var generateSampleTableForFrame = function(frame, baseDataOffset) {
  3754. var
  3755. sample,
  3756. dataOffset = baseDataOffset || 0,
  3757. samples = [];
  3758.  
  3759. sample = sampleForFrame(frame, dataOffset);
  3760. samples.push(sample);
  3761.  
  3762. return samples;
  3763. };
  3764.  
  3765. // generate the track's raw mdat data from a frame
  3766. var concatenateNalDataForFrame = function(frame) {
  3767. var
  3768. i,
  3769. currentNal,
  3770. dataOffset = 0,
  3771. nalsByteLength = frame.byteLength,
  3772. numberOfNals = frame.length,
  3773. totalByteLength = nalsByteLength + 4 * numberOfNals,
  3774. data = new Uint8Array(totalByteLength),
  3775. view = new DataView(data.buffer);
  3776.  
  3777. // For each NAL..
  3778. for (i = 0; i < frame.length; i++) {
  3779. currentNal = frame[i];
  3780.  
  3781. view.setUint32(dataOffset, currentNal.data.byteLength);
  3782. dataOffset += 4;
  3783. data.set(currentNal.data, dataOffset);
  3784. dataOffset += currentNal.data.byteLength;
  3785. }
  3786.  
  3787. return data;
  3788. };
  3789.  
  3790. module.exports = {
  3791. groupNalsIntoFrames: groupNalsIntoFrames,
  3792. groupFramesIntoGops: groupFramesIntoGops,
  3793. extendFirstKeyFrame: extendFirstKeyFrame,
  3794. generateSampleTable: generateSampleTable,
  3795. concatenateNalData: concatenateNalData,
  3796. generateSampleTableForFrame: generateSampleTableForFrame,
  3797. concatenateNalDataForFrame: concatenateNalDataForFrame
  3798. };
  3799.  
  3800. },{}],17:[function(require,module,exports){
  3801. /**
  3802. * mux.js
  3803. *
  3804. * Copyright (c) Brightcove
  3805. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3806. */
  3807. module.exports = {
  3808. generator: require(18),
  3809. probe: require(20),
  3810. Transmuxer: require(22).Transmuxer,
  3811. AudioSegmentStream: require(22).AudioSegmentStream,
  3812. VideoSegmentStream: require(22).VideoSegmentStream,
  3813. CaptionParser: require(14)
  3814. };
  3815.  
  3816. },{"14":14,"18":18,"20":20,"22":22}],18:[function(require,module,exports){
  3817. /**
  3818. * mux.js
  3819. *
  3820. * Copyright (c) Brightcove
  3821. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3822. *
  3823. * Functions that generate fragmented MP4s suitable for use with Media
  3824. * Source Extensions.
  3825. */
  3826. 'use strict';
  3827.  
  3828. var UINT32_MAX = Math.pow(2, 32) - 1;
  3829.  
  3830. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd,
  3831. trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex,
  3832. trun, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR,
  3833. AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;
  3834. var customDuration = 0xffffffff;
  3835.  
  3836. // pre-calculate constants
  3837. (function() {
  3838. var i;
  3839. types = {
  3840. avc1: [], // codingname
  3841. avcC: [],
  3842. btrt: [],
  3843. dinf: [],
  3844. dref: [],
  3845. esds: [],
  3846. ftyp: [],
  3847. hdlr: [],
  3848. mdat: [],
  3849. mdhd: [],
  3850. mdia: [],
  3851. mfhd: [],
  3852. minf: [],
  3853. moof: [],
  3854. moov: [],
  3855. mp4a: [], // codingname
  3856. mvex: [],
  3857. mvhd: [],
  3858. pasp: [],
  3859. sdtp: [],
  3860. smhd: [],
  3861. stbl: [],
  3862. stco: [],
  3863. stsc: [],
  3864. stsd: [],
  3865. stsz: [],
  3866. stts: [],
  3867. styp: [],
  3868. tfdt: [],
  3869. tfhd: [],
  3870. traf: [],
  3871. trak: [],
  3872. trun: [],
  3873. trex: [],
  3874. tkhd: [],
  3875. vmhd: []
  3876. };
  3877.  
  3878. // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  3879. // don't throw an error
  3880. if (typeof Uint8Array === 'undefined') {
  3881. return;
  3882. }
  3883.  
  3884. for (i in types) {
  3885. if (types.hasOwnProperty(i)) {
  3886. types[i] = [
  3887. i.charCodeAt(0),
  3888. i.charCodeAt(1),
  3889. i.charCodeAt(2),
  3890. i.charCodeAt(3)
  3891. ];
  3892. }
  3893. }
  3894.  
  3895. MAJOR_BRAND = new Uint8Array([
  3896. 'i'.charCodeAt(0),
  3897. 's'.charCodeAt(0),
  3898. 'o'.charCodeAt(0),
  3899. 'm'.charCodeAt(0)
  3900. ]);
  3901. AVC1_BRAND = new Uint8Array([
  3902. 'a'.charCodeAt(0),
  3903. 'v'.charCodeAt(0),
  3904. 'c'.charCodeAt(0),
  3905. '1'.charCodeAt(0)
  3906. ]);
  3907. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  3908. VIDEO_HDLR = new Uint8Array([
  3909. 0x00, // version 0
  3910. 0x00, 0x00, 0x00, // flags
  3911. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3912. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  3913. 0x00, 0x00, 0x00, 0x00, // reserved
  3914. 0x00, 0x00, 0x00, 0x00, // reserved
  3915. 0x00, 0x00, 0x00, 0x00, // reserved
  3916. 0x56, 0x69, 0x64, 0x65,
  3917. 0x6f, 0x48, 0x61, 0x6e,
  3918. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  3919. ]);
  3920. AUDIO_HDLR = new Uint8Array([
  3921. 0x00, // version 0
  3922. 0x00, 0x00, 0x00, // flags
  3923. 0x00, 0x00, 0x00, 0x00, // pre_defined
  3924. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  3925. 0x00, 0x00, 0x00, 0x00, // reserved
  3926. 0x00, 0x00, 0x00, 0x00, // reserved
  3927. 0x00, 0x00, 0x00, 0x00, // reserved
  3928. 0x53, 0x6f, 0x75, 0x6e,
  3929. 0x64, 0x48, 0x61, 0x6e,
  3930. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  3931. ]);
  3932. HDLR_TYPES = {
  3933. video: VIDEO_HDLR,
  3934. audio: AUDIO_HDLR
  3935. };
  3936. DREF = new Uint8Array([
  3937. 0x00, // version 0
  3938. 0x00, 0x00, 0x00, // flags
  3939. 0x00, 0x00, 0x00, 0x01, // entry_count
  3940. 0x00, 0x00, 0x00, 0x0c, // entry_size
  3941. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  3942. 0x00, // version 0
  3943. 0x00, 0x00, 0x01 // entry_flags
  3944. ]);
  3945. SMHD = new Uint8Array([
  3946. 0x00, // version
  3947. 0x00, 0x00, 0x00, // flags
  3948. 0x00, 0x00, // balance, 0 means centered
  3949. 0x00, 0x00 // reserved
  3950. ]);
  3951. STCO = new Uint8Array([
  3952. 0x00, // version
  3953. 0x00, 0x00, 0x00, // flags
  3954. 0x00, 0x00, 0x00, 0x00 // entry_count
  3955. ]);
  3956. STSC = STCO;
  3957. STSZ = new Uint8Array([
  3958. 0x00, // version
  3959. 0x00, 0x00, 0x00, // flags
  3960. 0x00, 0x00, 0x00, 0x00, // sample_size
  3961. 0x00, 0x00, 0x00, 0x00 // sample_count
  3962. ]);
  3963. STTS = STCO;
  3964. VMHD = new Uint8Array([
  3965. 0x00, // version
  3966. 0x00, 0x00, 0x01, // flags
  3967. 0x00, 0x00, // graphicsmode
  3968. 0x00, 0x00,
  3969. 0x00, 0x00,
  3970. 0x00, 0x00 // opcolor
  3971. ]);
  3972. }());
  3973.  
  3974. box = function(type) {
  3975. var
  3976. payload = [],
  3977. size = 0,
  3978. i,
  3979. result,
  3980. view;
  3981.  
  3982. for (i = 1; i < arguments.length; i++) {
  3983. payload.push(arguments[i]);
  3984. }
  3985.  
  3986. i = payload.length;
  3987.  
  3988. // calculate the total size we need to allocate
  3989. while (i--) {
  3990. size += payload[i].byteLength;
  3991. }
  3992. result = new Uint8Array(size + 8);
  3993. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  3994. view.setUint32(0, result.byteLength);
  3995. result.set(type, 4);
  3996.  
  3997. // copy the payload into the result
  3998. for (i = 0, size = 8; i < payload.length; i++) {
  3999. result.set(payload[i], size);
  4000. size += payload[i].byteLength;
  4001. }
  4002. return result;
  4003. };
  4004.  
  4005. dinf = function() {
  4006. return box(types.dinf, box(types.dref, DREF));
  4007. };
  4008.  
  4009. esds = function(track) {
  4010. return box(types.esds, new Uint8Array([
  4011. 0x00, // version
  4012. 0x00, 0x00, 0x00, // flags
  4013.  
  4014. // ES_Descriptor
  4015. 0x03, // tag, ES_DescrTag
  4016. 0x19, // length
  4017. 0x00, 0x00, // ES_ID
  4018. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  4019.  
  4020. // DecoderConfigDescriptor
  4021. 0x04, // tag, DecoderConfigDescrTag
  4022. 0x11, // length
  4023. 0x40, // object type
  4024. 0x15, // streamType
  4025. 0x00, 0x06, 0x00, // bufferSizeDB
  4026. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  4027. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  4028.  
  4029. // DecoderSpecificInfo
  4030. 0x05, // tag, DecoderSpecificInfoTag
  4031. 0x02, // length
  4032. // ISO/IEC 14496-3, AudioSpecificConfig
  4033. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  4034. (track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1),
  4035. (track.samplingfrequencyindex << 7) | (track.channelcount << 3),
  4036. 0x06, 0x01, 0x02 // GASpecificConfig
  4037. ]));
  4038. };
  4039.  
  4040. ftyp = function() {
  4041. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  4042. };
  4043.  
  4044. hdlr = function(type) {
  4045. return box(types.hdlr, HDLR_TYPES[type]);
  4046. };
  4047. mdat = function(data) {
  4048. return box(types.mdat, data);
  4049. };
  4050. mdhd = function(track) {
  4051. var result = new Uint8Array([
  4052. 0x00, // version 0
  4053. 0x00, 0x00, 0x00, // flags
  4054. 0x00, 0x00, 0x00, 0x02, // creation_time
  4055. 0x00, 0x00, 0x00, 0x03, // modification_time
  4056. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  4057.  
  4058. (track.duration >>> 24) & 0xFF,
  4059. (track.duration >>> 16) & 0xFF,
  4060. (track.duration >>> 8) & 0xFF,
  4061. track.duration & 0xFF, // duration
  4062. 0x55, 0xc4, // 'und' language (undetermined)
  4063. 0x00, 0x00
  4064. ]);
  4065.  
  4066. // Use the sample rate from the track metadata, when it is
  4067. // defined. The sample rate can be parsed out of an ADTS header, for
  4068. // instance.
  4069. if (track.samplerate) {
  4070. result[12] = (track.samplerate >>> 24) & 0xFF;
  4071. result[13] = (track.samplerate >>> 16) & 0xFF;
  4072. result[14] = (track.samplerate >>> 8) & 0xFF;
  4073. result[15] = (track.samplerate) & 0xFF;
  4074. // 閲嶇疆璇ヨ建閬撻暱搴�
  4075. track.duration = track.duration / 90000 * track.samplerate;
  4076. result[16] = (track.duration >>> 24) & 0xFF;
  4077. result[17] = (track.duration >>> 16) & 0xFF;
  4078. result[18] = (track.duration >>> 8) & 0xFF;
  4079. result[19] = (track.duration) & 0xFF;
  4080. }
  4081.  
  4082. return box(types.mdhd, result);
  4083. };
  4084. mdia = function(track) {
  4085. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  4086. };
  4087. mfhd = function(sequenceNumber) {
  4088. return box(types.mfhd, new Uint8Array([
  4089. 0x00,
  4090. 0x00, 0x00, 0x00, // flags
  4091. (sequenceNumber & 0xFF000000) >> 24,
  4092. (sequenceNumber & 0xFF0000) >> 16,
  4093. (sequenceNumber & 0xFF00) >> 8,
  4094. sequenceNumber & 0xFF // sequence_number
  4095. ]));
  4096. };
  4097. minf = function(track) {
  4098. return box(types.minf,
  4099. track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD),
  4100. dinf(),
  4101. stbl(track));
  4102. };
  4103. moof = function(sequenceNumber, tracks) {
  4104. var
  4105. trackFragments = [],
  4106. i = tracks.length;
  4107. // build traf boxes for each track fragment
  4108. while (i--) {
  4109. trackFragments[i] = traf(tracks[i]);
  4110. }
  4111. return box.apply(null, [
  4112. types.moof,
  4113. mfhd(sequenceNumber)
  4114. ].concat(trackFragments));
  4115. };
  4116. /**
  4117. * Returns a movie box.
  4118. * @param tracks {array} the tracks associated with this movie
  4119. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  4120. */
  4121. moov = function(tracks) {
  4122. var
  4123. i = tracks.length,
  4124. boxes = [];
  4125.  
  4126. while (i--) {
  4127. boxes[i] = trak(tracks[i]);
  4128. }
  4129.  
  4130. return box.apply(null, [types.moov, mvhd(customDuration)].concat(boxes).concat(mvex(tracks)));
  4131. };
  4132. mvex = function(tracks) {
  4133. var
  4134. i = tracks.length,
  4135. boxes = [];
  4136.  
  4137. while (i--) {
  4138. boxes[i] = trex(tracks[i]);
  4139. }
  4140. return box.apply(null, [types.mvex].concat(boxes));
  4141. };
  4142. mvhd = function(duration) {
  4143. var
  4144. bytes = new Uint8Array([
  4145. 0x00, // version 0
  4146. 0x00, 0x00, 0x00, // flags
  4147. 0x00, 0x00, 0x00, 0x01, // creation_time
  4148. 0x00, 0x00, 0x00, 0x02, // modification_time
  4149. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  4150. (duration & 0xFF000000) >> 24,
  4151. (duration & 0xFF0000) >> 16,
  4152. (duration & 0xFF00) >> 8,
  4153. duration & 0xFF, // duration
  4154. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  4155. 0x01, 0x00, // 1.0 volume
  4156. 0x00, 0x00, // reserved
  4157. 0x00, 0x00, 0x00, 0x00, // reserved
  4158. 0x00, 0x00, 0x00, 0x00, // reserved
  4159. 0x00, 0x01, 0x00, 0x00,
  4160. 0x00, 0x00, 0x00, 0x00,
  4161. 0x00, 0x00, 0x00, 0x00,
  4162. 0x00, 0x00, 0x00, 0x00,
  4163. 0x00, 0x01, 0x00, 0x00,
  4164. 0x00, 0x00, 0x00, 0x00,
  4165. 0x00, 0x00, 0x00, 0x00,
  4166. 0x00, 0x00, 0x00, 0x00,
  4167. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  4168. 0x00, 0x00, 0x00, 0x00,
  4169. 0x00, 0x00, 0x00, 0x00,
  4170. 0x00, 0x00, 0x00, 0x00,
  4171. 0x00, 0x00, 0x00, 0x00,
  4172. 0x00, 0x00, 0x00, 0x00,
  4173. 0x00, 0x00, 0x00, 0x00, // pre_defined
  4174. 0xff, 0xff, 0xff, 0xff // next_track_ID
  4175. ]);
  4176. return box(types.mvhd, bytes);
  4177. };
  4178.  
  4179. sdtp = function(track) {
  4180. var
  4181. samples = track.samples || [],
  4182. bytes = new Uint8Array(4 + samples.length),
  4183. flags,
  4184. i;
  4185.  
  4186. // leave the full box header (4 bytes) all zero
  4187.  
  4188. // write the sample table
  4189. for (i = 0; i < samples.length; i++) {
  4190. flags = samples[i].flags;
  4191.  
  4192. bytes[i + 4] = (flags.dependsOn << 4) |
  4193. (flags.isDependedOn << 2) |
  4194. (flags.hasRedundancy);
  4195. }
  4196.  
  4197. return box(types.sdtp,
  4198. bytes);
  4199. };
  4200.  
  4201. stbl = function(track) {
  4202. return box(types.stbl,
  4203. stsd(track),
  4204. box(types.stts, STTS),
  4205. box(types.stsc, STSC),
  4206. box(types.stsz, STSZ),
  4207. box(types.stco, STCO));
  4208. };
  4209.  
  4210. (function() {
  4211. var videoSample, audioSample;
  4212.  
  4213. stsd = function(track) {
  4214.  
  4215. return box(types.stsd, new Uint8Array([
  4216. 0x00, // version 0
  4217. 0x00, 0x00, 0x00, // flags
  4218. 0x00, 0x00, 0x00, 0x01
  4219. ]), track.type === 'video' ? videoSample(track) : audioSample(track));
  4220. };
  4221.  
  4222. videoSample = function(track) {
  4223. var
  4224. sps = track.sps || [],
  4225. pps = track.pps || [],
  4226. sequenceParameterSets = [],
  4227. pictureParameterSets = [],
  4228. i,
  4229. avc1Box;
  4230.  
  4231. // assemble the SPSs
  4232. for (i = 0; i < sps.length; i++) {
  4233. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  4234. sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength
  4235. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  4236. }
  4237.  
  4238. // assemble the PPSs
  4239. for (i = 0; i < pps.length; i++) {
  4240. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  4241. pictureParameterSets.push((pps[i].byteLength & 0xFF));
  4242. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  4243. }
  4244.  
  4245. avc1Box = [
  4246. types.avc1, new Uint8Array([
  4247. 0x00, 0x00, 0x00,
  4248. 0x00, 0x00, 0x00, // reserved
  4249. 0x00, 0x01, // data_reference_index
  4250. 0x00, 0x00, // pre_defined
  4251. 0x00, 0x00, // reserved
  4252. 0x00, 0x00, 0x00, 0x00,
  4253. 0x00, 0x00, 0x00, 0x00,
  4254. 0x00, 0x00, 0x00, 0x00, // pre_defined
  4255. (track.width & 0xff00) >> 8,
  4256. track.width & 0xff, // width
  4257. (track.height & 0xff00) >> 8,
  4258. track.height & 0xff, // height
  4259. 0x00, 0x48, 0x00, 0x00, // horizresolution
  4260. 0x00, 0x48, 0x00, 0x00, // vertresolution
  4261. 0x00, 0x00, 0x00, 0x00, // reserved
  4262. 0x00, 0x01, // frame_count
  4263. 0x13,
  4264. 0x76, 0x69, 0x64, 0x65,
  4265. 0x6f, 0x6a, 0x73, 0x2d,
  4266. 0x63, 0x6f, 0x6e, 0x74,
  4267. 0x72, 0x69, 0x62, 0x2d,
  4268. 0x68, 0x6c, 0x73, 0x00,
  4269. 0x00, 0x00, 0x00, 0x00,
  4270. 0x00, 0x00, 0x00, 0x00,
  4271. 0x00, 0x00, 0x00, // compressorname
  4272. 0x00, 0x18, // depth = 24
  4273. 0x11, 0x11 // pre_defined = -1
  4274. ]),
  4275. box(types.avcC, new Uint8Array([
  4276. 0x01, // configurationVersion
  4277. track.profileIdc, // AVCProfileIndication
  4278. track.profileCompatibility, // profile_compatibility
  4279. track.levelIdc, // AVCLevelIndication
  4280. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  4281. ].concat(
  4282. [sps.length], // numOfSequenceParameterSets
  4283. sequenceParameterSets, // "SPS"
  4284. [pps.length], // numOfPictureParameterSets
  4285. pictureParameterSets // "PPS"
  4286. ))),
  4287. box(types.btrt, new Uint8Array([
  4288. 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  4289. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  4290. 0x00, 0x2d, 0xc6, 0xc0 // avgBitrate
  4291. ]))
  4292. ];
  4293.  
  4294. if (track.sarRatio) {
  4295. var
  4296. hSpacing = track.sarRatio[0],
  4297. vSpacing = track.sarRatio[1];
  4298.  
  4299. avc1Box.push(
  4300. box(types.pasp, new Uint8Array([
  4301. (hSpacing & 0xFF000000) >> 24,
  4302. (hSpacing & 0xFF0000) >> 16,
  4303. (hSpacing & 0xFF00) >> 8,
  4304. hSpacing & 0xFF,
  4305. (vSpacing & 0xFF000000) >> 24,
  4306. (vSpacing & 0xFF0000) >> 16,
  4307. (vSpacing & 0xFF00) >> 8,
  4308. vSpacing & 0xFF
  4309. ]))
  4310. );
  4311. }
  4312.  
  4313. return box.apply(null, avc1Box);
  4314. };
  4315.  
  4316. audioSample = function(track) {
  4317. return box(types.mp4a, new Uint8Array([
  4318.  
  4319. // SampleEntry, ISO/IEC 14496-12
  4320. 0x00, 0x00, 0x00,
  4321. 0x00, 0x00, 0x00, // reserved
  4322. 0x00, 0x01, // data_reference_index
  4323.  
  4324. // AudioSampleEntry, ISO/IEC 14496-12
  4325. 0x00, 0x00, 0x00, 0x00, // reserved
  4326. 0x00, 0x00, 0x00, 0x00, // reserved
  4327. (track.channelcount & 0xff00) >> 8,
  4328. (track.channelcount & 0xff), // channelcount
  4329.  
  4330. (track.samplesize & 0xff00) >> 8,
  4331. (track.samplesize & 0xff), // samplesize
  4332. 0x00, 0x00, // pre_defined
  4333. 0x00, 0x00, // reserved
  4334.  
  4335. (track.samplerate & 0xff00) >> 8,
  4336. (track.samplerate & 0xff),
  4337. 0x00, 0x00 // samplerate, 16.16
  4338.  
  4339. // MP4AudioSampleEntry, ISO/IEC 14496-14
  4340. ]), esds(track));
  4341. };
  4342. }());
  4343.  
  4344. tkhd = function(track) {
  4345. var result = new Uint8Array([
  4346. 0x00, // version 0
  4347. 0x00, 0x00, 0x07, // flags
  4348. 0x00, 0x00, 0x00, 0x00, // creation_time
  4349. 0x00, 0x00, 0x00, 0x00, // modification_time
  4350. (track.id & 0xFF000000) >> 24,
  4351. (track.id & 0xFF0000) >> 16,
  4352. (track.id & 0xFF00) >> 8,
  4353. track.id & 0xFF, // track_ID
  4354. 0x00, 0x00, 0x00, 0x00, // reserved
  4355. (track.duration & 0xFF000000) >> 24,
  4356. (track.duration & 0xFF0000) >> 16,
  4357. (track.duration & 0xFF00) >> 8,
  4358. track.duration & 0xFF, // duration
  4359. 0x00, 0x00, 0x00, 0x00,
  4360. 0x00, 0x00, 0x00, 0x00, // reserved
  4361. 0x00, 0x00, // layer
  4362. 0x00, 0x00, // alternate_group
  4363. 0x01, 0x00, // non-audio track volume
  4364. 0x00, 0x00, // reserved
  4365. 0x00, 0x01, 0x00, 0x00,
  4366. 0x00, 0x00, 0x00, 0x00,
  4367. 0x00, 0x00, 0x00, 0x00,
  4368. 0x00, 0x00, 0x00, 0x00,
  4369. 0x00, 0x01, 0x00, 0x00,
  4370. 0x00, 0x00, 0x00, 0x00,
  4371. 0x00, 0x00, 0x00, 0x00,
  4372. 0x00, 0x00, 0x00, 0x00,
  4373. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  4374. (track.width & 0xFF00) >> 8,
  4375. track.width & 0xFF,
  4376. 0x00, 0x00, // width
  4377. (track.height & 0xFF00) >> 8,
  4378. track.height & 0xFF,
  4379. 0x00, 0x00 // height
  4380. ]);
  4381.  
  4382. return box(types.tkhd, result);
  4383. };
  4384.  
  4385. /**
  4386. * Generate a track fragment (traf) box. A traf box collects metadata
  4387. * about tracks in a movie fragment (moof) box.
  4388. */
  4389. traf = function(track) {
  4390. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun,
  4391. sampleDependencyTable, dataOffset,
  4392. upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  4393.  
  4394. trackFragmentHeader = box(types.tfhd, new Uint8Array([
  4395. 0x00, // version 0
  4396. 0x00, 0x00, 0x3a, // flags
  4397. (track.id & 0xFF000000) >> 24,
  4398. (track.id & 0xFF0000) >> 16,
  4399. (track.id & 0xFF00) >> 8,
  4400. (track.id & 0xFF), // track_ID
  4401. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  4402. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  4403. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  4404. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  4405. ]));
  4406.  
  4407. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
  4408. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
  4409.  
  4410. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
  4411. 0x01, // version 1
  4412. 0x00, 0x00, 0x00, // flags
  4413. // baseMediaDecodeTime
  4414. (upperWordBaseMediaDecodeTime >>> 24) & 0xFF,
  4415. (upperWordBaseMediaDecodeTime >>> 16) & 0xFF,
  4416. (upperWordBaseMediaDecodeTime >>> 8) & 0xFF,
  4417. upperWordBaseMediaDecodeTime & 0xFF,
  4418. (lowerWordBaseMediaDecodeTime >>> 24) & 0xFF,
  4419. (lowerWordBaseMediaDecodeTime >>> 16) & 0xFF,
  4420. (lowerWordBaseMediaDecodeTime >>> 8) & 0xFF,
  4421. lowerWordBaseMediaDecodeTime & 0xFF
  4422. ]));
  4423.  
  4424. // the data offset specifies the number of bytes from the start of
  4425. // the containing moof to the first payload byte of the associated
  4426. // mdat
  4427. dataOffset = (32 + // tfhd
  4428. 20 + // tfdt
  4429. 8 + // traf header
  4430. 16 + // mfhd
  4431. 8 + // moof header
  4432. 8); // mdat header
  4433.  
  4434. // audio tracks require less metadata
  4435. if (track.type === 'audio') {
  4436. trackFragmentRun = trun(track, dataOffset);
  4437. return box(types.traf,
  4438. trackFragmentHeader,
  4439. trackFragmentDecodeTime,
  4440. trackFragmentRun);
  4441. }
  4442.  
  4443. // video tracks should contain an independent and disposable samples
  4444. // box (sdtp)
  4445. // generate one and adjust offsets to match
  4446. sampleDependencyTable = sdtp(track);
  4447. trackFragmentRun = trun(track,
  4448. sampleDependencyTable.length + dataOffset);
  4449. return box(types.traf,
  4450. trackFragmentHeader,
  4451. trackFragmentDecodeTime,
  4452. trackFragmentRun,
  4453. sampleDependencyTable);
  4454. };
  4455.  
  4456. /**
  4457. * Generate a track box.
  4458. * @param track {object} a track definition
  4459. * @return {Uint8Array} the track box
  4460. */
  4461. trak = function(track) {
  4462. track.duration = track.duration || customDuration;
  4463. return box(types.trak,
  4464. tkhd(track),
  4465. mdia(track));
  4466. };
  4467.  
  4468. trex = function(track) {
  4469. var result = new Uint8Array([
  4470. 0x00, // version 0
  4471. 0x00, 0x00, 0x00, // flags
  4472. (track.id & 0xFF000000) >> 24,
  4473. (track.id & 0xFF0000) >> 16,
  4474. (track.id & 0xFF00) >> 8,
  4475. (track.id & 0xFF), // track_ID
  4476. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  4477. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  4478. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  4479. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  4480. ]);
  4481. // the last two bytes of default_sample_flags is the sample
  4482. // degradation priority, a hint about the importance of this sample
  4483. // relative to others. Lower the degradation priority for all sample
  4484. // types other than video.
  4485. if (track.type !== 'video') {
  4486. result[result.length - 1] = 0x00;
  4487. }
  4488.  
  4489. return box(types.trex, result);
  4490. };
  4491.  
  4492. (function() {
  4493. var audioTrun, videoTrun, trunHeader;
  4494.  
  4495. // This method assumes all samples are uniform. That is, if a
  4496. // duration is present for the first sample, it will be present for
  4497. // all subsequent samples.
  4498. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  4499. trunHeader = function(samples, offset) {
  4500. var durationPresent = 0, sizePresent = 0,
  4501. flagsPresent = 0, compositionTimeOffset = 0;
  4502.  
  4503. // trun flag constants
  4504. if (samples.length) {
  4505. if (samples[0].duration !== undefined) {
  4506. durationPresent = 0x1;
  4507. }
  4508. if (samples[0].size !== undefined) {
  4509. sizePresent = 0x2;
  4510. }
  4511. if (samples[0].flags !== undefined) {
  4512. flagsPresent = 0x4;
  4513. }
  4514. if (samples[0].compositionTimeOffset !== undefined) {
  4515. compositionTimeOffset = 0x8;
  4516. }
  4517. }
  4518.  
  4519. return [
  4520. 0x00, // version 0
  4521. 0x00,
  4522. durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
  4523. 0x01, // flags
  4524. (samples.length & 0xFF000000) >>> 24,
  4525. (samples.length & 0xFF0000) >>> 16,
  4526. (samples.length & 0xFF00) >>> 8,
  4527. samples.length & 0xFF, // sample_count
  4528. (offset & 0xFF000000) >>> 24,
  4529. (offset & 0xFF0000) >>> 16,
  4530. (offset & 0xFF00) >>> 8,
  4531. offset & 0xFF // data_offset
  4532. ];
  4533. };
  4534.  
  4535. videoTrun = function(track, offset) {
  4536. var bytesOffest, bytes, header, samples, sample, i;
  4537.  
  4538. samples = track.samples || [];
  4539. offset += 8 + 12 + (16 * samples.length);
  4540. header = trunHeader(samples, offset);
  4541. bytes = new Uint8Array(header.length + samples.length * 16);
  4542. bytes.set(header);
  4543. bytesOffest = header.length;
  4544.  
  4545. for (i = 0; i < samples.length; i++) {
  4546. sample = samples[i];
  4547.  
  4548. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  4549. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  4550. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  4551. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  4552. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  4553. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  4554. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  4555. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  4556. bytes[bytesOffest++] = (sample.flags.isLeading << 2) | sample.flags.dependsOn;
  4557. bytes[bytesOffest++] = (sample.flags.isDependedOn << 6) |
  4558. (sample.flags.hasRedundancy << 4) |
  4559. (sample.flags.paddingValue << 1) |
  4560. sample.flags.isNonSyncSample;
  4561. bytes[bytesOffest++] = sample.flags.degradationPriority & 0xF0 << 8;
  4562. bytes[bytesOffest++] = sample.flags.degradationPriority & 0x0F; // sample_flags
  4563. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF000000) >>> 24;
  4564. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF0000) >>> 16;
  4565. bytes[bytesOffest++] = (sample.compositionTimeOffset & 0xFF00) >>> 8;
  4566. bytes[bytesOffest++] = sample.compositionTimeOffset & 0xFF; // sample_composition_time_offset
  4567. }
  4568. return box(types.trun, bytes);
  4569. };
  4570.  
  4571. audioTrun = function(track, offset) {
  4572. var bytes, bytesOffest, header, samples, sample, i;
  4573.  
  4574. samples = track.samples || [];
  4575. offset += 8 + 12 + (8 * samples.length);
  4576.  
  4577. header = trunHeader(samples, offset);
  4578. bytes = new Uint8Array(header.length + samples.length * 8);
  4579. bytes.set(header);
  4580. bytesOffest = header.length;
  4581.  
  4582. for (i = 0; i < samples.length; i++) {
  4583. sample = samples[i];
  4584. bytes[bytesOffest++] = (sample.duration & 0xFF000000) >>> 24;
  4585. bytes[bytesOffest++] = (sample.duration & 0xFF0000) >>> 16;
  4586. bytes[bytesOffest++] = (sample.duration & 0xFF00) >>> 8;
  4587. bytes[bytesOffest++] = sample.duration & 0xFF; // sample_duration
  4588. bytes[bytesOffest++] = (sample.size & 0xFF000000) >>> 24;
  4589. bytes[bytesOffest++] = (sample.size & 0xFF0000) >>> 16;
  4590. bytes[bytesOffest++] = (sample.size & 0xFF00) >>> 8;
  4591. bytes[bytesOffest++] = sample.size & 0xFF; // sample_size
  4592. }
  4593.  
  4594. return box(types.trun, bytes);
  4595. };
  4596.  
  4597. trun = function(track, offset) {
  4598. if (track.type === 'audio') {
  4599. return audioTrun(track, offset);
  4600. }
  4601.  
  4602. return videoTrun(track, offset);
  4603. };
  4604. }());
  4605.  
  4606. module.exports = {
  4607. ftyp: ftyp,
  4608. mdat: mdat,
  4609. moof: moof,
  4610. moov: moov,
  4611. setDuration: function(duration) {
  4612. if (duration) {
  4613. customDuration = duration * 90000; // 涔樹互 timescale
  4614. }
  4615. },
  4616. initSegment: function(tracks) {
  4617. var
  4618. fileType = ftyp(),
  4619. movie = moov(tracks),
  4620. result;
  4621.  
  4622. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  4623. result.set(fileType);
  4624. result.set(movie, fileType.byteLength);
  4625. return result;
  4626. }
  4627. };
  4628.  
  4629. },{}],19:[function(require,module,exports){
  4630. var parseType = function(buffer) {
  4631. var result = '';
  4632. result += String.fromCharCode(buffer[0]);
  4633. result += String.fromCharCode(buffer[1]);
  4634. result += String.fromCharCode(buffer[2]);
  4635. result += String.fromCharCode(buffer[3]);
  4636. return result;
  4637. };
  4638.  
  4639.  
  4640. module.exports = parseType;
  4641.  
  4642. },{}],20:[function(require,module,exports){
  4643. /**
  4644. * mux.js
  4645. *
  4646. * Copyright (c) Brightcove
  4647. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4648. *
  4649. * Utilities to detect basic properties and metadata about MP4s.
  4650. */
  4651. 'use strict';
  4652.  
  4653. var toUnsigned = require(28).toUnsigned;
  4654. var toHexString = require(28).toHexString;
  4655. var findBox = require(15);
  4656. var parseType = require(19);
  4657. var parseTfhd = require(26);
  4658. var parseTrun = require(27);
  4659. var parseTfdt = require(25);
  4660. var timescale, startTime, compositionStartTime, getVideoTrackIds, getTracks,
  4661. getTimescaleFromMediaHeader;
  4662.  
  4663. /**
  4664. * Parses an MP4 initialization segment and extracts the timescale
  4665. * values for any declared tracks. Timescale values indicate the
  4666. * number of clock ticks per second to assume for time-based values
  4667. * elsewhere in the MP4.
  4668. *
  4669. * To determine the start time of an MP4, you need two pieces of
  4670. * information: the timescale unit and the earliest base media decode
  4671. * time. Multiple timescales can be specified within an MP4 but the
  4672. * base media decode time is always expressed in the timescale from
  4673. * the media header box for the track:
  4674. * ```
  4675. * moov > trak > mdia > mdhd.timescale
  4676. * ```
  4677. * @param init {Uint8Array} the bytes of the init segment
  4678. * @return {object} a hash of track ids to timescale values or null if
  4679. * the init segment is malformed.
  4680. */
  4681. timescale = function(init) {
  4682. var
  4683. result = {},
  4684. traks = findBox(init, ['moov', 'trak']);
  4685.  
  4686. // mdhd timescale
  4687. return traks.reduce(function(result, trak) {
  4688. var tkhd, version, index, id, mdhd;
  4689.  
  4690. tkhd = findBox(trak, ['tkhd'])[0];
  4691. if (!tkhd) {
  4692. return null;
  4693. }
  4694. version = tkhd[0];
  4695. index = version === 0 ? 12 : 20;
  4696. id = toUnsigned(tkhd[index] << 24 |
  4697. tkhd[index + 1] << 16 |
  4698. tkhd[index + 2] << 8 |
  4699. tkhd[index + 3]);
  4700.  
  4701. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  4702. if (!mdhd) {
  4703. return null;
  4704. }
  4705. version = mdhd[0];
  4706. index = version === 0 ? 12 : 20;
  4707. result[id] = toUnsigned(mdhd[index] << 24 |
  4708. mdhd[index + 1] << 16 |
  4709. mdhd[index + 2] << 8 |
  4710. mdhd[index + 3]);
  4711. return result;
  4712. }, result);
  4713. };
  4714.  
  4715. /**
  4716. * Determine the base media decode start time, in seconds, for an MP4
  4717. * fragment. If multiple fragments are specified, the earliest time is
  4718. * returned.
  4719. *
  4720. * The base media decode time can be parsed from track fragment
  4721. * metadata:
  4722. * ```
  4723. * moof > traf > tfdt.baseMediaDecodeTime
  4724. * ```
  4725. * It requires the timescale value from the mdhd to interpret.
  4726. *
  4727. * @param timescale {object} a hash of track ids to timescale values.
  4728. * @return {number} the earliest base media decode start time for the
  4729. * fragment, in seconds
  4730. */
  4731. startTime = function(timescale, fragment) {
  4732. var trafs, baseTimes, result;
  4733.  
  4734. // we need info from two childrend of each track fragment box
  4735. trafs = findBox(fragment, ['moof', 'traf']);
  4736.  
  4737. // determine the start times for each track
  4738. baseTimes = [].concat.apply([], trafs.map(function(traf) {
  4739. return findBox(traf, ['tfhd']).map(function(tfhd) {
  4740. var id, scale, baseTime;
  4741.  
  4742. // get the track id from the tfhd
  4743. id = toUnsigned(tfhd[4] << 24 |
  4744. tfhd[5] << 16 |
  4745. tfhd[6] << 8 |
  4746. tfhd[7]);
  4747. // assume a 90kHz clock if no timescale was specified
  4748. scale = timescale[id] || 90e3;
  4749.  
  4750. // get the base media decode time from the tfdt
  4751. baseTime = findBox(traf, ['tfdt']).map(function(tfdt) {
  4752. var version, result;
  4753.  
  4754. version = tfdt[0];
  4755. result = toUnsigned(tfdt[4] << 24 |
  4756. tfdt[5] << 16 |
  4757. tfdt[6] << 8 |
  4758. tfdt[7]);
  4759. if (version === 1) {
  4760. result *= Math.pow(2, 32);
  4761. result += toUnsigned(tfdt[8] << 24 |
  4762. tfdt[9] << 16 |
  4763. tfdt[10] << 8 |
  4764. tfdt[11]);
  4765. }
  4766. return result;
  4767. })[0];
  4768. baseTime = baseTime || Infinity;
  4769.  
  4770. // convert base time to seconds
  4771. return baseTime / scale;
  4772. });
  4773. }));
  4774.  
  4775. // return the minimum
  4776. result = Math.min.apply(null, baseTimes);
  4777. return isFinite(result) ? result : 0;
  4778. };
  4779.  
  4780. /**
  4781. * Determine the composition start, in seconds, for an MP4
  4782. * fragment.
  4783. *
  4784. * The composition start time of a fragment can be calculated using the base
  4785. * media decode time, composition time offset, and timescale, as follows:
  4786. *
  4787. * compositionStartTime = (baseMediaDecodeTime + compositionTimeOffset) / timescale
  4788. *
  4789. * All of the aforementioned information is contained within a media fragment's
  4790. * `traf` box, except for timescale info, which comes from the initialization
  4791. * segment, so a track id (also contained within a `traf`) is also necessary to
  4792. * associate it with a timescale
  4793. *
  4794. *
  4795. * @param timescales {object} - a hash of track ids to timescale values.
  4796. * @param fragment {Unit8Array} - the bytes of a media segment
  4797. * @return {number} the composition start time for the fragment, in seconds
  4798. **/
  4799. compositionStartTime = function(timescales, fragment) {
  4800. var trafBoxes = findBox(fragment, ['moof', 'traf']);
  4801. var baseMediaDecodeTime = 0;
  4802. var compositionTimeOffset = 0;
  4803. var trackId;
  4804.  
  4805. if (trafBoxes && trafBoxes.length) {
  4806. // The spec states that track run samples contained within a `traf` box are contiguous, but
  4807. // it does not explicitly state whether the `traf` boxes themselves are contiguous.
  4808. // We will assume that they are, so we only need the first to calculate start time.
  4809. var tfhd = findBox(trafBoxes[0], ['tfhd'])[0];
  4810. var trun = findBox(trafBoxes[0], ['trun'])[0];
  4811. var tfdt = findBox(trafBoxes[0], ['tfdt'])[0];
  4812.  
  4813. if (tfhd) {
  4814. var parsedTfhd = parseTfhd(tfhd);
  4815.  
  4816. trackId = parsedTfhd.trackId;
  4817. }
  4818.  
  4819. if (tfdt) {
  4820. var parsedTfdt = parseTfdt(tfdt);
  4821.  
  4822. baseMediaDecodeTime = parsedTfdt.baseMediaDecodeTime;
  4823. }
  4824.  
  4825. if (trun) {
  4826. var parsedTrun = parseTrun(trun);
  4827.  
  4828. if (parsedTrun.samples && parsedTrun.samples.length) {
  4829. compositionTimeOffset = parsedTrun.samples[0].compositionTimeOffset || 0;
  4830. }
  4831. }
  4832. }
  4833.  
  4834. // Get timescale for this specific track. Assume a 90kHz clock if no timescale was
  4835. // specified.
  4836. var timescale = timescales[trackId] || 90e3;
  4837.  
  4838. // return the composition start time, in seconds
  4839. return (baseMediaDecodeTime + compositionTimeOffset) / timescale;
  4840. };
  4841.  
  4842. /**
  4843. * Find the trackIds of the video tracks in this source.
  4844. * Found by parsing the Handler Reference and Track Header Boxes:
  4845. * moov > trak > mdia > hdlr
  4846. * moov > trak > tkhd
  4847. *
  4848. * @param {Uint8Array} init - The bytes of the init segment for this source
  4849. * @return {Number[]} A list of trackIds
  4850. *
  4851. * @see ISO-BMFF-12/2015, Section 8.4.3
  4852. **/
  4853. getVideoTrackIds = function(init) {
  4854. var traks = findBox(init, ['moov', 'trak']);
  4855. var videoTrackIds = [];
  4856.  
  4857. traks.forEach(function(trak) {
  4858. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  4859. var tkhds = findBox(trak, ['tkhd']);
  4860.  
  4861. hdlrs.forEach(function(hdlr, index) {
  4862. var handlerType = parseType(hdlr.subarray(8, 12));
  4863. var tkhd = tkhds[index];
  4864. var view;
  4865. var version;
  4866. var trackId;
  4867.  
  4868. if (handlerType === 'vide') {
  4869. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  4870. version = view.getUint8(0);
  4871. trackId = (version === 0) ? view.getUint32(12) : view.getUint32(20);
  4872.  
  4873. videoTrackIds.push(trackId);
  4874. }
  4875. });
  4876. });
  4877.  
  4878. return videoTrackIds;
  4879. };
  4880.  
  4881. getTimescaleFromMediaHeader = function(mdhd) {
  4882. // mdhd is a FullBox, meaning it will have its own version as the first byte
  4883. var version = mdhd[0];
  4884. var index = version === 0 ? 12 : 20;
  4885.  
  4886. return toUnsigned(
  4887. mdhd[index] << 24 |
  4888. mdhd[index + 1] << 16 |
  4889. mdhd[index + 2] << 8 |
  4890. mdhd[index + 3]
  4891. );
  4892. };
  4893.  
  4894. /**
  4895. * Get all the video, audio, and hint tracks from a non fragmented
  4896. * mp4 segment
  4897. */
  4898. getTracks = function(init) {
  4899. var traks = findBox(init, ['moov', 'trak']);
  4900. var tracks = [];
  4901.  
  4902. traks.forEach(function(trak) {
  4903. var track = {};
  4904. var tkhd = findBox(trak, ['tkhd'])[0];
  4905. var view, tkhdVersion;
  4906.  
  4907. // id
  4908. if (tkhd) {
  4909. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  4910. tkhdVersion = view.getUint8(0);
  4911.  
  4912. track.id = (tkhdVersion === 0) ? view.getUint32(12) : view.getUint32(20);
  4913. }
  4914.  
  4915. var hdlr = findBox(trak, ['mdia', 'hdlr'])[0];
  4916.  
  4917. // type
  4918. if (hdlr) {
  4919. var type = parseType(hdlr.subarray(8, 12));
  4920.  
  4921. if (type === 'vide') {
  4922. track.type = 'video';
  4923. } else if (type === 'soun') {
  4924. track.type = 'audio';
  4925. } else {
  4926. track.type = type;
  4927. }
  4928. }
  4929.  
  4930.  
  4931. // codec
  4932. var stsd = findBox(trak, ['mdia', 'minf', 'stbl', 'stsd'])[0];
  4933.  
  4934. if (stsd) {
  4935. var sampleDescriptions = stsd.subarray(8);
  4936. // gives the codec type string
  4937. track.codec = parseType(sampleDescriptions.subarray(4, 8));
  4938.  
  4939. var codecBox = findBox(sampleDescriptions, [track.codec])[0];
  4940. var codecConfig, codecConfigType;
  4941.  
  4942. if (codecBox) {
  4943. // https://tools.ietf.org/html/rfc6381#section-3.3
  4944. if ((/^[a-z]vc[1-9]$/i).test(track.codec)) {
  4945. // we don't need anything but the "config" parameter of the
  4946. // avc1 codecBox
  4947. codecConfig = codecBox.subarray(78);
  4948. codecConfigType = parseType(codecConfig.subarray(4, 8));
  4949.  
  4950. if (codecConfigType === 'avcC' && codecConfig.length > 11) {
  4951. track.codec += '.';
  4952.  
  4953. // left padded with zeroes for single digit hex
  4954. // profile idc
  4955. track.codec += toHexString(codecConfig[9]);
  4956. // the byte containing the constraint_set flags
  4957. track.codec += toHexString(codecConfig[10]);
  4958. // level idc
  4959. track.codec += toHexString(codecConfig[11]);
  4960. } else {
  4961. // TODO: show a warning that we couldn't parse the codec
  4962. // and are using the default
  4963. track.codec = 'avc1.4d400d';
  4964. }
  4965. } else if ((/^mp4[a,v]$/i).test(track.codec)) {
  4966. // we do not need anything but the streamDescriptor of the mp4a codecBox
  4967. codecConfig = codecBox.subarray(28);
  4968. codecConfigType = parseType(codecConfig.subarray(4, 8));
  4969.  
  4970. if (codecConfigType === 'esds' && codecConfig.length > 20 && codecConfig[19] !== 0) {
  4971. track.codec += '.' + toHexString(codecConfig[19]);
  4972. // this value is only a single digit
  4973. track.codec += '.' + toHexString((codecConfig[20] >>> 2) & 0x3f).replace(/^0/, '');
  4974. } else {
  4975. // TODO: show a warning that we couldn't parse the codec
  4976. // and are using the default
  4977. track.codec = 'mp4a.40.2';
  4978. }
  4979. } else {
  4980. // TODO: show a warning? for unknown codec type
  4981. }
  4982. }
  4983. }
  4984.  
  4985. var mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  4986.  
  4987. if (mdhd) {
  4988. track.timescale = getTimescaleFromMediaHeader(mdhd);
  4989. }
  4990.  
  4991. tracks.push(track);
  4992. });
  4993.  
  4994. return tracks;
  4995. };
  4996.  
  4997. module.exports = {
  4998. // export mp4 inspector's findBox and parseType for backwards compatibility
  4999. findBox: findBox,
  5000. parseType: parseType,
  5001. timescale: timescale,
  5002. startTime: startTime,
  5003. compositionStartTime: compositionStartTime,
  5004. videoTrackIds: getVideoTrackIds,
  5005. tracks: getTracks,
  5006. getTimescaleFromMediaHeader: getTimescaleFromMediaHeader
  5007. };
  5008.  
  5009. },{"15":15,"19":19,"25":25,"26":26,"27":27,"28":28}],21:[function(require,module,exports){
  5010. /**
  5011. * mux.js
  5012. *
  5013. * Copyright (c) Brightcove
  5014. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5015. */
  5016. var ONE_SECOND_IN_TS = require(29).ONE_SECOND_IN_TS;
  5017.  
  5018. /**
  5019. * Store information about the start and end of the track and the
  5020. * duration for each frame/sample we process in order to calculate
  5021. * the baseMediaDecodeTime
  5022. */
  5023. var collectDtsInfo = function(track, data) {
  5024. if (typeof data.pts === 'number') {
  5025. if (track.timelineStartInfo.pts === undefined) {
  5026. track.timelineStartInfo.pts = data.pts;
  5027. }
  5028.  
  5029. if (track.minSegmentPts === undefined) {
  5030. track.minSegmentPts = data.pts;
  5031. } else {
  5032. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  5033. }
  5034.  
  5035. if (track.maxSegmentPts === undefined) {
  5036. track.maxSegmentPts = data.pts;
  5037. } else {
  5038. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  5039. }
  5040. }
  5041.  
  5042. if (typeof data.dts === 'number') {
  5043. if (track.timelineStartInfo.dts === undefined) {
  5044. track.timelineStartInfo.dts = data.dts;
  5045. }
  5046.  
  5047. if (track.minSegmentDts === undefined) {
  5048. track.minSegmentDts = data.dts;
  5049. } else {
  5050. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  5051. }
  5052.  
  5053. if (track.maxSegmentDts === undefined) {
  5054. track.maxSegmentDts = data.dts;
  5055. } else {
  5056. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  5057. }
  5058. }
  5059. };
  5060.  
  5061. /**
  5062. * Clear values used to calculate the baseMediaDecodeTime between
  5063. * tracks
  5064. */
  5065. var clearDtsInfo = function(track) {
  5066. delete track.minSegmentDts;
  5067. delete track.maxSegmentDts;
  5068. delete track.minSegmentPts;
  5069. delete track.maxSegmentPts;
  5070. };
  5071.  
  5072. /**
  5073. * Calculate the track's baseMediaDecodeTime based on the earliest
  5074. * DTS the transmuxer has ever seen and the minimum DTS for the
  5075. * current track
  5076. * @param track {object} track metadata configuration
  5077. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  5078. * in the source; false to adjust the first segment to start at 0.
  5079. */
  5080. var calculateTrackBaseMediaDecodeTime = function(track, keepOriginalTimestamps) {
  5081. var
  5082. baseMediaDecodeTime,
  5083. scale,
  5084. minSegmentDts = track.minSegmentDts;
  5085.  
  5086. // Optionally adjust the time so the first segment starts at zero.
  5087. if (!keepOriginalTimestamps) {
  5088. minSegmentDts -= track.timelineStartInfo.dts;
  5089. }
  5090.  
  5091. // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  5092. // we want the start of the first segment to be placed
  5093. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;
  5094.  
  5095. // Add to that the distance this segment is from the very first
  5096. baseMediaDecodeTime += minSegmentDts;
  5097.  
  5098. // baseMediaDecodeTime must not become negative
  5099. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  5100.  
  5101. if (track.type === 'audio') {
  5102. // Audio has a different clock equal to the sampling_rate so we need to
  5103. // scale the PTS values into the clock rate of the track
  5104. scale = track.samplerate / ONE_SECOND_IN_TS;
  5105. baseMediaDecodeTime *= scale;
  5106. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  5107. }
  5108.  
  5109. return baseMediaDecodeTime;
  5110. };
  5111.  
  5112. module.exports = {
  5113. clearDtsInfo: clearDtsInfo,
  5114. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  5115. collectDtsInfo: collectDtsInfo
  5116. };
  5117.  
  5118. },{"29":29}],22:[function(require,module,exports){
  5119. /**
  5120. * mux.js
  5121. *
  5122. * Copyright (c) Brightcove
  5123. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5124. *
  5125. * A stream-based mp2t to mp4 converter. This utility can be used to
  5126. * deliver mp4s to a SourceBuffer on platforms that support native
  5127. * Media Source Extensions.
  5128. */
  5129. 'use strict';
  5130.  
  5131. var Stream = require(31);
  5132. var mp4 = require(18);
  5133. var frameUtils = require(16);
  5134. var audioFrameUtils = require(13);
  5135. var trackDecodeInfo = require(21);
  5136. var m2ts = require(9);
  5137. var clock = require(29);
  5138. var AdtsStream = require(3);
  5139. var H264Stream = require(4).H264Stream;
  5140. var AacStream = require(1);
  5141. var isLikelyAacData = require(2).isLikelyAacData;
  5142. var ONE_SECOND_IN_TS = require(29).ONE_SECOND_IN_TS;
  5143. var AUDIO_PROPERTIES = require(5);
  5144. var VIDEO_PROPERTIES = require(6);
  5145.  
  5146. // object types
  5147. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  5148.  
  5149. /**
  5150. * Compare two arrays (even typed) for same-ness
  5151. */
  5152. var arrayEquals = function(a, b) {
  5153. var
  5154. i;
  5155.  
  5156. if (a.length !== b.length) {
  5157. return false;
  5158. }
  5159.  
  5160. // compare the value of each element in the array
  5161. for (i = 0; i < a.length; i++) {
  5162. if (a[i] !== b[i]) {
  5163. return false;
  5164. }
  5165. }
  5166.  
  5167. return true;
  5168. };
  5169.  
  5170. var generateVideoSegmentTimingInfo = function(
  5171. baseMediaDecodeTime,
  5172. startDts,
  5173. startPts,
  5174. endDts,
  5175. endPts,
  5176. prependedContentDuration
  5177. ) {
  5178. var
  5179. ptsOffsetFromDts = startPts - startDts,
  5180. decodeDuration = endDts - startDts,
  5181. presentationDuration = endPts - startPts;
  5182.  
  5183. // The PTS and DTS values are based on the actual stream times from the segment,
  5184. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  5185. // In order to provide relevant values for the player times, base timing info on the
  5186. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  5187. return {
  5188. start: {
  5189. dts: baseMediaDecodeTime,
  5190. pts: baseMediaDecodeTime + ptsOffsetFromDts
  5191. },
  5192. end: {
  5193. dts: baseMediaDecodeTime + decodeDuration,
  5194. pts: baseMediaDecodeTime + presentationDuration
  5195. },
  5196. prependedContentDuration: prependedContentDuration,
  5197. baseMediaDecodeTime: baseMediaDecodeTime
  5198. };
  5199. };
  5200.  
  5201. /**
  5202. * Constructs a single-track, ISO BMFF media segment from AAC data
  5203. * events. The output of this stream can be fed to a SourceBuffer
  5204. * configured with a suitable initialization segment.
  5205. * @param track {object} track metadata configuration
  5206. * @param options {object} transmuxer options object
  5207. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  5208. * in the source; false to adjust the first segment to start at 0.
  5209. */
  5210. AudioSegmentStream = function(track, options) {
  5211. var
  5212. adtsFrames = [],
  5213. sequenceNumber = 0,
  5214. earliestAllowedDts = 0,
  5215. audioAppendStartTs = 0,
  5216. videoBaseMediaDecodeTime = Infinity;
  5217.  
  5218. options = options || {};
  5219.  
  5220. AudioSegmentStream.prototype.init.call(this);
  5221.  
  5222. this.push = function(data) {
  5223. trackDecodeInfo.collectDtsInfo(track, data);
  5224.  
  5225. if (track) {
  5226. AUDIO_PROPERTIES.forEach(function(prop) {
  5227. track[prop] = data[prop];
  5228. });
  5229. }
  5230.  
  5231. // buffer audio data until end() is called
  5232. adtsFrames.push(data);
  5233. };
  5234.  
  5235. this.setEarliestDts = function(earliestDts) {
  5236. earliestAllowedDts = earliestDts;
  5237. };
  5238.  
  5239. this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  5240. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  5241. };
  5242.  
  5243. this.setAudioAppendStart = function(timestamp) {
  5244. audioAppendStartTs = timestamp;
  5245. };
  5246.  
  5247. this.flush = function() {
  5248. var
  5249. frames,
  5250. moof,
  5251. mdat,
  5252. boxes,
  5253. frameDuration;
  5254.  
  5255. // return early if no audio data has been observed
  5256. if (adtsFrames.length === 0) {
  5257. this.trigger('done', 'AudioSegmentStream');
  5258. return;
  5259. }
  5260.  
  5261. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(
  5262. adtsFrames, track, earliestAllowedDts);
  5263. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
  5264. track, options.keepOriginalTimestamps);
  5265.  
  5266. audioFrameUtils.prefixWithSilence(
  5267. track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);
  5268.  
  5269. // we have to build the index from byte locations to
  5270. // samples (that is, adts frames) in the audio data
  5271. track.samples = audioFrameUtils.generateSampleTable(frames);
  5272.  
  5273. // concatenate the audio data to constuct the mdat
  5274. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  5275.  
  5276. adtsFrames = [];
  5277.  
  5278. moof = mp4.moof(sequenceNumber, [track]);
  5279. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  5280.  
  5281. // bump the sequence number for next time
  5282. sequenceNumber++;
  5283.  
  5284. boxes.set(moof);
  5285. boxes.set(mdat, moof.byteLength);
  5286.  
  5287. trackDecodeInfo.clearDtsInfo(track);
  5288.  
  5289. frameDuration = Math.ceil(ONE_SECOND_IN_TS * 1024 / track.samplerate);
  5290.  
  5291. // TODO this check was added to maintain backwards compatibility (particularly with
  5292. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  5293. // valid use-case where an init segment/data should be triggered without associated
  5294. // frames. Leaving for now, but should be looked into.
  5295. if (frames.length) {
  5296. this.trigger('timingInfo', {
  5297. start: frames[0].pts,
  5298. end: frames[0].pts + (frames.length * frameDuration)
  5299. });
  5300. }
  5301. this.trigger('data', {track: track, boxes: boxes});
  5302. this.trigger('done', 'AudioSegmentStream');
  5303. };
  5304.  
  5305. this.reset = function() {
  5306. trackDecodeInfo.clearDtsInfo(track);
  5307. adtsFrames = [];
  5308. this.trigger('reset');
  5309. };
  5310. };
  5311.  
  5312. AudioSegmentStream.prototype = new Stream();
  5313.  
  5314. /**
  5315. * Constructs a single-track, ISO BMFF media segment from H264 data
  5316. * events. The output of this stream can be fed to a SourceBuffer
  5317. * configured with a suitable initialization segment.
  5318. * @param track {object} track metadata configuration
  5319. * @param options {object} transmuxer options object
  5320. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  5321. * gopsToAlignWith list when attempting to align gop pts
  5322. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  5323. * in the source; false to adjust the first segment to start at 0.
  5324. */
  5325. VideoSegmentStream = function(track, options) {
  5326. var
  5327. sequenceNumber = 0,
  5328. nalUnits = [],
  5329. gopsToAlignWith = [],
  5330. config,
  5331. pps;
  5332.  
  5333. options = options || {};
  5334.  
  5335. VideoSegmentStream.prototype.init.call(this);
  5336.  
  5337. delete track.minPTS;
  5338.  
  5339. this.gopCache_ = [];
  5340.  
  5341. /**
  5342. * Constructs a ISO BMFF segment given H264 nalUnits
  5343. * @param {Object} nalUnit A data event representing a nalUnit
  5344. * @param {String} nalUnit.nalUnitType
  5345. * @param {Object} nalUnit.config Properties for a mp4 track
  5346. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  5347. * @see lib/codecs/h264.js
  5348. **/
  5349. this.push = function(nalUnit) {
  5350. trackDecodeInfo.collectDtsInfo(track, nalUnit);
  5351.  
  5352. // record the track config
  5353. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  5354. config = nalUnit.config;
  5355. track.sps = [nalUnit.data];
  5356.  
  5357. VIDEO_PROPERTIES.forEach(function(prop) {
  5358. track[prop] = config[prop];
  5359. }, this);
  5360. }
  5361.  
  5362. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
  5363. !pps) {
  5364. pps = nalUnit.data;
  5365. track.pps = [nalUnit.data];
  5366. }
  5367.  
  5368. // buffer video until flush() is called
  5369. nalUnits.push(nalUnit);
  5370. };
  5371.  
  5372. /**
  5373. * Pass constructed ISO BMFF track and boxes on to the
  5374. * next stream in the pipeline
  5375. **/
  5376. this.flush = function() {
  5377. var
  5378. frames,
  5379. gopForFusion,
  5380. gops,
  5381. moof,
  5382. mdat,
  5383. boxes,
  5384. prependedContentDuration = 0,
  5385. firstGop,
  5386. lastGop;
  5387.  
  5388. // Throw away nalUnits at the start of the byte stream until
  5389. // we find the first AUD
  5390. while (nalUnits.length) {
  5391. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  5392. break;
  5393. }
  5394. nalUnits.shift();
  5395. }
  5396.  
  5397. // Return early if no video data has been observed
  5398. if (nalUnits.length === 0) {
  5399. this.resetStream_();
  5400. this.trigger('done', 'VideoSegmentStream');
  5401. return;
  5402. }
  5403.  
  5404. // Organize the raw nal-units into arrays that represent
  5405. // higher-level constructs such as frames and gops
  5406. // (group-of-pictures)
  5407. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  5408. gops = frameUtils.groupFramesIntoGops(frames);
  5409.  
  5410. // If the first frame of this fragment is not a keyframe we have
  5411. // a problem since MSE (on Chrome) requires a leading keyframe.
  5412. //
  5413. // We have two approaches to repairing this situation:
  5414. // 1) GOP-FUSION:
  5415. // This is where we keep track of the GOPS (group-of-pictures)
  5416. // from previous fragments and attempt to find one that we can
  5417. // prepend to the current fragment in order to create a valid
  5418. // fragment.
  5419. // 2) KEYFRAME-PULLING:
  5420. // Here we search for the first keyframe in the fragment and
  5421. // throw away all the frames between the start of the fragment
  5422. // and that keyframe. We then extend the duration and pull the
  5423. // PTS of the keyframe forward so that it covers the time range
  5424. // of the frames that were disposed of.
  5425. //
  5426. // #1 is far prefereable over #2 which can cause "stuttering" but
  5427. // requires more things to be just right.
  5428. if (!gops[0][0].keyFrame) {
  5429. // Search for a gop for fusion from our gopCache
  5430. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  5431.  
  5432. if (gopForFusion) {
  5433. // in order to provide more accurate timing information about the segment, save
  5434. // the number of seconds prepended to the original segment due to GOP fusion
  5435. prependedContentDuration = gopForFusion.duration;
  5436.  
  5437. gops.unshift(gopForFusion);
  5438. // Adjust Gops' metadata to account for the inclusion of the
  5439. // new gop at the beginning
  5440. gops.byteLength += gopForFusion.byteLength;
  5441. gops.nalCount += gopForFusion.nalCount;
  5442. gops.pts = gopForFusion.pts;
  5443. gops.dts = gopForFusion.dts;
  5444. gops.duration += gopForFusion.duration;
  5445. } else {
  5446. // If we didn't find a candidate gop fall back to keyframe-pulling
  5447. gops = frameUtils.extendFirstKeyFrame(gops);
  5448. }
  5449. }
  5450.  
  5451. // Trim gops to align with gopsToAlignWith
  5452. if (gopsToAlignWith.length) {
  5453. var alignedGops;
  5454.  
  5455. if (options.alignGopsAtEnd) {
  5456. alignedGops = this.alignGopsAtEnd_(gops);
  5457. } else {
  5458. alignedGops = this.alignGopsAtStart_(gops);
  5459. }
  5460.  
  5461. if (!alignedGops) {
  5462. // save all the nals in the last GOP into the gop cache
  5463. this.gopCache_.unshift({
  5464. gop: gops.pop(),
  5465. pps: track.pps,
  5466. sps: track.sps
  5467. });
  5468.  
  5469. // Keep a maximum of 6 GOPs in the cache
  5470. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  5471.  
  5472. // Clear nalUnits
  5473. nalUnits = [];
  5474.  
  5475. // return early no gops can be aligned with desired gopsToAlignWith
  5476. this.resetStream_();
  5477. this.trigger('done', 'VideoSegmentStream');
  5478. return;
  5479. }
  5480.  
  5481. // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  5482. // when recalculated before sending off to CoalesceStream
  5483. trackDecodeInfo.clearDtsInfo(track);
  5484.  
  5485. gops = alignedGops;
  5486. }
  5487.  
  5488. trackDecodeInfo.collectDtsInfo(track, gops);
  5489.  
  5490. // First, we have to build the index from byte locations to
  5491. // samples (that is, frames) in the video data
  5492. track.samples = frameUtils.generateSampleTable(gops);
  5493.  
  5494. // Concatenate the video data and construct the mdat
  5495. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  5496.  
  5497. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
  5498. track, options.keepOriginalTimestamps);
  5499.  
  5500. this.trigger('processedGopsInfo', gops.map(function(gop) {
  5501. return {
  5502. pts: gop.pts,
  5503. dts: gop.dts,
  5504. byteLength: gop.byteLength
  5505. };
  5506. }));
  5507.  
  5508. firstGop = gops[0];
  5509. lastGop = gops[gops.length - 1];
  5510.  
  5511. this.trigger(
  5512. 'segmentTimingInfo',
  5513. generateVideoSegmentTimingInfo(
  5514. track.baseMediaDecodeTime,
  5515. firstGop.dts,
  5516. firstGop.pts,
  5517. lastGop.dts + lastGop.duration,
  5518. lastGop.pts + lastGop.duration,
  5519. prependedContentDuration));
  5520.  
  5521. this.trigger('timingInfo', {
  5522. start: gops[0].pts,
  5523. end: gops[gops.length - 1].pts + gops[gops.length - 1].duration
  5524. });
  5525.  
  5526. // save all the nals in the last GOP into the gop cache
  5527. this.gopCache_.unshift({
  5528. gop: gops.pop(),
  5529. pps: track.pps,
  5530. sps: track.sps
  5531. });
  5532.  
  5533. // Keep a maximum of 6 GOPs in the cache
  5534. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  5535.  
  5536. // Clear nalUnits
  5537. nalUnits = [];
  5538.  
  5539. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  5540. this.trigger('timelineStartInfo', track.timelineStartInfo);
  5541.  
  5542. moof = mp4.moof(sequenceNumber, [track]);
  5543.  
  5544. // it would be great to allocate this array up front instead of
  5545. // throwing away hundreds of media segment fragments
  5546. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  5547.  
  5548. // Bump the sequence number for next time
  5549. sequenceNumber++;
  5550.  
  5551. boxes.set(moof);
  5552. boxes.set(mdat, moof.byteLength);
  5553.  
  5554. this.trigger('data', {track: track, boxes: boxes});
  5555.  
  5556. this.resetStream_();
  5557.  
  5558. // Continue with the flush process now
  5559. this.trigger('done', 'VideoSegmentStream');
  5560. };
  5561.  
  5562. this.reset = function() {
  5563. this.resetStream_();
  5564. nalUnits = [];
  5565. this.gopCache_.length = 0;
  5566. gopsToAlignWith.length = 0;
  5567. this.trigger('reset');
  5568. };
  5569.  
  5570. this.resetStream_ = function() {
  5571. trackDecodeInfo.clearDtsInfo(track);
  5572.  
  5573. // reset config and pps because they may differ across segments
  5574. // for instance, when we are rendition switching
  5575. config = undefined;
  5576. pps = undefined;
  5577. };
  5578.  
  5579. // Search for a candidate Gop for gop-fusion from the gop cache and
  5580. // return it or return null if no good candidate was found
  5581. this.getGopForFusion_ = function(nalUnit) {
  5582. var
  5583. halfSecond = 45000, // Half-a-second in a 90khz clock
  5584. allowableOverlap = 10000, // About 3 frames @ 30fps
  5585. nearestDistance = Infinity,
  5586. dtsDistance,
  5587. nearestGopObj,
  5588. currentGop,
  5589. currentGopObj,
  5590. i;
  5591.  
  5592. // Search for the GOP nearest to the beginning of this nal unit
  5593. for (i = 0; i < this.gopCache_.length; i++) {
  5594. currentGopObj = this.gopCache_[i];
  5595. currentGop = currentGopObj.gop;
  5596.  
  5597. // Reject Gops with different SPS or PPS
  5598. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
  5599. !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  5600. continue;
  5601. }
  5602.  
  5603. // Reject Gops that would require a negative baseMediaDecodeTime
  5604. if (currentGop.dts < track.timelineStartInfo.dts) {
  5605. continue;
  5606. }
  5607.  
  5608. // The distance between the end of the gop and the start of the nalUnit
  5609. dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;
  5610.  
  5611. // Only consider GOPS that start before the nal unit and end within
  5612. // a half-second of the nal unit
  5613. if (dtsDistance >= -allowableOverlap &&
  5614. dtsDistance <= halfSecond) {
  5615.  
  5616. // Always use the closest GOP we found if there is more than
  5617. // one candidate
  5618. if (!nearestGopObj ||
  5619. nearestDistance > dtsDistance) {
  5620. nearestGopObj = currentGopObj;
  5621. nearestDistance = dtsDistance;
  5622. }
  5623. }
  5624. }
  5625.  
  5626. if (nearestGopObj) {
  5627. return nearestGopObj.gop;
  5628. }
  5629. return null;
  5630. };
  5631.  
  5632. // trim gop list to the first gop found that has a matching pts with a gop in the list
  5633. // of gopsToAlignWith starting from the START of the list
  5634. this.alignGopsAtStart_ = function(gops) {
  5635. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  5636.  
  5637. byteLength = gops.byteLength;
  5638. nalCount = gops.nalCount;
  5639. duration = gops.duration;
  5640. alignIndex = gopIndex = 0;
  5641.  
  5642. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  5643. align = gopsToAlignWith[alignIndex];
  5644. gop = gops[gopIndex];
  5645.  
  5646. if (align.pts === gop.pts) {
  5647. break;
  5648. }
  5649.  
  5650. if (gop.pts > align.pts) {
  5651. // this current gop starts after the current gop we want to align on, so increment
  5652. // align index
  5653. alignIndex++;
  5654. continue;
  5655. }
  5656.  
  5657. // current gop starts before the current gop we want to align on. so increment gop
  5658. // index
  5659. gopIndex++;
  5660. byteLength -= gop.byteLength;
  5661. nalCount -= gop.nalCount;
  5662. duration -= gop.duration;
  5663. }
  5664.  
  5665. if (gopIndex === 0) {
  5666. // no gops to trim
  5667. return gops;
  5668. }
  5669.  
  5670. if (gopIndex === gops.length) {
  5671. // all gops trimmed, skip appending all gops
  5672. return null;
  5673. }
  5674.  
  5675. alignedGops = gops.slice(gopIndex);
  5676. alignedGops.byteLength = byteLength;
  5677. alignedGops.duration = duration;
  5678. alignedGops.nalCount = nalCount;
  5679. alignedGops.pts = alignedGops[0].pts;
  5680. alignedGops.dts = alignedGops[0].dts;
  5681.  
  5682. return alignedGops;
  5683. };
  5684.  
  5685. // trim gop list to the first gop found that has a matching pts with a gop in the list
  5686. // of gopsToAlignWith starting from the END of the list
  5687. this.alignGopsAtEnd_ = function(gops) {
  5688. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  5689.  
  5690. alignIndex = gopsToAlignWith.length - 1;
  5691. gopIndex = gops.length - 1;
  5692. alignEndIndex = null;
  5693. matchFound = false;
  5694.  
  5695. while (alignIndex >= 0 && gopIndex >= 0) {
  5696. align = gopsToAlignWith[alignIndex];
  5697. gop = gops[gopIndex];
  5698.  
  5699. if (align.pts === gop.pts) {
  5700. matchFound = true;
  5701. break;
  5702. }
  5703.  
  5704. if (align.pts > gop.pts) {
  5705. alignIndex--;
  5706. continue;
  5707. }
  5708.  
  5709. if (alignIndex === gopsToAlignWith.length - 1) {
  5710. // gop.pts is greater than the last alignment candidate. If no match is found
  5711. // by the end of this loop, we still want to append gops that come after this
  5712. // point
  5713. alignEndIndex = gopIndex;
  5714. }
  5715.  
  5716. gopIndex--;
  5717. }
  5718.  
  5719. if (!matchFound && alignEndIndex === null) {
  5720. return null;
  5721. }
  5722.  
  5723. var trimIndex;
  5724.  
  5725. if (matchFound) {
  5726. trimIndex = gopIndex;
  5727. } else {
  5728. trimIndex = alignEndIndex;
  5729. }
  5730.  
  5731. if (trimIndex === 0) {
  5732. return gops;
  5733. }
  5734.  
  5735. var alignedGops = gops.slice(trimIndex);
  5736. var metadata = alignedGops.reduce(function(total, gop) {
  5737. total.byteLength += gop.byteLength;
  5738. total.duration += gop.duration;
  5739. total.nalCount += gop.nalCount;
  5740. return total;
  5741. }, { byteLength: 0, duration: 0, nalCount: 0 });
  5742.  
  5743. alignedGops.byteLength = metadata.byteLength;
  5744. alignedGops.duration = metadata.duration;
  5745. alignedGops.nalCount = metadata.nalCount;
  5746. alignedGops.pts = alignedGops[0].pts;
  5747. alignedGops.dts = alignedGops[0].dts;
  5748.  
  5749. return alignedGops;
  5750. };
  5751.  
  5752. this.alignGopsWith = function(newGopsToAlignWith) {
  5753. gopsToAlignWith = newGopsToAlignWith;
  5754. };
  5755. };
  5756.  
  5757. VideoSegmentStream.prototype = new Stream();
  5758.  
  5759. /**
  5760. * A Stream that can combine multiple streams (ie. audio & video)
  5761. * into a single output segment for MSE. Also supports audio-only
  5762. * and video-only streams.
  5763. * @param options {object} transmuxer options object
  5764. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  5765. * in the source; false to adjust the first segment to start at media timeline start.
  5766. */
  5767. CoalesceStream = function(options, metadataStream) {
  5768. // Number of Tracks per output segment
  5769. // If greater than 1, we combine multiple
  5770. // tracks into a single segment
  5771. this.numberOfTracks = 0;
  5772. this.metadataStream = metadataStream;
  5773.  
  5774. options = options || {};
  5775.  
  5776. if (typeof options.remux !== 'undefined') {
  5777. this.remuxTracks = !!options.remux;
  5778. } else {
  5779. this.remuxTracks = true;
  5780. }
  5781.  
  5782. if (typeof options.keepOriginalTimestamps === 'boolean') {
  5783. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  5784. } else {
  5785. this.keepOriginalTimestamps = false;
  5786. }
  5787.  
  5788. this.pendingTracks = [];
  5789. this.videoTrack = null;
  5790. this.pendingBoxes = [];
  5791. this.pendingCaptions = [];
  5792. this.pendingMetadata = [];
  5793. this.pendingBytes = 0;
  5794. this.emittedTracks = 0;
  5795.  
  5796. CoalesceStream.prototype.init.call(this);
  5797.  
  5798. // Take output from multiple
  5799. this.push = function(output) {
  5800. // buffer incoming captions until the associated video segment
  5801. // finishes
  5802. if (output.text) {
  5803. return this.pendingCaptions.push(output);
  5804. }
  5805. // buffer incoming id3 tags until the final flush
  5806. if (output.frames) {
  5807. return this.pendingMetadata.push(output);
  5808. }
  5809.  
  5810. // Add this track to the list of pending tracks and store
  5811. // important information required for the construction of
  5812. // the final segment
  5813. this.pendingTracks.push(output.track);
  5814. this.pendingBytes += output.boxes.byteLength;
  5815.  
  5816. // TODO: is there an issue for this against chrome?
  5817. // We unshift audio and push video because
  5818. // as of Chrome 75 when switching from
  5819. // one init segment to another if the video
  5820. // mdat does not appear after the audio mdat
  5821. // only audio will play for the duration of our transmux.
  5822. if (output.track.type === 'video') {
  5823. this.videoTrack = output.track;
  5824. this.pendingBoxes.push(output.boxes);
  5825. }
  5826. if (output.track.type === 'audio') {
  5827. this.audioTrack = output.track;
  5828. this.pendingBoxes.unshift(output.boxes);
  5829. }
  5830. };
  5831. };
  5832.  
  5833. CoalesceStream.prototype = new Stream();
  5834. CoalesceStream.prototype.flush = function(flushSource) {
  5835. var
  5836. offset = 0,
  5837. event = {
  5838. captions: [],
  5839. captionStreams: {},
  5840. metadata: [],
  5841. info: {}
  5842. },
  5843. caption,
  5844. id3,
  5845. initSegment,
  5846. timelineStartPts = 0,
  5847. i;
  5848.  
  5849. if (this.pendingTracks.length < this.numberOfTracks) {
  5850. if (flushSource !== 'VideoSegmentStream' &&
  5851. flushSource !== 'AudioSegmentStream') {
  5852. // Return because we haven't received a flush from a data-generating
  5853. // portion of the segment (meaning that we have only recieved meta-data
  5854. // or captions.)
  5855. return;
  5856. } else if (this.remuxTracks) {
  5857. // Return until we have enough tracks from the pipeline to remux (if we
  5858. // are remuxing audio and video into a single MP4)
  5859. return;
  5860. } else if (this.pendingTracks.length === 0) {
  5861. // In the case where we receive a flush without any data having been
  5862. // received we consider it an emitted track for the purposes of coalescing
  5863. // `done` events.
  5864. // We do this for the case where there is an audio and video track in the
  5865. // segment but no audio data. (seen in several playlists with alternate
  5866. // audio tracks and no audio present in the main TS segments.)
  5867. this.emittedTracks++;
  5868.  
  5869. if (this.emittedTracks >= this.numberOfTracks) {
  5870. this.trigger('done');
  5871. this.emittedTracks = 0;
  5872. }
  5873. return;
  5874. }
  5875. }
  5876.  
  5877. if (this.videoTrack) {
  5878. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  5879. VIDEO_PROPERTIES.forEach(function(prop) {
  5880. event.info[prop] = this.videoTrack[prop];
  5881. }, this);
  5882. } else if (this.audioTrack) {
  5883. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  5884. AUDIO_PROPERTIES.forEach(function(prop) {
  5885. event.info[prop] = this.audioTrack[prop];
  5886. }, this);
  5887. }
  5888.  
  5889. if (this.videoTrack || this.audioTrack) {
  5890. if (this.pendingTracks.length === 1) {
  5891. event.type = this.pendingTracks[0].type;
  5892. } else {
  5893. event.type = 'combined';
  5894. }
  5895.  
  5896. this.emittedTracks += this.pendingTracks.length;
  5897.  
  5898. initSegment = mp4.initSegment(this.pendingTracks);
  5899.  
  5900. // Create a new typed array to hold the init segment
  5901. event.initSegment = new Uint8Array(initSegment.byteLength);
  5902.  
  5903. // Create an init segment containing a moov
  5904. // and track definitions
  5905. event.initSegment.set(initSegment);
  5906.  
  5907. // Create a new typed array to hold the moof+mdats
  5908. event.data = new Uint8Array(this.pendingBytes);
  5909.  
  5910. // Append each moof+mdat (one per track) together
  5911. for (i = 0; i < this.pendingBoxes.length; i++) {
  5912. event.data.set(this.pendingBoxes[i], offset);
  5913. offset += this.pendingBoxes[i].byteLength;
  5914. }
  5915.  
  5916. // Translate caption PTS times into second offsets to match the
  5917. // video timeline for the segment, and add track info
  5918. for (i = 0; i < this.pendingCaptions.length; i++) {
  5919. caption = this.pendingCaptions[i];
  5920. caption.startTime = clock.metadataTsToSeconds(
  5921. caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  5922. caption.endTime = clock.metadataTsToSeconds(
  5923. caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  5924.  
  5925. event.captionStreams[caption.stream] = true;
  5926. event.captions.push(caption);
  5927. }
  5928.  
  5929. // Translate ID3 frame PTS times into second offsets to match the
  5930. // video timeline for the segment
  5931. for (i = 0; i < this.pendingMetadata.length; i++) {
  5932. id3 = this.pendingMetadata[i];
  5933. id3.cueTime = clock.metadataTsToSeconds(
  5934. id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  5935.  
  5936. event.metadata.push(id3);
  5937. }
  5938.  
  5939. // We add this to every single emitted segment even though we only need
  5940. // it for the first
  5941. event.metadata.dispatchType = this.metadataStream.dispatchType;
  5942.  
  5943. // Reset stream state
  5944. this.pendingTracks.length = 0;
  5945. this.videoTrack = null;
  5946. this.pendingBoxes.length = 0;
  5947. this.pendingCaptions.length = 0;
  5948. this.pendingBytes = 0;
  5949. this.pendingMetadata.length = 0;
  5950.  
  5951. // Emit the built segment
  5952. // We include captions and ID3 tags for backwards compatibility,
  5953. // ideally we should send only video and audio in the data event
  5954. this.trigger('data', event);
  5955. // Emit each caption to the outside world
  5956. // Ideally, this would happen immediately on parsing captions,
  5957. // but we need to ensure that video data is sent back first
  5958. // so that caption timing can be adjusted to match video timing
  5959. for (i = 0; i < event.captions.length; i++) {
  5960. caption = event.captions[i];
  5961.  
  5962. this.trigger('caption', caption);
  5963. }
  5964. // Emit each id3 tag to the outside world
  5965. // Ideally, this would happen immediately on parsing the tag,
  5966. // but we need to ensure that video data is sent back first
  5967. // so that ID3 frame timing can be adjusted to match video timing
  5968. for (i = 0; i < event.metadata.length; i++) {
  5969. id3 = event.metadata[i];
  5970.  
  5971. this.trigger('id3Frame', id3);
  5972. }
  5973. }
  5974.  
  5975. // Only emit `done` if all tracks have been flushed and emitted
  5976. if (this.emittedTracks >= this.numberOfTracks) {
  5977. this.trigger('done');
  5978. this.emittedTracks = 0;
  5979. }
  5980. };
  5981.  
  5982. CoalesceStream.prototype.setRemux = function(val) {
  5983. this.remuxTracks = val;
  5984. };
  5985. /**
  5986. * A Stream that expects MP2T binary data as input and produces
  5987. * corresponding media segments, suitable for use with Media Source
  5988. * Extension (MSE) implementations that support the ISO BMFF byte
  5989. * stream format, like Chrome.
  5990. */
  5991. Transmuxer = function(options) {
  5992. var
  5993. self = this,
  5994. hasFlushed = true,
  5995. videoTrack,
  5996. audioTrack;
  5997.  
  5998. Transmuxer.prototype.init.call(this);
  5999.  
  6000. options = options || {};
  6001. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  6002. this.transmuxPipeline_ = {};
  6003. mp4.setDuration(options.duration)
  6004.  
  6005. this.setupAacPipeline = function() {
  6006. var pipeline = {};
  6007. this.transmuxPipeline_ = pipeline;
  6008.  
  6009. pipeline.type = 'aac';
  6010. pipeline.metadataStream = new m2ts.MetadataStream();
  6011.  
  6012. // set up the parsing pipeline
  6013. pipeline.aacStream = new AacStream();
  6014. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  6015. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  6016. pipeline.adtsStream = new AdtsStream();
  6017. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  6018. pipeline.headOfPipeline = pipeline.aacStream;
  6019.  
  6020. pipeline.aacStream
  6021. .pipe(pipeline.audioTimestampRolloverStream)
  6022. .pipe(pipeline.adtsStream);
  6023. pipeline.aacStream
  6024. .pipe(pipeline.timedMetadataTimestampRolloverStream)
  6025. .pipe(pipeline.metadataStream)
  6026. .pipe(pipeline.coalesceStream);
  6027.  
  6028. pipeline.metadataStream.on('timestamp', function(frame) {
  6029. pipeline.aacStream.setTimestamp(frame.timeStamp);
  6030. });
  6031.  
  6032. pipeline.aacStream.on('data', function(data) {
  6033. if ((data.type !== 'timed-metadata' && data.type !== 'audio') || pipeline.audioSegmentStream) {
  6034. return;
  6035. }
  6036.  
  6037. audioTrack = audioTrack || {
  6038. timelineStartInfo: {
  6039. baseMediaDecodeTime: self.baseMediaDecodeTime
  6040. },
  6041. codec: 'adts',
  6042. type: 'audio'
  6043. };
  6044. // hook up the audio segment stream to the first track with aac data
  6045. pipeline.coalesceStream.numberOfTracks++;
  6046. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  6047.  
  6048. pipeline.audioSegmentStream.on('timingInfo',
  6049. self.trigger.bind(self, 'audioTimingInfo'));
  6050.  
  6051. // Set up the final part of the audio pipeline
  6052. pipeline.adtsStream
  6053. .pipe(pipeline.audioSegmentStream)
  6054. .pipe(pipeline.coalesceStream);
  6055.  
  6056. // emit pmt info
  6057. self.trigger('trackinfo', {
  6058. hasAudio: !!audioTrack,
  6059. hasVideo: !!videoTrack
  6060. });
  6061. });
  6062.  
  6063. // Re-emit any data coming from the coalesce stream to the outside world
  6064. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  6065. // Let the consumer know we have finished flushing the entire pipeline
  6066. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  6067. };
  6068.  
  6069. this.setupTsPipeline = function() {
  6070. var pipeline = {};
  6071. this.transmuxPipeline_ = pipeline;
  6072.  
  6073. pipeline.type = 'ts';
  6074. pipeline.metadataStream = new m2ts.MetadataStream();
  6075.  
  6076. // set up the parsing pipeline
  6077. pipeline.packetStream = new m2ts.TransportPacketStream();
  6078. pipeline.parseStream = new m2ts.TransportParseStream();
  6079. pipeline.elementaryStream = new m2ts.ElementaryStream();
  6080. pipeline.timestampRolloverStream = new m2ts.TimestampRolloverStream();
  6081. pipeline.adtsStream = new AdtsStream();
  6082. pipeline.h264Stream = new H264Stream();
  6083. pipeline.captionStream = new m2ts.CaptionStream();
  6084. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  6085. pipeline.headOfPipeline = pipeline.packetStream;
  6086.  
  6087. // disassemble MPEG2-TS packets into elementary streams
  6088. pipeline.packetStream
  6089. .pipe(pipeline.parseStream)
  6090. .pipe(pipeline.elementaryStream)
  6091. .pipe(pipeline.timestampRolloverStream);
  6092.  
  6093. // !!THIS ORDER IS IMPORTANT!!
  6094. // demux the streams
  6095. pipeline.timestampRolloverStream
  6096. .pipe(pipeline.h264Stream);
  6097.  
  6098. pipeline.timestampRolloverStream
  6099. .pipe(pipeline.adtsStream);
  6100.  
  6101. pipeline.timestampRolloverStream
  6102. .pipe(pipeline.metadataStream)
  6103. .pipe(pipeline.coalesceStream);
  6104.  
  6105. // Hook up CEA-608/708 caption stream
  6106. pipeline.h264Stream.pipe(pipeline.captionStream)
  6107. .pipe(pipeline.coalesceStream);
  6108.  
  6109. pipeline.elementaryStream.on('data', function(data) {
  6110. var i;
  6111.  
  6112. if (data.type === 'metadata') {
  6113. i = data.tracks.length;
  6114.  
  6115. // scan the tracks listed in the metadata
  6116. while (i--) {
  6117. if (!videoTrack && data.tracks[i].type === 'video') {
  6118. videoTrack = data.tracks[i];
  6119. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  6120. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  6121. audioTrack = data.tracks[i];
  6122. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  6123. }
  6124. }
  6125.  
  6126. // hook up the video segment stream to the first track with h264 data
  6127. if (videoTrack && !pipeline.videoSegmentStream) {
  6128. pipeline.coalesceStream.numberOfTracks++;
  6129. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  6130.  
  6131. pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo) {
  6132. // When video emits timelineStartInfo data after a flush, we forward that
  6133. // info to the AudioSegmentStream, if it exists, because video timeline
  6134. // data takes precedence. Do not do this if keepOriginalTimestamps is set,
  6135. // because this is a particularly subtle form of timestamp alteration.
  6136. if (audioTrack && !options.keepOriginalTimestamps) {
  6137. audioTrack.timelineStartInfo = timelineStartInfo;
  6138. // On the first segment we trim AAC frames that exist before the
  6139. // very earliest DTS we have seen in video because Chrome will
  6140. // interpret any video track with a baseMediaDecodeTime that is
  6141. // non-zero as a gap.
  6142. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts - self.baseMediaDecodeTime);
  6143. }
  6144. });
  6145.  
  6146. pipeline.videoSegmentStream.on('processedGopsInfo',
  6147. self.trigger.bind(self, 'gopInfo'));
  6148. pipeline.videoSegmentStream.on('segmentTimingInfo',
  6149. self.trigger.bind(self, 'videoSegmentTimingInfo'));
  6150.  
  6151. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function(baseMediaDecodeTime) {
  6152. if (audioTrack) {
  6153. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  6154. }
  6155. });
  6156.  
  6157. pipeline.videoSegmentStream.on('timingInfo',
  6158. self.trigger.bind(self, 'videoTimingInfo'));
  6159.  
  6160. // Set up the final part of the video pipeline
  6161. pipeline.h264Stream
  6162. .pipe(pipeline.videoSegmentStream)
  6163. .pipe(pipeline.coalesceStream);
  6164. }
  6165.  
  6166. if (audioTrack && !pipeline.audioSegmentStream) {
  6167. // hook up the audio segment stream to the first track with aac data
  6168. pipeline.coalesceStream.numberOfTracks++;
  6169. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  6170.  
  6171. pipeline.audioSegmentStream.on('timingInfo',
  6172. self.trigger.bind(self, 'audioTimingInfo'));
  6173.  
  6174. // Set up the final part of the audio pipeline
  6175. pipeline.adtsStream
  6176. .pipe(pipeline.audioSegmentStream)
  6177. .pipe(pipeline.coalesceStream);
  6178. }
  6179.  
  6180. // emit pmt info
  6181. self.trigger('trackinfo', {
  6182. hasAudio: !!audioTrack,
  6183. hasVideo: !!videoTrack
  6184. });
  6185. }
  6186. });
  6187.  
  6188. // Re-emit any data coming from the coalesce stream to the outside world
  6189. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  6190. pipeline.coalesceStream.on('id3Frame', function(id3Frame) {
  6191. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  6192.  
  6193. self.trigger('id3Frame', id3Frame);
  6194. });
  6195. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption'));
  6196. // Let the consumer know we have finished flushing the entire pipeline
  6197. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  6198. };
  6199.  
  6200. // hook up the segment streams once track metadata is delivered
  6201. this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  6202. var pipeline = this.transmuxPipeline_;
  6203.  
  6204. if (!options.keepOriginalTimestamps) {
  6205. this.baseMediaDecodeTime = baseMediaDecodeTime;
  6206. }
  6207.  
  6208. if (audioTrack) {
  6209. audioTrack.timelineStartInfo.dts = undefined;
  6210. audioTrack.timelineStartInfo.pts = undefined;
  6211. trackDecodeInfo.clearDtsInfo(audioTrack);
  6212. if (pipeline.audioTimestampRolloverStream) {
  6213. pipeline.audioTimestampRolloverStream.discontinuity();
  6214. }
  6215. }
  6216. if (videoTrack) {
  6217. if (pipeline.videoSegmentStream) {
  6218. pipeline.videoSegmentStream.gopCache_ = [];
  6219. }
  6220. videoTrack.timelineStartInfo.dts = undefined;
  6221. videoTrack.timelineStartInfo.pts = undefined;
  6222. trackDecodeInfo.clearDtsInfo(videoTrack);
  6223. pipeline.captionStream.reset();
  6224. }
  6225.  
  6226. if (pipeline.timestampRolloverStream) {
  6227. pipeline.timestampRolloverStream.discontinuity();
  6228. }
  6229. };
  6230.  
  6231. this.setAudioAppendStart = function(timestamp) {
  6232. if (audioTrack) {
  6233. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  6234. }
  6235. };
  6236.  
  6237. this.setRemux = function(val) {
  6238. var pipeline = this.transmuxPipeline_;
  6239.  
  6240. options.remux = val;
  6241.  
  6242. if (pipeline && pipeline.coalesceStream) {
  6243. pipeline.coalesceStream.setRemux(val);
  6244. }
  6245. };
  6246.  
  6247. this.alignGopsWith = function(gopsToAlignWith) {
  6248. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  6249. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  6250. }
  6251. };
  6252.  
  6253. // feed incoming data to the front of the parsing pipeline
  6254. this.push = function(data) {
  6255. if (hasFlushed) {
  6256. var isAac = isLikelyAacData(data);
  6257.  
  6258. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  6259. this.setupAacPipeline();
  6260. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  6261. this.setupTsPipeline();
  6262. }
  6263. hasFlushed = false;
  6264. }
  6265. this.transmuxPipeline_.headOfPipeline.push(data);
  6266. };
  6267.  
  6268. // flush any buffered data
  6269. this.flush = function() {
  6270. hasFlushed = true;
  6271. // Start at the top of the pipeline and flush all pending work
  6272. this.transmuxPipeline_.headOfPipeline.flush();
  6273. };
  6274.  
  6275. this.endTimeline = function() {
  6276. this.transmuxPipeline_.headOfPipeline.endTimeline();
  6277. };
  6278.  
  6279. this.reset = function() {
  6280. if (this.transmuxPipeline_.headOfPipeline) {
  6281. this.transmuxPipeline_.headOfPipeline.reset();
  6282. }
  6283. };
  6284.  
  6285. // Caption data has to be reset when seeking outside buffered range
  6286. this.resetCaptions = function() {
  6287. if (this.transmuxPipeline_.captionStream) {
  6288. this.transmuxPipeline_.captionStream.reset();
  6289. }
  6290. };
  6291.  
  6292. };
  6293. Transmuxer.prototype = new Stream();
  6294.  
  6295. module.exports = {
  6296. Transmuxer: Transmuxer,
  6297. VideoSegmentStream: VideoSegmentStream,
  6298. AudioSegmentStream: AudioSegmentStream,
  6299. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  6300. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  6301. // exported for testing
  6302. generateVideoSegmentTimingInfo: generateVideoSegmentTimingInfo
  6303. };
  6304.  
  6305. },{"1":1,"13":13,"16":16,"18":18,"2":2,"21":21,"29":29,"3":3,"31":31,"4":4,"5":5,"6":6,"9":9}],23:[function(require,module,exports){
  6306. /**
  6307. * mux.js
  6308. *
  6309. * Copyright (c) Brightcove
  6310. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6311. *
  6312. * Reads in-band caption information from a video elementary
  6313. * stream. Captions must follow the CEA-708 standard for injection
  6314. * into an MPEG-2 transport streams.
  6315. * @see https://en.wikipedia.org/wiki/CEA-708
  6316. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  6317. */
  6318.  
  6319. 'use strict';
  6320.  
  6321. // Supplemental enhancement information (SEI) NAL units have a
  6322. // payload type field to indicate how they are to be
  6323. // interpreted. CEAS-708 caption content is always transmitted with
  6324. // payload type 0x04.
  6325. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  6326. RBSP_TRAILING_BITS = 128;
  6327.  
  6328. /**
  6329. * Parse a supplemental enhancement information (SEI) NAL unit.
  6330. * Stops parsing once a message of type ITU T T35 has been found.
  6331. *
  6332. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  6333. * @return {object} the parsed SEI payload
  6334. * @see Rec. ITU-T H.264, 7.3.2.3.1
  6335. */
  6336. var parseSei = function(bytes) {
  6337. var
  6338. i = 0,
  6339. result = {
  6340. payloadType: -1,
  6341. payloadSize: 0
  6342. },
  6343. payloadType = 0,
  6344. payloadSize = 0;
  6345.  
  6346. // go through the sei_rbsp parsing each each individual sei_message
  6347. while (i < bytes.byteLength) {
  6348. // stop once we have hit the end of the sei_rbsp
  6349. if (bytes[i] === RBSP_TRAILING_BITS) {
  6350. break;
  6351. }
  6352.  
  6353. // Parse payload type
  6354. while (bytes[i] === 0xFF) {
  6355. payloadType += 255;
  6356. i++;
  6357. }
  6358. payloadType += bytes[i++];
  6359.  
  6360. // Parse payload size
  6361. while (bytes[i] === 0xFF) {
  6362. payloadSize += 255;
  6363. i++;
  6364. }
  6365. payloadSize += bytes[i++];
  6366.  
  6367. // this sei_message is a 608/708 caption so save it and break
  6368. // there can only ever be one caption message in a frame's sei
  6369. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  6370. var userIdentifier = String.fromCharCode(
  6371. bytes[i + 3],
  6372. bytes[i + 4],
  6373. bytes[i + 5],
  6374. bytes[i + 6]);
  6375.  
  6376. if (userIdentifier === 'GA94') {
  6377. result.payloadType = payloadType;
  6378. result.payloadSize = payloadSize;
  6379. result.payload = bytes.subarray(i, i + payloadSize);
  6380. break;
  6381. } else {
  6382. result.payload = void 0;
  6383. }
  6384. }
  6385.  
  6386. // skip the payload and parse the next message
  6387. i += payloadSize;
  6388. payloadType = 0;
  6389. payloadSize = 0;
  6390. }
  6391.  
  6392. return result;
  6393. };
  6394.  
  6395. // see ANSI/SCTE 128-1 (2013), section 8.1
  6396. var parseUserData = function(sei) {
  6397. // itu_t_t35_contry_code must be 181 (United States) for
  6398. // captions
  6399. if (sei.payload[0] !== 181) {
  6400. return null;
  6401. }
  6402.  
  6403. // itu_t_t35_provider_code should be 49 (ATSC) for captions
  6404. if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) {
  6405. return null;
  6406. }
  6407.  
  6408. // the user_identifier should be "GA94" to indicate ATSC1 data
  6409. if (String.fromCharCode(sei.payload[3],
  6410. sei.payload[4],
  6411. sei.payload[5],
  6412. sei.payload[6]) !== 'GA94') {
  6413. return null;
  6414. }
  6415.  
  6416. // finally, user_data_type_code should be 0x03 for caption data
  6417. if (sei.payload[7] !== 0x03) {
  6418. return null;
  6419. }
  6420.  
  6421. // return the user_data_type_structure and strip the trailing
  6422. // marker bits
  6423. return sei.payload.subarray(8, sei.payload.length - 1);
  6424. };
  6425.  
  6426. // see CEA-708-D, section 4.4
  6427. var parseCaptionPackets = function(pts, userData) {
  6428. var results = [], i, count, offset, data;
  6429.  
  6430. // if this is just filler, return immediately
  6431. if (!(userData[0] & 0x40)) {
  6432. return results;
  6433. }
  6434.  
  6435. // parse out the cc_data_1 and cc_data_2 fields
  6436. count = userData[0] & 0x1f;
  6437. for (i = 0; i < count; i++) {
  6438. offset = i * 3;
  6439. data = {
  6440. type: userData[offset + 2] & 0x03,
  6441. pts: pts
  6442. };
  6443.  
  6444. // capture cc data when cc_valid is 1
  6445. if (userData[offset + 2] & 0x04) {
  6446. data.ccData = (userData[offset + 3] << 8) | userData[offset + 4];
  6447. results.push(data);
  6448. }
  6449. }
  6450. return results;
  6451. };
  6452.  
  6453. var discardEmulationPreventionBytes = function(data) {
  6454. var
  6455. length = data.byteLength,
  6456. emulationPreventionBytesPositions = [],
  6457. i = 1,
  6458. newLength, newData;
  6459.  
  6460. // Find all `Emulation Prevention Bytes`
  6461. while (i < length - 2) {
  6462. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  6463. emulationPreventionBytesPositions.push(i + 2);
  6464. i += 2;
  6465. } else {
  6466. i++;
  6467. }
  6468. }
  6469.  
  6470. // If no Emulation Prevention Bytes were found just return the original
  6471. // array
  6472. if (emulationPreventionBytesPositions.length === 0) {
  6473. return data;
  6474. }
  6475.  
  6476. // Create a new array to hold the NAL unit data
  6477. newLength = length - emulationPreventionBytesPositions.length;
  6478. newData = new Uint8Array(newLength);
  6479. var sourceIndex = 0;
  6480.  
  6481. for (i = 0; i < newLength; sourceIndex++, i++) {
  6482. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  6483. // Skip this byte
  6484. sourceIndex++;
  6485. // Remove this position index
  6486. emulationPreventionBytesPositions.shift();
  6487. }
  6488. newData[i] = data[sourceIndex];
  6489. }
  6490.  
  6491. return newData;
  6492. };
  6493.  
  6494. // exports
  6495. module.exports = {
  6496. parseSei: parseSei,
  6497. parseUserData: parseUserData,
  6498. parseCaptionPackets: parseCaptionPackets,
  6499. discardEmulationPreventionBytes: discardEmulationPreventionBytes,
  6500. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  6501. };
  6502.  
  6503. },{}],24:[function(require,module,exports){
  6504. var parseSampleFlags = function(flags) {
  6505. return {
  6506. isLeading: (flags[0] & 0x0c) >>> 2,
  6507. dependsOn: flags[0] & 0x03,
  6508. isDependedOn: (flags[1] & 0xc0) >>> 6,
  6509. hasRedundancy: (flags[1] & 0x30) >>> 4,
  6510. paddingValue: (flags[1] & 0x0e) >>> 1,
  6511. isNonSyncSample: flags[1] & 0x01,
  6512. degradationPriority: (flags[2] << 8) | flags[3]
  6513. };
  6514. };
  6515.  
  6516. module.exports = parseSampleFlags;
  6517.  
  6518. },{}],25:[function(require,module,exports){
  6519. var toUnsigned = require(28).toUnsigned;
  6520.  
  6521. var tfdt = function(data) {
  6522. var result = {
  6523. version: data[0],
  6524. flags: new Uint8Array(data.subarray(1, 4)),
  6525. baseMediaDecodeTime: toUnsigned(data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7])
  6526. };
  6527. if (result.version === 1) {
  6528. result.baseMediaDecodeTime *= Math.pow(2, 32);
  6529. result.baseMediaDecodeTime += toUnsigned(data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11]);
  6530. }
  6531. return result;
  6532. };
  6533.  
  6534. module.exports = tfdt;
  6535.  
  6536.  
  6537. },{"28":28}],26:[function(require,module,exports){
  6538. var tfhd = function(data) {
  6539. var
  6540. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  6541. result = {
  6542. version: data[0],
  6543. flags: new Uint8Array(data.subarray(1, 4)),
  6544. trackId: view.getUint32(4)
  6545. },
  6546. baseDataOffsetPresent = result.flags[2] & 0x01,
  6547. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  6548. defaultSampleDurationPresent = result.flags[2] & 0x08,
  6549. defaultSampleSizePresent = result.flags[2] & 0x10,
  6550. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  6551. durationIsEmpty = result.flags[0] & 0x010000,
  6552. defaultBaseIsMoof = result.flags[0] & 0x020000,
  6553. i;
  6554.  
  6555. i = 8;
  6556. if (baseDataOffsetPresent) {
  6557. i += 4; // truncate top 4 bytes
  6558. // FIXME: should we read the full 64 bits?
  6559. result.baseDataOffset = view.getUint32(12);
  6560. i += 4;
  6561. }
  6562. if (sampleDescriptionIndexPresent) {
  6563. result.sampleDescriptionIndex = view.getUint32(i);
  6564. i += 4;
  6565. }
  6566. if (defaultSampleDurationPresent) {
  6567. result.defaultSampleDuration = view.getUint32(i);
  6568. i += 4;
  6569. }
  6570. if (defaultSampleSizePresent) {
  6571. result.defaultSampleSize = view.getUint32(i);
  6572. i += 4;
  6573. }
  6574. if (defaultSampleFlagsPresent) {
  6575. result.defaultSampleFlags = view.getUint32(i);
  6576. }
  6577. if (durationIsEmpty) {
  6578. result.durationIsEmpty = true;
  6579. }
  6580. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  6581. result.baseDataOffsetIsMoof = true;
  6582. }
  6583. return result;
  6584. };
  6585.  
  6586. module.exports = tfhd;
  6587.  
  6588. },{}],27:[function(require,module,exports){
  6589. var parseSampleFlags = require(24);
  6590.  
  6591. var trun = function(data) {
  6592. var
  6593. result = {
  6594. version: data[0],
  6595. flags: new Uint8Array(data.subarray(1, 4)),
  6596. samples: []
  6597. },
  6598. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  6599. // Flag interpretation
  6600. dataOffsetPresent = result.flags[2] & 0x01, // compare with 2nd byte of 0x1
  6601. firstSampleFlagsPresent = result.flags[2] & 0x04, // compare with 2nd byte of 0x4
  6602. sampleDurationPresent = result.flags[1] & 0x01, // compare with 2nd byte of 0x100
  6603. sampleSizePresent = result.flags[1] & 0x02, // compare with 2nd byte of 0x200
  6604. sampleFlagsPresent = result.flags[1] & 0x04, // compare with 2nd byte of 0x400
  6605. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08, // compare with 2nd byte of 0x800
  6606. sampleCount = view.getUint32(4),
  6607. offset = 8,
  6608. sample;
  6609.  
  6610. if (dataOffsetPresent) {
  6611. // 32 bit signed integer
  6612. result.dataOffset = view.getInt32(offset);
  6613. offset += 4;
  6614. }
  6615.  
  6616. // Overrides the flags for the first sample only. The order of
  6617. // optional values will be: duration, size, compositionTimeOffset
  6618. if (firstSampleFlagsPresent && sampleCount) {
  6619. sample = {
  6620. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  6621. };
  6622. offset += 4;
  6623. if (sampleDurationPresent) {
  6624. sample.duration = view.getUint32(offset);
  6625. offset += 4;
  6626. }
  6627. if (sampleSizePresent) {
  6628. sample.size = view.getUint32(offset);
  6629. offset += 4;
  6630. }
  6631. if (sampleCompositionTimeOffsetPresent) {
  6632. if (result.version === 1) {
  6633. sample.compositionTimeOffset = view.getInt32(offset);
  6634. } else {
  6635. sample.compositionTimeOffset = view.getUint32(offset);
  6636. }
  6637. offset += 4;
  6638. }
  6639. result.samples.push(sample);
  6640. sampleCount--;
  6641. }
  6642.  
  6643. while (sampleCount--) {
  6644. sample = {};
  6645. if (sampleDurationPresent) {
  6646. sample.duration = view.getUint32(offset);
  6647. offset += 4;
  6648. }
  6649. if (sampleSizePresent) {
  6650. sample.size = view.getUint32(offset);
  6651. offset += 4;
  6652. }
  6653. if (sampleFlagsPresent) {
  6654. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  6655. offset += 4;
  6656. }
  6657. if (sampleCompositionTimeOffsetPresent) {
  6658. if (result.version === 1) {
  6659. sample.compositionTimeOffset = view.getInt32(offset);
  6660. } else {
  6661. sample.compositionTimeOffset = view.getUint32(offset);
  6662. }
  6663. offset += 4;
  6664. }
  6665. result.samples.push(sample);
  6666. }
  6667. return result;
  6668. };
  6669.  
  6670. module.exports = trun;
  6671.  
  6672. },{"24":24}],28:[function(require,module,exports){
  6673. /**
  6674. * mux.js
  6675. *
  6676. * Copyright (c) Brightcove
  6677. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6678. */
  6679. var toUnsigned = function(value) {
  6680. return value >>> 0;
  6681. };
  6682.  
  6683. var toHexString = function(value) {
  6684. return ('00' + value.toString(16)).slice(-2);
  6685. };
  6686.  
  6687. module.exports = {
  6688. toUnsigned: toUnsigned,
  6689. toHexString: toHexString
  6690. };
  6691.  
  6692. },{}],29:[function(require,module,exports){
  6693. /**
  6694. * mux.js
  6695. *
  6696. * Copyright (c) Brightcove
  6697. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6698. */
  6699. var
  6700. ONE_SECOND_IN_TS = 90000, // 90kHz clock
  6701. secondsToVideoTs,
  6702. secondsToAudioTs,
  6703. videoTsToSeconds,
  6704. audioTsToSeconds,
  6705. audioTsToVideoTs,
  6706. videoTsToAudioTs,
  6707. metadataTsToSeconds;
  6708.  
  6709. secondsToVideoTs = function(seconds) {
  6710. return seconds * ONE_SECOND_IN_TS;
  6711. };
  6712.  
  6713. secondsToAudioTs = function(seconds, sampleRate) {
  6714. return seconds * sampleRate;
  6715. };
  6716.  
  6717. videoTsToSeconds = function(timestamp) {
  6718. return timestamp / ONE_SECOND_IN_TS;
  6719. };
  6720.  
  6721. audioTsToSeconds = function(timestamp, sampleRate) {
  6722. return timestamp / sampleRate;
  6723. };
  6724.  
  6725. audioTsToVideoTs = function(timestamp, sampleRate) {
  6726. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  6727. };
  6728.  
  6729. videoTsToAudioTs = function(timestamp, sampleRate) {
  6730. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  6731. };
  6732.  
  6733. /**
  6734. * Adjust ID3 tag or caption timing information by the timeline pts values
  6735. * (if keepOriginalTimestamps is false) and convert to seconds
  6736. */
  6737. metadataTsToSeconds = function(timestamp, timelineStartPts, keepOriginalTimestamps) {
  6738. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  6739. };
  6740.  
  6741. module.exports = {
  6742. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  6743. secondsToVideoTs: secondsToVideoTs,
  6744. secondsToAudioTs: secondsToAudioTs,
  6745. videoTsToSeconds: videoTsToSeconds,
  6746. audioTsToSeconds: audioTsToSeconds,
  6747. audioTsToVideoTs: audioTsToVideoTs,
  6748. videoTsToAudioTs: videoTsToAudioTs,
  6749. metadataTsToSeconds: metadataTsToSeconds
  6750. };
  6751.  
  6752. },{}],30:[function(require,module,exports){
  6753. /**
  6754. * mux.js
  6755. *
  6756. * Copyright (c) Brightcove
  6757. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6758. */
  6759. 'use strict';
  6760.  
  6761. var ExpGolomb;
  6762.  
  6763. /**
  6764. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  6765. * scheme used by h264.
  6766. */
  6767. ExpGolomb = function(workingData) {
  6768. var
  6769. // the number of bytes left to examine in workingData
  6770. workingBytesAvailable = workingData.byteLength,
  6771.  
  6772. // the current word being examined
  6773. workingWord = 0, // :uint
  6774.  
  6775. // the number of bits left to examine in the current word
  6776. workingBitsAvailable = 0; // :uint;
  6777.  
  6778. // ():uint
  6779. this.length = function() {
  6780. return (8 * workingBytesAvailable);
  6781. };
  6782.  
  6783. // ():uint
  6784. this.bitsAvailable = function() {
  6785. return (8 * workingBytesAvailable) + workingBitsAvailable;
  6786. };
  6787.  
  6788. // ():void
  6789. this.loadWord = function() {
  6790. var
  6791. position = workingData.byteLength - workingBytesAvailable,
  6792. workingBytes = new Uint8Array(4),
  6793. availableBytes = Math.min(4, workingBytesAvailable);
  6794.  
  6795. if (availableBytes === 0) {
  6796. throw new Error('no bytes available');
  6797. }
  6798.  
  6799. workingBytes.set(workingData.subarray(position,
  6800. position + availableBytes));
  6801. workingWord = new DataView(workingBytes.buffer).getUint32(0);
  6802.  
  6803. // track the amount of workingData that has been processed
  6804. workingBitsAvailable = availableBytes * 8;
  6805. workingBytesAvailable -= availableBytes;
  6806. };
  6807.  
  6808. // (count:int):void
  6809. this.skipBits = function(count) {
  6810. var skipBytes; // :int
  6811. if (workingBitsAvailable > count) {
  6812. workingWord <<= count;
  6813. workingBitsAvailable -= count;
  6814. } else {
  6815. count -= workingBitsAvailable;
  6816. skipBytes = Math.floor(count / 8);
  6817.  
  6818. count -= (skipBytes * 8);
  6819. workingBytesAvailable -= skipBytes;
  6820.  
  6821. this.loadWord();
  6822.  
  6823. workingWord <<= count;
  6824. workingBitsAvailable -= count;
  6825. }
  6826. };
  6827.  
  6828. // (size:int):uint
  6829. this.readBits = function(size) {
  6830. var
  6831. bits = Math.min(workingBitsAvailable, size), // :uint
  6832. valu = workingWord >>> (32 - bits); // :uint
  6833. // if size > 31, handle error
  6834. workingBitsAvailable -= bits;
  6835. if (workingBitsAvailable > 0) {
  6836. workingWord <<= bits;
  6837. } else if (workingBytesAvailable > 0) {
  6838. this.loadWord();
  6839. }
  6840.  
  6841. bits = size - bits;
  6842. if (bits > 0) {
  6843. return valu << bits | this.readBits(bits);
  6844. }
  6845. return valu;
  6846. };
  6847.  
  6848. // ():uint
  6849. this.skipLeadingZeros = function() {
  6850. var leadingZeroCount; // :uint
  6851. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  6852. if ((workingWord & (0x80000000 >>> leadingZeroCount)) !== 0) {
  6853. // the first bit of working word is 1
  6854. workingWord <<= leadingZeroCount;
  6855. workingBitsAvailable -= leadingZeroCount;
  6856. return leadingZeroCount;
  6857. }
  6858. }
  6859.  
  6860. // we exhausted workingWord and still have not found a 1
  6861. this.loadWord();
  6862. return leadingZeroCount + this.skipLeadingZeros();
  6863. };
  6864.  
  6865. // ():void
  6866. this.skipUnsignedExpGolomb = function() {
  6867. this.skipBits(1 + this.skipLeadingZeros());
  6868. };
  6869.  
  6870. // ():void
  6871. this.skipExpGolomb = function() {
  6872. this.skipBits(1 + this.skipLeadingZeros());
  6873. };
  6874.  
  6875. // ():uint
  6876. this.readUnsignedExpGolomb = function() {
  6877. var clz = this.skipLeadingZeros(); // :uint
  6878. return this.readBits(clz + 1) - 1;
  6879. };
  6880.  
  6881. // ():int
  6882. this.readExpGolomb = function() {
  6883. var valu = this.readUnsignedExpGolomb(); // :int
  6884. if (0x01 & valu) {
  6885. // the number is odd if the low order bit is set
  6886. return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
  6887. }
  6888. return -1 * (valu >>> 1); // divide by two then make it negative
  6889. };
  6890.  
  6891. // Some convenience functions
  6892. // :Boolean
  6893. this.readBoolean = function() {
  6894. return this.readBits(1) === 1;
  6895. };
  6896.  
  6897. // ():int
  6898. this.readUnsignedByte = function() {
  6899. return this.readBits(8);
  6900. };
  6901.  
  6902. this.loadWord();
  6903. };
  6904.  
  6905. module.exports = ExpGolomb;
  6906.  
  6907. },{}],31:[function(require,module,exports){
  6908. /**
  6909. * mux.js
  6910. *
  6911. * Copyright (c) Brightcove
  6912. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6913. *
  6914. * A lightweight readable stream implemention that handles event dispatching.
  6915. * Objects that inherit from streams should call init in their constructors.
  6916. */
  6917. 'use strict';
  6918.  
  6919. var Stream = function() {
  6920. this.init = function() {
  6921. var listeners = {};
  6922. /**
  6923. * Add a listener for a specified event type.
  6924. * @param type {string} the event name
  6925. * @param listener {function} the callback to be invoked when an event of
  6926. * the specified type occurs
  6927. */
  6928. this.on = function(type, listener) {
  6929. if (!listeners[type]) {
  6930. listeners[type] = [];
  6931. }
  6932. listeners[type] = listeners[type].concat(listener);
  6933. };
  6934. /**
  6935. * Remove a listener for a specified event type.
  6936. * @param type {string} the event name
  6937. * @param listener {function} a function previously registered for this
  6938. * type of event through `on`
  6939. */
  6940. this.off = function(type, listener) {
  6941. var index;
  6942. if (!listeners[type]) {
  6943. return false;
  6944. }
  6945. index = listeners[type].indexOf(listener);
  6946. listeners[type] = listeners[type].slice();
  6947. listeners[type].splice(index, 1);
  6948. return index > -1;
  6949. };
  6950. /**
  6951. * Trigger an event of the specified type on this stream. Any additional
  6952. * arguments to this function are passed as parameters to event listeners.
  6953. * @param type {string} the event name
  6954. */
  6955. this.trigger = function(type) {
  6956. var callbacks, i, length, args;
  6957. callbacks = listeners[type];
  6958. if (!callbacks) {
  6959. return;
  6960. }
  6961. // Slicing the arguments on every invocation of this method
  6962. // can add a significant amount of overhead. Avoid the
  6963. // intermediate object creation for the common case of a
  6964. // single callback argument
  6965. if (arguments.length === 2) {
  6966. length = callbacks.length;
  6967. for (i = 0; i < length; ++i) {
  6968. callbacks[i].call(this, arguments[1]);
  6969. }
  6970. } else {
  6971. args = [];
  6972. i = arguments.length;
  6973. for (i = 1; i < arguments.length; ++i) {
  6974. args.push(arguments[i]);
  6975. }
  6976. length = callbacks.length;
  6977. for (i = 0; i < length; ++i) {
  6978. callbacks[i].apply(this, args);
  6979. }
  6980. }
  6981. };
  6982. /**
  6983. * Destroys the stream and cleans up.
  6984. */
  6985. this.dispose = function() {
  6986. listeners = {};
  6987. };
  6988. };
  6989. };
  6990.  
  6991. /**
  6992. * Forwards all `data` events on this stream to the destination stream. The
  6993. * destination stream should provide a method `push` to receive the data
  6994. * events as they arrive.
  6995. * @param destination {stream} the stream that will receive all `data` events
  6996. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  6997. * when the current stream emits a 'done' event
  6998. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  6999. */
  7000. Stream.prototype.pipe = function(destination) {
  7001. this.on('data', function(data) {
  7002. destination.push(data);
  7003. });
  7004.  
  7005. this.on('done', function(flushSource) {
  7006. destination.flush(flushSource);
  7007. });
  7008.  
  7009. this.on('partialdone', function(flushSource) {
  7010. destination.partialFlush(flushSource);
  7011. });
  7012.  
  7013. this.on('endedtimeline', function(flushSource) {
  7014. destination.endTimeline(flushSource);
  7015. });
  7016.  
  7017. this.on('reset', function(flushSource) {
  7018. destination.reset(flushSource);
  7019. });
  7020.  
  7021. return destination;
  7022. };
  7023.  
  7024. // Default stream functions that are expected to be overridden to perform
  7025. // actual work. These are provided by the prototype as a sort of no-op
  7026. // implementation so that we don't have to check for their existence in the
  7027. // `pipe` function above.
  7028. Stream.prototype.push = function(data) {
  7029. this.trigger('data', data);
  7030. };
  7031.  
  7032. Stream.prototype.flush = function(flushSource) {
  7033. this.trigger('done', flushSource);
  7034. };
  7035.  
  7036. Stream.prototype.partialFlush = function(flushSource) {
  7037. this.trigger('partialdone', flushSource);
  7038. };
  7039.  
  7040. Stream.prototype.endTimeline = function(flushSource) {
  7041. this.trigger('endedtimeline', flushSource);
  7042. };
  7043.  
  7044. Stream.prototype.reset = function(flushSource) {
  7045. this.trigger('reset', flushSource);
  7046. };
  7047.  
  7048. module.exports = Stream;
  7049.  
  7050. },{}]},{},[17])(17)
  7051. });

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址