muxmp4

tt

此脚本不应直接安装。它是供其他脚本使用的外部库,要使用该库请加入元指令 // @require https://update.gf.qytechs.cn/scripts/386217/709239/muxmp4.js

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

QingJ © 2025

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