mux

test

此脚本不应直接安装,它是一个供其他脚本使用的外部库。如果您需要使用该库,请在脚本元属性加入:// @require https://update.cn-greasyfork.org/scripts/386194/709235/mux.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(40);
  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,"40":40}],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(40);
  317. var ONE_SECOND_IN_TS = require(38).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. },{"38":38,"40":40}],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(40);
  475. var ExpGolomb = require(39);
  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. },{"39":39,"40":40}],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. module.exports = {
  958. Adts: require(3),
  959. h264: require(4)
  960. };
  961.  
  962. },{"3":3,"4":4}],6:[function(require,module,exports){
  963. /**
  964. * mux.js
  965. *
  966. * Copyright (c) Brightcove
  967. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  968. */
  969. var highPrefix = [33, 16, 5, 32, 164, 27];
  970. var lowPrefix = [33, 65, 108, 84, 1, 2, 4, 8, 168, 2, 4, 8, 17, 191, 252];
  971. var zeroFill = function(count) {
  972. var a = [];
  973. while (count--) {
  974. a.push(0);
  975. }
  976. return a;
  977. };
  978.  
  979. var makeTable = function(metaTable) {
  980. return Object.keys(metaTable).reduce(function(obj, key) {
  981. obj[key] = new Uint8Array(metaTable[key].reduce(function(arr, part) {
  982. return arr.concat(part);
  983. }, []));
  984. return obj;
  985. }, {});
  986. };
  987.  
  988. // Frames-of-silence to use for filling in missing AAC frames
  989. var coneOfSilence = {
  990. 96000: [highPrefix, [227, 64], zeroFill(154), [56]],
  991. 88200: [highPrefix, [231], zeroFill(170), [56]],
  992. 64000: [highPrefix, [248, 192], zeroFill(240), [56]],
  993. 48000: [highPrefix, [255, 192], zeroFill(268), [55, 148, 128], zeroFill(54), [112]],
  994. 44100: [highPrefix, [255, 192], zeroFill(268), [55, 163, 128], zeroFill(84), [112]],
  995. 32000: [highPrefix, [255, 192], zeroFill(268), [55, 234], zeroFill(226), [112]],
  996. 24000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 112], zeroFill(126), [224]],
  997. 16000: [highPrefix, [255, 192], zeroFill(268), [55, 255, 128], zeroFill(268), [111, 255], zeroFill(269), [223, 108], zeroFill(195), [1, 192]],
  998. 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]],
  999. 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]],
  1000. 8000: [lowPrefix, zeroFill(268), [3, 121, 16], zeroFill(47), [7]]
  1001. };
  1002.  
  1003. module.exports = makeTable(coneOfSilence);
  1004.  
  1005. },{}],7:[function(require,module,exports){
  1006. /**
  1007. * mux.js
  1008. *
  1009. * Copyright (c) Brightcove
  1010. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1011. */
  1012. 'use strict';
  1013.  
  1014. var Stream = require(40);
  1015.  
  1016. /**
  1017. * The final stage of the transmuxer that emits the flv tags
  1018. * for audio, video, and metadata. Also tranlates in time and
  1019. * outputs caption data and id3 cues.
  1020. */
  1021. var CoalesceStream = function(options) {
  1022. // Number of Tracks per output segment
  1023. // If greater than 1, we combine multiple
  1024. // tracks into a single segment
  1025. this.numberOfTracks = 0;
  1026. this.metadataStream = options.metadataStream;
  1027.  
  1028. this.videoTags = [];
  1029. this.audioTags = [];
  1030. this.videoTrack = null;
  1031. this.audioTrack = null;
  1032. this.pendingCaptions = [];
  1033. this.pendingMetadata = [];
  1034. this.pendingTracks = 0;
  1035. this.processedTracks = 0;
  1036.  
  1037. CoalesceStream.prototype.init.call(this);
  1038.  
  1039. // Take output from multiple
  1040. this.push = function(output) {
  1041. // buffer incoming captions until the associated video segment
  1042. // finishes
  1043. if (output.text) {
  1044. return this.pendingCaptions.push(output);
  1045. }
  1046. // buffer incoming id3 tags until the final flush
  1047. if (output.frames) {
  1048. return this.pendingMetadata.push(output);
  1049. }
  1050.  
  1051. if (output.track.type === 'video') {
  1052. this.videoTrack = output.track;
  1053. this.videoTags = output.tags;
  1054. this.pendingTracks++;
  1055. }
  1056. if (output.track.type === 'audio') {
  1057. this.audioTrack = output.track;
  1058. this.audioTags = output.tags;
  1059. this.pendingTracks++;
  1060. }
  1061. };
  1062. };
  1063.  
  1064. CoalesceStream.prototype = new Stream();
  1065. CoalesceStream.prototype.flush = function(flushSource) {
  1066. var
  1067. id3,
  1068. caption,
  1069. i,
  1070. timelineStartPts,
  1071. event = {
  1072. tags: {},
  1073. captions: [],
  1074. captionStreams: {},
  1075. metadata: []
  1076. };
  1077.  
  1078. if (this.pendingTracks < this.numberOfTracks) {
  1079. if (flushSource !== 'VideoSegmentStream' &&
  1080. flushSource !== 'AudioSegmentStream') {
  1081. // Return because we haven't received a flush from a data-generating
  1082. // portion of the segment (meaning that we have only recieved meta-data
  1083. // or captions.)
  1084. return;
  1085. } else if (this.pendingTracks === 0) {
  1086. // In the case where we receive a flush without any data having been
  1087. // received we consider it an emitted track for the purposes of coalescing
  1088. // `done` events.
  1089. // We do this for the case where there is an audio and video track in the
  1090. // segment but no audio data. (seen in several playlists with alternate
  1091. // audio tracks and no audio present in the main TS segments.)
  1092. this.processedTracks++;
  1093.  
  1094. if (this.processedTracks < this.numberOfTracks) {
  1095. return;
  1096. }
  1097. }
  1098. }
  1099.  
  1100. this.processedTracks += this.pendingTracks;
  1101. this.pendingTracks = 0;
  1102.  
  1103. if (this.processedTracks < this.numberOfTracks) {
  1104. return;
  1105. }
  1106.  
  1107. if (this.videoTrack) {
  1108. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  1109. } else if (this.audioTrack) {
  1110. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  1111. }
  1112.  
  1113. event.tags.videoTags = this.videoTags;
  1114. event.tags.audioTags = this.audioTags;
  1115.  
  1116. // Translate caption PTS times into second offsets into the
  1117. // video timeline for the segment, and add track info
  1118. for (i = 0; i < this.pendingCaptions.length; i++) {
  1119. caption = this.pendingCaptions[i];
  1120. caption.startTime = caption.startPts - timelineStartPts;
  1121. caption.startTime /= 90e3;
  1122. caption.endTime = caption.endPts - timelineStartPts;
  1123. caption.endTime /= 90e3;
  1124. event.captionStreams[caption.stream] = true;
  1125. event.captions.push(caption);
  1126. }
  1127.  
  1128. // Translate ID3 frame PTS times into second offsets into the
  1129. // video timeline for the segment
  1130. for (i = 0; i < this.pendingMetadata.length; i++) {
  1131. id3 = this.pendingMetadata[i];
  1132. id3.cueTime = id3.pts - timelineStartPts;
  1133. id3.cueTime /= 90e3;
  1134. event.metadata.push(id3);
  1135. }
  1136. // We add this to every single emitted segment even though we only need
  1137. // it for the first
  1138. event.metadata.dispatchType = this.metadataStream.dispatchType;
  1139.  
  1140. // Reset stream state
  1141. this.videoTrack = null;
  1142. this.audioTrack = null;
  1143. this.videoTags = [];
  1144. this.audioTags = [];
  1145. this.pendingCaptions.length = 0;
  1146. this.pendingMetadata.length = 0;
  1147. this.pendingTracks = 0;
  1148. this.processedTracks = 0;
  1149.  
  1150. // Emit the final segment
  1151. this.trigger('data', event);
  1152.  
  1153. this.trigger('done');
  1154. };
  1155.  
  1156. module.exports = CoalesceStream;
  1157.  
  1158. },{"40":40}],8:[function(require,module,exports){
  1159. /**
  1160. * mux.js
  1161. *
  1162. * Copyright (c) Brightcove
  1163. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1164. */
  1165. 'use strict';
  1166.  
  1167. var FlvTag = require(9);
  1168.  
  1169. // For information on the FLV format, see
  1170. // http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf.
  1171. // Technically, this function returns the header and a metadata FLV tag
  1172. // if duration is greater than zero
  1173. // duration in seconds
  1174. // @return {object} the bytes of the FLV header as a Uint8Array
  1175. var getFlvHeader = function(duration, audio, video) { // :ByteArray {
  1176. var
  1177. headBytes = new Uint8Array(3 + 1 + 1 + 4),
  1178. head = new DataView(headBytes.buffer),
  1179. metadata,
  1180. result,
  1181. metadataLength;
  1182.  
  1183. // default arguments
  1184. duration = duration || 0;
  1185. audio = audio === undefined ? true : audio;
  1186. video = video === undefined ? true : video;
  1187.  
  1188. // signature
  1189. head.setUint8(0, 0x46); // 'F'
  1190. head.setUint8(1, 0x4c); // 'L'
  1191. head.setUint8(2, 0x56); // 'V'
  1192.  
  1193. // version
  1194. head.setUint8(3, 0x01);
  1195.  
  1196. // flags
  1197. head.setUint8(4, (audio ? 0x04 : 0x00) | (video ? 0x01 : 0x00));
  1198.  
  1199. // data offset, should be 9 for FLV v1
  1200. head.setUint32(5, headBytes.byteLength);
  1201.  
  1202. // init the first FLV tag
  1203. if (duration <= 0) {
  1204. // no duration available so just write the first field of the first
  1205. // FLV tag
  1206. result = new Uint8Array(headBytes.byteLength + 4);
  1207. result.set(headBytes);
  1208. result.set([0, 0, 0, 0], headBytes.byteLength);
  1209. return result;
  1210. }
  1211.  
  1212. // write out the duration metadata tag
  1213. metadata = new FlvTag(FlvTag.METADATA_TAG);
  1214. metadata.pts = metadata.dts = 0;
  1215. metadata.writeMetaDataDouble('duration', duration);
  1216. metadataLength = metadata.finalize().length;
  1217. result = new Uint8Array(headBytes.byteLength + metadataLength);
  1218. result.set(headBytes);
  1219. result.set(head.byteLength, metadataLength);
  1220.  
  1221. return result;
  1222. };
  1223.  
  1224. module.exports = getFlvHeader;
  1225.  
  1226. },{"9":9}],9:[function(require,module,exports){
  1227. /**
  1228. * mux.js
  1229. *
  1230. * Copyright (c) Brightcove
  1231. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1232. *
  1233. * An object that stores the bytes of an FLV tag and methods for
  1234. * querying and manipulating that data.
  1235. * @see http://download.macromedia.com/f4v/video_file_format_spec_v10_1.pdf
  1236. */
  1237. 'use strict';
  1238.  
  1239. var FlvTag;
  1240.  
  1241. // (type:uint, extraData:Boolean = false) extends ByteArray
  1242. FlvTag = function(type, extraData) {
  1243. var
  1244. // Counter if this is a metadata tag, nal start marker if this is a video
  1245. // tag. unused if this is an audio tag
  1246. adHoc = 0, // :uint
  1247.  
  1248. // The default size is 16kb but this is not enough to hold iframe
  1249. // data and the resizing algorithm costs a bit so we create a larger
  1250. // starting buffer for video tags
  1251. bufferStartSize = 16384,
  1252.  
  1253. // checks whether the FLV tag has enough capacity to accept the proposed
  1254. // write and re-allocates the internal buffers if necessary
  1255. prepareWrite = function(flv, count) {
  1256. var
  1257. bytes,
  1258. minLength = flv.position + count;
  1259. if (minLength < flv.bytes.byteLength) {
  1260. // there's enough capacity so do nothing
  1261. return;
  1262. }
  1263.  
  1264. // allocate a new buffer and copy over the data that will not be modified
  1265. bytes = new Uint8Array(minLength * 2);
  1266. bytes.set(flv.bytes.subarray(0, flv.position), 0);
  1267. flv.bytes = bytes;
  1268. flv.view = new DataView(flv.bytes.buffer);
  1269. },
  1270.  
  1271. // commonly used metadata properties
  1272. widthBytes = FlvTag.widthBytes || new Uint8Array('width'.length),
  1273. heightBytes = FlvTag.heightBytes || new Uint8Array('height'.length),
  1274. videocodecidBytes = FlvTag.videocodecidBytes || new Uint8Array('videocodecid'.length),
  1275. i;
  1276.  
  1277. if (!FlvTag.widthBytes) {
  1278. // calculating the bytes of common metadata names ahead of time makes the
  1279. // corresponding writes faster because we don't have to loop over the
  1280. // characters
  1281. // re-test with test/perf.html if you're planning on changing this
  1282. for (i = 0; i < 'width'.length; i++) {
  1283. widthBytes[i] = 'width'.charCodeAt(i);
  1284. }
  1285. for (i = 0; i < 'height'.length; i++) {
  1286. heightBytes[i] = 'height'.charCodeAt(i);
  1287. }
  1288. for (i = 0; i < 'videocodecid'.length; i++) {
  1289. videocodecidBytes[i] = 'videocodecid'.charCodeAt(i);
  1290. }
  1291.  
  1292. FlvTag.widthBytes = widthBytes;
  1293. FlvTag.heightBytes = heightBytes;
  1294. FlvTag.videocodecidBytes = videocodecidBytes;
  1295. }
  1296.  
  1297. this.keyFrame = false; // :Boolean
  1298.  
  1299. switch (type) {
  1300. case FlvTag.VIDEO_TAG:
  1301. this.length = 16;
  1302. // Start the buffer at 256k
  1303. bufferStartSize *= 6;
  1304. break;
  1305. case FlvTag.AUDIO_TAG:
  1306. this.length = 13;
  1307. this.keyFrame = true;
  1308. break;
  1309. case FlvTag.METADATA_TAG:
  1310. this.length = 29;
  1311. this.keyFrame = true;
  1312. break;
  1313. default:
  1314. throw new Error('Unknown FLV tag type');
  1315. }
  1316.  
  1317. this.bytes = new Uint8Array(bufferStartSize);
  1318. this.view = new DataView(this.bytes.buffer);
  1319. this.bytes[0] = type;
  1320. this.position = this.length;
  1321. this.keyFrame = extraData; // Defaults to false
  1322.  
  1323. // presentation timestamp
  1324. this.pts = 0;
  1325. // decoder timestamp
  1326. this.dts = 0;
  1327.  
  1328. // ByteArray#writeBytes(bytes:ByteArray, offset:uint = 0, length:uint = 0)
  1329. this.writeBytes = function(bytes, offset, length) {
  1330. var
  1331. start = offset || 0,
  1332. end;
  1333. length = length || bytes.byteLength;
  1334. end = start + length;
  1335.  
  1336. prepareWrite(this, length);
  1337. this.bytes.set(bytes.subarray(start, end), this.position);
  1338.  
  1339. this.position += length;
  1340. this.length = Math.max(this.length, this.position);
  1341. };
  1342.  
  1343. // ByteArray#writeByte(value:int):void
  1344. this.writeByte = function(byte) {
  1345. prepareWrite(this, 1);
  1346. this.bytes[this.position] = byte;
  1347. this.position++;
  1348. this.length = Math.max(this.length, this.position);
  1349. };
  1350.  
  1351. // ByteArray#writeShort(value:int):void
  1352. this.writeShort = function(short) {
  1353. prepareWrite(this, 2);
  1354. this.view.setUint16(this.position, short);
  1355. this.position += 2;
  1356. this.length = Math.max(this.length, this.position);
  1357. };
  1358.  
  1359. // Negative index into array
  1360. // (pos:uint):int
  1361. this.negIndex = function(pos) {
  1362. return this.bytes[this.length - pos];
  1363. };
  1364.  
  1365. // The functions below ONLY work when this[0] == VIDEO_TAG.
  1366. // We are not going to check for that because we dont want the overhead
  1367. // (nal:ByteArray = null):int
  1368. this.nalUnitSize = function() {
  1369. if (adHoc === 0) {
  1370. return 0;
  1371. }
  1372.  
  1373. return this.length - (adHoc + 4);
  1374. };
  1375.  
  1376. this.startNalUnit = function() {
  1377. // remember position and add 4 bytes
  1378. if (adHoc > 0) {
  1379. throw new Error('Attempted to create new NAL wihout closing the old one');
  1380. }
  1381.  
  1382. // reserve 4 bytes for nal unit size
  1383. adHoc = this.length;
  1384. this.length += 4;
  1385. this.position = this.length;
  1386. };
  1387.  
  1388. // (nal:ByteArray = null):void
  1389. this.endNalUnit = function(nalContainer) {
  1390. var
  1391. nalStart, // :uint
  1392. nalLength; // :uint
  1393.  
  1394. // Rewind to the marker and write the size
  1395. if (this.length === adHoc + 4) {
  1396. // we started a nal unit, but didnt write one, so roll back the 4 byte size value
  1397. this.length -= 4;
  1398. } else if (adHoc > 0) {
  1399. nalStart = adHoc + 4;
  1400. nalLength = this.length - nalStart;
  1401.  
  1402. this.position = adHoc;
  1403. this.view.setUint32(this.position, nalLength);
  1404. this.position = this.length;
  1405.  
  1406. if (nalContainer) {
  1407. // Add the tag to the NAL unit
  1408. nalContainer.push(this.bytes.subarray(nalStart, nalStart + nalLength));
  1409. }
  1410. }
  1411.  
  1412. adHoc = 0;
  1413. };
  1414.  
  1415. /**
  1416. * Write out a 64-bit floating point valued metadata property. This method is
  1417. * called frequently during a typical parse and needs to be fast.
  1418. */
  1419. // (key:String, val:Number):void
  1420. this.writeMetaDataDouble = function(key, val) {
  1421. var i;
  1422. prepareWrite(this, 2 + key.length + 9);
  1423.  
  1424. // write size of property name
  1425. this.view.setUint16(this.position, key.length);
  1426. this.position += 2;
  1427.  
  1428. // this next part looks terrible but it improves parser throughput by
  1429. // 10kB/s in my testing
  1430.  
  1431. // write property name
  1432. if (key === 'width') {
  1433. this.bytes.set(widthBytes, this.position);
  1434. this.position += 5;
  1435. } else if (key === 'height') {
  1436. this.bytes.set(heightBytes, this.position);
  1437. this.position += 6;
  1438. } else if (key === 'videocodecid') {
  1439. this.bytes.set(videocodecidBytes, this.position);
  1440. this.position += 12;
  1441. } else {
  1442. for (i = 0; i < key.length; i++) {
  1443. this.bytes[this.position] = key.charCodeAt(i);
  1444. this.position++;
  1445. }
  1446. }
  1447.  
  1448. // skip null byte
  1449. this.position++;
  1450.  
  1451. // write property value
  1452. this.view.setFloat64(this.position, val);
  1453. this.position += 8;
  1454.  
  1455. // update flv tag length
  1456. this.length = Math.max(this.length, this.position);
  1457. ++adHoc;
  1458. };
  1459.  
  1460. // (key:String, val:Boolean):void
  1461. this.writeMetaDataBoolean = function(key, val) {
  1462. var i;
  1463. prepareWrite(this, 2);
  1464. this.view.setUint16(this.position, key.length);
  1465. this.position += 2;
  1466. for (i = 0; i < key.length; i++) {
  1467. // if key.charCodeAt(i) >= 255, handle error
  1468. prepareWrite(this, 1);
  1469. this.bytes[this.position] = key.charCodeAt(i);
  1470. this.position++;
  1471. }
  1472. prepareWrite(this, 2);
  1473. this.view.setUint8(this.position, 0x01);
  1474. this.position++;
  1475. this.view.setUint8(this.position, val ? 0x01 : 0x00);
  1476. this.position++;
  1477. this.length = Math.max(this.length, this.position);
  1478. ++adHoc;
  1479. };
  1480.  
  1481. // ():ByteArray
  1482. this.finalize = function() {
  1483. var
  1484. dtsDelta, // :int
  1485. len; // :int
  1486.  
  1487. switch (this.bytes[0]) {
  1488. // Video Data
  1489. case FlvTag.VIDEO_TAG:
  1490. // We only support AVC, 1 = key frame (for AVC, a seekable
  1491. // frame), 2 = inter frame (for AVC, a non-seekable frame)
  1492. this.bytes[11] = ((this.keyFrame || extraData) ? 0x10 : 0x20) | 0x07;
  1493. this.bytes[12] = extraData ? 0x00 : 0x01;
  1494.  
  1495. dtsDelta = this.pts - this.dts;
  1496. this.bytes[13] = (dtsDelta & 0x00FF0000) >>> 16;
  1497. this.bytes[14] = (dtsDelta & 0x0000FF00) >>> 8;
  1498. this.bytes[15] = (dtsDelta & 0x000000FF) >>> 0;
  1499. break;
  1500.  
  1501. case FlvTag.AUDIO_TAG:
  1502. this.bytes[11] = 0xAF; // 44 kHz, 16-bit stereo
  1503. this.bytes[12] = extraData ? 0x00 : 0x01;
  1504. break;
  1505.  
  1506. case FlvTag.METADATA_TAG:
  1507. this.position = 11;
  1508. this.view.setUint8(this.position, 0x02); // String type
  1509. this.position++;
  1510. this.view.setUint16(this.position, 0x0A); // 10 Bytes
  1511. this.position += 2;
  1512. // set "onMetaData"
  1513. this.bytes.set([0x6f, 0x6e, 0x4d, 0x65,
  1514. 0x74, 0x61, 0x44, 0x61,
  1515. 0x74, 0x61], this.position);
  1516. this.position += 10;
  1517. this.bytes[this.position] = 0x08; // Array type
  1518. this.position++;
  1519. this.view.setUint32(this.position, adHoc);
  1520. this.position = this.length;
  1521. this.bytes.set([0, 0, 9], this.position);
  1522. this.position += 3; // End Data Tag
  1523. this.length = this.position;
  1524. break;
  1525. }
  1526.  
  1527. len = this.length - 11;
  1528.  
  1529. // write the DataSize field
  1530. this.bytes[ 1] = (len & 0x00FF0000) >>> 16;
  1531. this.bytes[ 2] = (len & 0x0000FF00) >>> 8;
  1532. this.bytes[ 3] = (len & 0x000000FF) >>> 0;
  1533. // write the Timestamp
  1534. this.bytes[ 4] = (this.dts & 0x00FF0000) >>> 16;
  1535. this.bytes[ 5] = (this.dts & 0x0000FF00) >>> 8;
  1536. this.bytes[ 6] = (this.dts & 0x000000FF) >>> 0;
  1537. this.bytes[ 7] = (this.dts & 0xFF000000) >>> 24;
  1538. // write the StreamID
  1539. this.bytes[ 8] = 0;
  1540. this.bytes[ 9] = 0;
  1541. this.bytes[10] = 0;
  1542.  
  1543. // Sometimes we're at the end of the view and have one slot to write a
  1544. // uint32, so, prepareWrite of count 4, since, view is uint8
  1545. prepareWrite(this, 4);
  1546. this.view.setUint32(this.length, this.length);
  1547. this.length += 4;
  1548. this.position += 4;
  1549.  
  1550. // trim down the byte buffer to what is actually being used
  1551. this.bytes = this.bytes.subarray(0, this.length);
  1552. this.frameTime = FlvTag.frameTime(this.bytes);
  1553. // if bytes.bytelength isn't equal to this.length, handle error
  1554. return this;
  1555. };
  1556. };
  1557.  
  1558. FlvTag.AUDIO_TAG = 0x08; // == 8, :uint
  1559. FlvTag.VIDEO_TAG = 0x09; // == 9, :uint
  1560. FlvTag.METADATA_TAG = 0x12; // == 18, :uint
  1561.  
  1562. // (tag:ByteArray):Boolean {
  1563. FlvTag.isAudioFrame = function(tag) {
  1564. return FlvTag.AUDIO_TAG === tag[0];
  1565. };
  1566.  
  1567. // (tag:ByteArray):Boolean {
  1568. FlvTag.isVideoFrame = function(tag) {
  1569. return FlvTag.VIDEO_TAG === tag[0];
  1570. };
  1571.  
  1572. // (tag:ByteArray):Boolean {
  1573. FlvTag.isMetaData = function(tag) {
  1574. return FlvTag.METADATA_TAG === tag[0];
  1575. };
  1576.  
  1577. // (tag:ByteArray):Boolean {
  1578. FlvTag.isKeyFrame = function(tag) {
  1579. if (FlvTag.isVideoFrame(tag)) {
  1580. return tag[11] === 0x17;
  1581. }
  1582.  
  1583. if (FlvTag.isAudioFrame(tag)) {
  1584. return true;
  1585. }
  1586.  
  1587. if (FlvTag.isMetaData(tag)) {
  1588. return true;
  1589. }
  1590.  
  1591. return false;
  1592. };
  1593.  
  1594. // (tag:ByteArray):uint {
  1595. FlvTag.frameTime = function(tag) {
  1596. var pts = tag[ 4] << 16; // :uint
  1597. pts |= tag[ 5] << 8;
  1598. pts |= tag[ 6] << 0;
  1599. pts |= tag[ 7] << 24;
  1600. return pts;
  1601. };
  1602.  
  1603. module.exports = FlvTag;
  1604.  
  1605. },{}],10:[function(require,module,exports){
  1606. /**
  1607. * mux.js
  1608. *
  1609. * Copyright (c) Brightcove
  1610. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1611. */
  1612. module.exports = {
  1613. tag: require(9),
  1614. Transmuxer: require(12),
  1615. getFlvHeader: require(8)
  1616. };
  1617.  
  1618. },{"12":12,"8":8,"9":9}],11:[function(require,module,exports){
  1619. /**
  1620. * mux.js
  1621. *
  1622. * Copyright (c) Brightcove
  1623. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1624. */
  1625. 'use strict';
  1626.  
  1627. var TagList = function() {
  1628. var self = this;
  1629.  
  1630. this.list = [];
  1631.  
  1632. this.push = function(tag) {
  1633. this.list.push({
  1634. bytes: tag.bytes,
  1635. dts: tag.dts,
  1636. pts: tag.pts,
  1637. keyFrame: tag.keyFrame,
  1638. metaDataTag: tag.metaDataTag
  1639. });
  1640. };
  1641.  
  1642. Object.defineProperty(this, 'length', {
  1643. get: function() {
  1644. return self.list.length;
  1645. }
  1646. });
  1647. };
  1648.  
  1649. module.exports = TagList;
  1650.  
  1651. },{}],12:[function(require,module,exports){
  1652. /**
  1653. * mux.js
  1654. *
  1655. * Copyright (c) Brightcove
  1656. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  1657. */
  1658. 'use strict';
  1659.  
  1660. var Stream = require(40);
  1661. var FlvTag = require(9);
  1662. var m2ts = require(16);
  1663. var AdtsStream = require(3);
  1664. var H264Stream = require(4).H264Stream;
  1665. var CoalesceStream = require(7);
  1666. var TagList = require(11);
  1667.  
  1668. var
  1669. Transmuxer,
  1670. VideoSegmentStream,
  1671. AudioSegmentStream,
  1672. collectTimelineInfo,
  1673. metaDataTag,
  1674. extraDataTag;
  1675.  
  1676. /**
  1677. * Store information about the start and end of the tracka and the
  1678. * duration for each frame/sample we process in order to calculate
  1679. * the baseMediaDecodeTime
  1680. */
  1681. collectTimelineInfo = function(track, data) {
  1682. if (typeof data.pts === 'number') {
  1683. if (track.timelineStartInfo.pts === undefined) {
  1684. track.timelineStartInfo.pts = data.pts;
  1685. } else {
  1686. track.timelineStartInfo.pts =
  1687. Math.min(track.timelineStartInfo.pts, data.pts);
  1688. }
  1689. }
  1690.  
  1691. if (typeof data.dts === 'number') {
  1692. if (track.timelineStartInfo.dts === undefined) {
  1693. track.timelineStartInfo.dts = data.dts;
  1694. } else {
  1695. track.timelineStartInfo.dts =
  1696. Math.min(track.timelineStartInfo.dts, data.dts);
  1697. }
  1698. }
  1699. };
  1700.  
  1701. metaDataTag = function(track, pts) {
  1702. var
  1703. tag = new FlvTag(FlvTag.METADATA_TAG); // :FlvTag
  1704.  
  1705. tag.dts = pts;
  1706. tag.pts = pts;
  1707.  
  1708. tag.writeMetaDataDouble('videocodecid', 7);
  1709. tag.writeMetaDataDouble('width', track.width);
  1710. tag.writeMetaDataDouble('height', track.height);
  1711.  
  1712. return tag;
  1713. };
  1714.  
  1715. extraDataTag = function(track, pts) {
  1716. var
  1717. i,
  1718. tag = new FlvTag(FlvTag.VIDEO_TAG, true);
  1719.  
  1720. tag.dts = pts;
  1721. tag.pts = pts;
  1722.  
  1723. tag.writeByte(0x01);// version
  1724. tag.writeByte(track.profileIdc);// profile
  1725. tag.writeByte(track.profileCompatibility);// compatibility
  1726. tag.writeByte(track.levelIdc);// level
  1727. tag.writeByte(0xFC | 0x03); // reserved (6 bits), NULA length size - 1 (2 bits)
  1728. tag.writeByte(0xE0 | 0x01); // reserved (3 bits), num of SPS (5 bits)
  1729. tag.writeShort(track.sps[0].length); // data of SPS
  1730. tag.writeBytes(track.sps[0]); // SPS
  1731.  
  1732. tag.writeByte(track.pps.length); // num of PPS (will there ever be more that 1 PPS?)
  1733. for (i = 0; i < track.pps.length; ++i) {
  1734. tag.writeShort(track.pps[i].length); // 2 bytes for length of PPS
  1735. tag.writeBytes(track.pps[i]); // data of PPS
  1736. }
  1737.  
  1738. return tag;
  1739. };
  1740.  
  1741. /**
  1742. * Constructs a single-track, media segment from AAC data
  1743. * events. The output of this stream can be fed to flash.
  1744. */
  1745. AudioSegmentStream = function(track) {
  1746. var
  1747. adtsFrames = [],
  1748. videoKeyFrames = [],
  1749. oldExtraData;
  1750.  
  1751. AudioSegmentStream.prototype.init.call(this);
  1752.  
  1753. this.push = function(data) {
  1754. collectTimelineInfo(track, data);
  1755.  
  1756. if (track) {
  1757. track.audioobjecttype = data.audioobjecttype;
  1758. track.channelcount = data.channelcount;
  1759. track.samplerate = data.samplerate;
  1760. track.samplingfrequencyindex = data.samplingfrequencyindex;
  1761. track.samplesize = data.samplesize;
  1762. track.extraData = (track.audioobjecttype << 11) |
  1763. (track.samplingfrequencyindex << 7) |
  1764. (track.channelcount << 3);
  1765. }
  1766.  
  1767. data.pts = Math.round(data.pts / 90);
  1768. data.dts = Math.round(data.dts / 90);
  1769.  
  1770. // buffer audio data until end() is called
  1771. adtsFrames.push(data);
  1772. };
  1773.  
  1774. this.flush = function() {
  1775. var currentFrame, adtsFrame, lastMetaPts, tags = new TagList();
  1776. // return early if no audio data has been observed
  1777. if (adtsFrames.length === 0) {
  1778. this.trigger('done', 'AudioSegmentStream');
  1779. return;
  1780. }
  1781.  
  1782. lastMetaPts = -Infinity;
  1783.  
  1784. while (adtsFrames.length) {
  1785. currentFrame = adtsFrames.shift();
  1786.  
  1787. // write out a metadata frame at every video key frame
  1788. if (videoKeyFrames.length && currentFrame.pts >= videoKeyFrames[0]) {
  1789. lastMetaPts = videoKeyFrames.shift();
  1790. this.writeMetaDataTags(tags, lastMetaPts);
  1791. }
  1792.  
  1793. // also write out metadata tags every 1 second so that the decoder
  1794. // is re-initialized quickly after seeking into a different
  1795. // audio configuration.
  1796. if (track.extraData !== oldExtraData || currentFrame.pts - lastMetaPts >= 1000) {
  1797. this.writeMetaDataTags(tags, currentFrame.pts);
  1798. oldExtraData = track.extraData;
  1799. lastMetaPts = currentFrame.pts;
  1800. }
  1801.  
  1802. adtsFrame = new FlvTag(FlvTag.AUDIO_TAG);
  1803. adtsFrame.pts = currentFrame.pts;
  1804. adtsFrame.dts = currentFrame.dts;
  1805.  
  1806. adtsFrame.writeBytes(currentFrame.data);
  1807.  
  1808. tags.push(adtsFrame.finalize());
  1809. }
  1810.  
  1811. videoKeyFrames.length = 0;
  1812. oldExtraData = null;
  1813. this.trigger('data', {track: track, tags: tags.list});
  1814.  
  1815. this.trigger('done', 'AudioSegmentStream');
  1816. };
  1817.  
  1818. this.writeMetaDataTags = function(tags, pts) {
  1819. var adtsFrame;
  1820.  
  1821. adtsFrame = new FlvTag(FlvTag.METADATA_TAG);
  1822. // For audio, DTS is always the same as PTS. We want to set the DTS
  1823. // however so we can compare with video DTS to determine approximate
  1824. // packet order
  1825. adtsFrame.pts = pts;
  1826. adtsFrame.dts = pts;
  1827.  
  1828. // AAC is always 10
  1829. adtsFrame.writeMetaDataDouble('audiocodecid', 10);
  1830. adtsFrame.writeMetaDataBoolean('stereo', track.channelcount === 2);
  1831. adtsFrame.writeMetaDataDouble('audiosamplerate', track.samplerate);
  1832. // Is AAC always 16 bit?
  1833. adtsFrame.writeMetaDataDouble('audiosamplesize', 16);
  1834.  
  1835. tags.push(adtsFrame.finalize());
  1836.  
  1837. adtsFrame = new FlvTag(FlvTag.AUDIO_TAG, true);
  1838. // For audio, DTS is always the same as PTS. We want to set the DTS
  1839. // however so we can compare with video DTS to determine approximate
  1840. // packet order
  1841. adtsFrame.pts = pts;
  1842. adtsFrame.dts = pts;
  1843.  
  1844. adtsFrame.view.setUint16(adtsFrame.position, track.extraData);
  1845. adtsFrame.position += 2;
  1846. adtsFrame.length = Math.max(adtsFrame.length, adtsFrame.position);
  1847.  
  1848. tags.push(adtsFrame.finalize());
  1849. };
  1850.  
  1851. this.onVideoKeyFrame = function(pts) {
  1852. videoKeyFrames.push(pts);
  1853. };
  1854. };
  1855. AudioSegmentStream.prototype = new Stream();
  1856.  
  1857. /**
  1858. * Store FlvTags for the h264 stream
  1859. * @param track {object} track metadata configuration
  1860. */
  1861. VideoSegmentStream = function(track) {
  1862. var
  1863. nalUnits = [],
  1864. config,
  1865. h264Frame;
  1866. VideoSegmentStream.prototype.init.call(this);
  1867.  
  1868. this.finishFrame = function(tags, frame) {
  1869. if (!frame) {
  1870. return;
  1871. }
  1872. // Check if keyframe and the length of tags.
  1873. // This makes sure we write metadata on the first frame of a segment.
  1874. if (config && track && track.newMetadata &&
  1875. (frame.keyFrame || tags.length === 0)) {
  1876. // Push extra data on every IDR frame in case we did a stream change + seek
  1877. var metaTag = metaDataTag(config, frame.dts).finalize();
  1878. var extraTag = extraDataTag(track, frame.dts).finalize();
  1879.  
  1880. metaTag.metaDataTag = extraTag.metaDataTag = true;
  1881.  
  1882. tags.push(metaTag);
  1883. tags.push(extraTag);
  1884. track.newMetadata = false;
  1885.  
  1886. this.trigger('keyframe', frame.dts);
  1887. }
  1888.  
  1889. frame.endNalUnit();
  1890. tags.push(frame.finalize());
  1891. h264Frame = null;
  1892. };
  1893.  
  1894. this.push = function(data) {
  1895. collectTimelineInfo(track, data);
  1896.  
  1897. data.pts = Math.round(data.pts / 90);
  1898. data.dts = Math.round(data.dts / 90);
  1899.  
  1900. // buffer video until flush() is called
  1901. nalUnits.push(data);
  1902. };
  1903.  
  1904. this.flush = function() {
  1905. var
  1906. currentNal,
  1907. tags = new TagList();
  1908.  
  1909. // Throw away nalUnits at the start of the byte stream until we find
  1910. // the first AUD
  1911. while (nalUnits.length) {
  1912. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  1913. break;
  1914. }
  1915. nalUnits.shift();
  1916. }
  1917.  
  1918. // return early if no video data has been observed
  1919. if (nalUnits.length === 0) {
  1920. this.trigger('done', 'VideoSegmentStream');
  1921. return;
  1922. }
  1923.  
  1924. while (nalUnits.length) {
  1925. currentNal = nalUnits.shift();
  1926.  
  1927. // record the track config
  1928. if (currentNal.nalUnitType === 'seq_parameter_set_rbsp') {
  1929. track.newMetadata = true;
  1930. config = currentNal.config;
  1931. track.width = config.width;
  1932. track.height = config.height;
  1933. track.sps = [currentNal.data];
  1934. track.profileIdc = config.profileIdc;
  1935. track.levelIdc = config.levelIdc;
  1936. track.profileCompatibility = config.profileCompatibility;
  1937. h264Frame.endNalUnit();
  1938. } else if (currentNal.nalUnitType === 'pic_parameter_set_rbsp') {
  1939. track.newMetadata = true;
  1940. track.pps = [currentNal.data];
  1941. h264Frame.endNalUnit();
  1942. } else if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  1943. if (h264Frame) {
  1944. this.finishFrame(tags, h264Frame);
  1945. }
  1946. h264Frame = new FlvTag(FlvTag.VIDEO_TAG);
  1947. h264Frame.pts = currentNal.pts;
  1948. h264Frame.dts = currentNal.dts;
  1949. } else {
  1950. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  1951. // the current sample is a key frame
  1952. h264Frame.keyFrame = true;
  1953. }
  1954. h264Frame.endNalUnit();
  1955. }
  1956. h264Frame.startNalUnit();
  1957. h264Frame.writeBytes(currentNal.data);
  1958. }
  1959. if (h264Frame) {
  1960. this.finishFrame(tags, h264Frame);
  1961. }
  1962.  
  1963. this.trigger('data', {track: track, tags: tags.list});
  1964.  
  1965. // Continue with the flush process now
  1966. this.trigger('done', 'VideoSegmentStream');
  1967. };
  1968. };
  1969.  
  1970. VideoSegmentStream.prototype = new Stream();
  1971.  
  1972. /**
  1973. * An object that incrementally transmuxes MPEG2 Trasport Stream
  1974. * chunks into an FLV.
  1975. */
  1976. Transmuxer = function(options) {
  1977. var
  1978. self = this,
  1979.  
  1980. packetStream, parseStream, elementaryStream,
  1981. videoTimestampRolloverStream, audioTimestampRolloverStream,
  1982. timedMetadataTimestampRolloverStream,
  1983. adtsStream, h264Stream,
  1984. videoSegmentStream, audioSegmentStream, captionStream,
  1985. coalesceStream;
  1986.  
  1987. Transmuxer.prototype.init.call(this);
  1988.  
  1989. options = options || {};
  1990.  
  1991. // expose the metadata stream
  1992. this.metadataStream = new m2ts.MetadataStream();
  1993.  
  1994. options.metadataStream = this.metadataStream;
  1995.  
  1996. // set up the parsing pipeline
  1997. packetStream = new m2ts.TransportPacketStream();
  1998. parseStream = new m2ts.TransportParseStream();
  1999. elementaryStream = new m2ts.ElementaryStream();
  2000. videoTimestampRolloverStream = new m2ts.TimestampRolloverStream('video');
  2001. audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  2002. timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  2003.  
  2004. adtsStream = new AdtsStream();
  2005. h264Stream = new H264Stream();
  2006. coalesceStream = new CoalesceStream(options);
  2007.  
  2008. // disassemble MPEG2-TS packets into elementary streams
  2009. packetStream
  2010. .pipe(parseStream)
  2011. .pipe(elementaryStream);
  2012.  
  2013. // !!THIS ORDER IS IMPORTANT!!
  2014. // demux the streams
  2015. elementaryStream
  2016. .pipe(videoTimestampRolloverStream)
  2017. .pipe(h264Stream);
  2018. elementaryStream
  2019. .pipe(audioTimestampRolloverStream)
  2020. .pipe(adtsStream);
  2021.  
  2022. elementaryStream
  2023. .pipe(timedMetadataTimestampRolloverStream)
  2024. .pipe(this.metadataStream)
  2025. .pipe(coalesceStream);
  2026. // if CEA-708 parsing is available, hook up a caption stream
  2027. captionStream = new m2ts.CaptionStream();
  2028. h264Stream.pipe(captionStream)
  2029. .pipe(coalesceStream);
  2030.  
  2031. // hook up the segment streams once track metadata is delivered
  2032. elementaryStream.on('data', function(data) {
  2033. var i, videoTrack, audioTrack;
  2034.  
  2035. if (data.type === 'metadata') {
  2036. i = data.tracks.length;
  2037.  
  2038. // scan the tracks listed in the metadata
  2039. while (i--) {
  2040. if (data.tracks[i].type === 'video') {
  2041. videoTrack = data.tracks[i];
  2042. } else if (data.tracks[i].type === 'audio') {
  2043. audioTrack = data.tracks[i];
  2044. }
  2045. }
  2046.  
  2047. // hook up the video segment stream to the first track with h264 data
  2048. if (videoTrack && !videoSegmentStream) {
  2049. coalesceStream.numberOfTracks++;
  2050. videoSegmentStream = new VideoSegmentStream(videoTrack);
  2051.  
  2052. // Set up the final part of the video pipeline
  2053. h264Stream
  2054. .pipe(videoSegmentStream)
  2055. .pipe(coalesceStream);
  2056. }
  2057.  
  2058. if (audioTrack && !audioSegmentStream) {
  2059. // hook up the audio segment stream to the first track with aac data
  2060. coalesceStream.numberOfTracks++;
  2061. audioSegmentStream = new AudioSegmentStream(audioTrack);
  2062.  
  2063. // Set up the final part of the audio pipeline
  2064. adtsStream
  2065. .pipe(audioSegmentStream)
  2066. .pipe(coalesceStream);
  2067.  
  2068. if (videoSegmentStream) {
  2069. videoSegmentStream.on('keyframe', audioSegmentStream.onVideoKeyFrame);
  2070. }
  2071. }
  2072. }
  2073. });
  2074.  
  2075. // feed incoming data to the front of the parsing pipeline
  2076. this.push = function(data) {
  2077. packetStream.push(data);
  2078. };
  2079.  
  2080. // flush any buffered data
  2081. this.flush = function() {
  2082. // Start at the top of the pipeline and flush all pending work
  2083. packetStream.flush();
  2084. };
  2085.  
  2086. // Caption data has to be reset when seeking outside buffered range
  2087. this.resetCaptions = function() {
  2088. captionStream.reset();
  2089. };
  2090.  
  2091. // Re-emit any data coming from the coalesce stream to the outside world
  2092. coalesceStream.on('data', function(event) {
  2093. self.trigger('data', event);
  2094. });
  2095.  
  2096. // Let the consumer know we have finished flushing the entire pipeline
  2097. coalesceStream.on('done', function() {
  2098. self.trigger('done');
  2099. });
  2100. };
  2101. Transmuxer.prototype = new Stream();
  2102.  
  2103. // forward compatibility
  2104. module.exports = Transmuxer;
  2105.  
  2106. },{"11":11,"16":16,"3":3,"4":4,"40":40,"7":7,"9":9}],13:[function(require,module,exports){
  2107. /**
  2108. * mux.js
  2109. *
  2110. * Copyright (c) Brightcove
  2111. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2112. */
  2113. 'use strict';
  2114.  
  2115. var muxjs = {
  2116. codecs: require(5),
  2117. mp4: require(24),
  2118. flv: require(10),
  2119. mp2t: require(15),
  2120. partial: require(30)
  2121. };
  2122.  
  2123. // include all the tools when the full library is required
  2124. muxjs.mp4.tools = require(35);
  2125. muxjs.flv.tools = require(34);
  2126. muxjs.mp2t.tools = require(36);
  2127.  
  2128.  
  2129. module.exports = muxjs;
  2130.  
  2131. },{"10":10,"15":15,"24":24,"30":30,"34":34,"35":35,"36":36,"5":5}],14:[function(require,module,exports){
  2132. /**
  2133. * mux.js
  2134. *
  2135. * Copyright (c) Brightcove
  2136. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2137. *
  2138. * Reads in-band caption information from a video elementary
  2139. * stream. Captions must follow the CEA-708 standard for injection
  2140. * into an MPEG-2 transport streams.
  2141. * @see https://en.wikipedia.org/wiki/CEA-708
  2142. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  2143. */
  2144.  
  2145. 'use strict';
  2146.  
  2147. // -----------------
  2148. // Link To Transport
  2149. // -----------------
  2150.  
  2151. var Stream = require(40);
  2152. var cea708Parser = require(33);
  2153.  
  2154. var CaptionStream = function() {
  2155.  
  2156. CaptionStream.prototype.init.call(this);
  2157.  
  2158. this.captionPackets_ = [];
  2159.  
  2160. this.ccStreams_ = [
  2161. new Cea608Stream(0, 0), // eslint-disable-line no-use-before-define
  2162. new Cea608Stream(0, 1), // eslint-disable-line no-use-before-define
  2163. new Cea608Stream(1, 0), // eslint-disable-line no-use-before-define
  2164. new Cea608Stream(1, 1) // eslint-disable-line no-use-before-define
  2165. ];
  2166.  
  2167. this.reset();
  2168.  
  2169. // forward data and done events from CCs to this CaptionStream
  2170. this.ccStreams_.forEach(function(cc) {
  2171. cc.on('data', this.trigger.bind(this, 'data'));
  2172. cc.on('partialdone', this.trigger.bind(this, 'partialdone'));
  2173. cc.on('done', this.trigger.bind(this, 'done'));
  2174. }, this);
  2175.  
  2176. };
  2177.  
  2178. CaptionStream.prototype = new Stream();
  2179. CaptionStream.prototype.push = function(event) {
  2180. var sei, userData, newCaptionPackets;
  2181.  
  2182. // only examine SEI NALs
  2183. if (event.nalUnitType !== 'sei_rbsp') {
  2184. return;
  2185. }
  2186.  
  2187. // parse the sei
  2188. sei = cea708Parser.parseSei(event.escapedRBSP);
  2189.  
  2190. // ignore everything but user_data_registered_itu_t_t35
  2191. if (sei.payloadType !== cea708Parser.USER_DATA_REGISTERED_ITU_T_T35) {
  2192. return;
  2193. }
  2194.  
  2195. // parse out the user data payload
  2196. userData = cea708Parser.parseUserData(sei);
  2197.  
  2198. // ignore unrecognized userData
  2199. if (!userData) {
  2200. return;
  2201. }
  2202.  
  2203. // Sometimes, the same segment # will be downloaded twice. To stop the
  2204. // caption data from being processed twice, we track the latest dts we've
  2205. // received and ignore everything with a dts before that. However, since
  2206. // data for a specific dts can be split across packets on either side of
  2207. // a segment boundary, we need to make sure we *don't* ignore the packets
  2208. // from the *next* segment that have dts === this.latestDts_. By constantly
  2209. // tracking the number of packets received with dts === this.latestDts_, we
  2210. // know how many should be ignored once we start receiving duplicates.
  2211. if (event.dts < this.latestDts_) {
  2212. // We've started getting older data, so set the flag.
  2213. this.ignoreNextEqualDts_ = true;
  2214. return;
  2215. } else if ((event.dts === this.latestDts_) && (this.ignoreNextEqualDts_)) {
  2216. this.numSameDts_--;
  2217. if (!this.numSameDts_) {
  2218. // We've received the last duplicate packet, time to start processing again
  2219. this.ignoreNextEqualDts_ = false;
  2220. }
  2221. return;
  2222. }
  2223.  
  2224. // parse out CC data packets and save them for later
  2225. newCaptionPackets = cea708Parser.parseCaptionPackets(event.pts, userData);
  2226. this.captionPackets_ = this.captionPackets_.concat(newCaptionPackets);
  2227. if (this.latestDts_ !== event.dts) {
  2228. this.numSameDts_ = 0;
  2229. }
  2230. this.numSameDts_++;
  2231. this.latestDts_ = event.dts;
  2232. };
  2233.  
  2234. CaptionStream.prototype.flushCCStreams = function(flushType) {
  2235. this.ccStreams_.forEach(function(cc) {
  2236. return flushType === 'flush' ? cc.flush() : cc.partialFlush();
  2237. }, this);
  2238. };
  2239.  
  2240. CaptionStream.prototype.flushStream = function(flushType) {
  2241. // make sure we actually parsed captions before proceeding
  2242. if (!this.captionPackets_.length) {
  2243. this.flushCCStreams(flushType);
  2244. return;
  2245. }
  2246.  
  2247. // In Chrome, the Array#sort function is not stable so add a
  2248. // presortIndex that we can use to ensure we get a stable-sort
  2249. this.captionPackets_.forEach(function(elem, idx) {
  2250. elem.presortIndex = idx;
  2251. });
  2252.  
  2253. // sort caption byte-pairs based on their PTS values
  2254. this.captionPackets_.sort(function(a, b) {
  2255. if (a.pts === b.pts) {
  2256. return a.presortIndex - b.presortIndex;
  2257. }
  2258. return a.pts - b.pts;
  2259. });
  2260.  
  2261. this.captionPackets_.forEach(function(packet) {
  2262. if (packet.type < 2) {
  2263. // Dispatch packet to the right Cea608Stream
  2264. this.dispatchCea608Packet(packet);
  2265. }
  2266. // this is where an 'else' would go for a dispatching packets
  2267. // to a theoretical Cea708Stream that handles SERVICEn data
  2268. }, this);
  2269.  
  2270. this.captionPackets_.length = 0;
  2271. this.flushCCStreams(flushType);
  2272. };
  2273.  
  2274. CaptionStream.prototype.flush = function() {
  2275. return this.flushStream('flush');
  2276. };
  2277.  
  2278. // Only called if handling partial data
  2279. CaptionStream.prototype.partialFlush = function() {
  2280. return this.flushStream('partialFlush');
  2281. };
  2282.  
  2283. CaptionStream.prototype.reset = function() {
  2284. this.latestDts_ = null;
  2285. this.ignoreNextEqualDts_ = false;
  2286. this.numSameDts_ = 0;
  2287. this.activeCea608Channel_ = [null, null];
  2288. this.ccStreams_.forEach(function(ccStream) {
  2289. ccStream.reset();
  2290. });
  2291. };
  2292.  
  2293. // From the CEA-608 spec:
  2294. /*
  2295. * When XDS sub-packets are interleaved with other services, the end of each sub-packet shall be followed
  2296. * by a control pair to change to a different service. When any of the control codes from 0x10 to 0x1F is
  2297. * used to begin a control code pair, it indicates the return to captioning or Text data. The control code pair
  2298. * and subsequent data should then be processed according to the FCC rules. It may be necessary for the
  2299. * line 21 data encoder to automatically insert a control code pair (i.e. RCL, RU2, RU3, RU4, RDC, or RTD)
  2300. * to switch to captioning or Text.
  2301. */
  2302. // With that in mind, we ignore any data between an XDS control code and a
  2303. // subsequent closed-captioning control code.
  2304. CaptionStream.prototype.dispatchCea608Packet = function(packet) {
  2305. // NOTE: packet.type is the CEA608 field
  2306. if (this.setsTextOrXDSActive(packet)) {
  2307. this.activeCea608Channel_[packet.type] = null;
  2308. } else if (this.setsChannel1Active(packet)) {
  2309. this.activeCea608Channel_[packet.type] = 0;
  2310. } else if (this.setsChannel2Active(packet)) {
  2311. this.activeCea608Channel_[packet.type] = 1;
  2312. }
  2313. if (this.activeCea608Channel_[packet.type] === null) {
  2314. // If we haven't received anything to set the active channel, or the
  2315. // packets are Text/XDS data, discard the data; we don't want jumbled
  2316. // captions
  2317. return;
  2318. }
  2319. this.ccStreams_[(packet.type << 1) + this.activeCea608Channel_[packet.type]].push(packet);
  2320. };
  2321.  
  2322. CaptionStream.prototype.setsChannel1Active = function(packet) {
  2323. return ((packet.ccData & 0x7800) === 0x1000);
  2324. };
  2325. CaptionStream.prototype.setsChannel2Active = function(packet) {
  2326. return ((packet.ccData & 0x7800) === 0x1800);
  2327. };
  2328. CaptionStream.prototype.setsTextOrXDSActive = function(packet) {
  2329. return ((packet.ccData & 0x7100) === 0x0100) ||
  2330. ((packet.ccData & 0x78fe) === 0x102a) ||
  2331. ((packet.ccData & 0x78fe) === 0x182a);
  2332. };
  2333.  
  2334. // ----------------------
  2335. // Session to Application
  2336. // ----------------------
  2337.  
  2338. // This hash maps non-ASCII, special, and extended character codes to their
  2339. // proper Unicode equivalent. The first keys that are only a single byte
  2340. // are the non-standard ASCII characters, which simply map the CEA608 byte
  2341. // to the standard ASCII/Unicode. The two-byte keys that follow are the CEA608
  2342. // character codes, but have their MSB bitmasked with 0x03 so that a lookup
  2343. // can be performed regardless of the field and data channel on which the
  2344. // character code was received.
  2345. var CHARACTER_TRANSLATION = {
  2346. 0x2a: 0xe1, // ГЎ
  2347. 0x5c: 0xe9, // Г©
  2348. 0x5e: 0xed, // Г­
  2349. 0x5f: 0xf3, // Гі
  2350. 0x60: 0xfa, // Гє
  2351. 0x7b: 0xe7, // Г§
  2352. 0x7c: 0xf7, // Г·
  2353. 0x7d: 0xd1, // Г‘
  2354. 0x7e: 0xf1, // Г±
  2355. 0x7f: 0x2588, // в–€
  2356. 0x0130: 0xae, // В®
  2357. 0x0131: 0xb0, // В°
  2358. 0x0132: 0xbd, // ВЅ
  2359. 0x0133: 0xbf, // Вї
  2360. 0x0134: 0x2122, // в„ў
  2361. 0x0135: 0xa2, // Вў
  2362. 0x0136: 0xa3, // ВЈ
  2363. 0x0137: 0x266a, // в™Є
  2364. 0x0138: 0xe0, // Г 
  2365. 0x0139: 0xa0, //
  2366. 0x013a: 0xe8, // ГЁ
  2367. 0x013b: 0xe2, // Гў
  2368. 0x013c: 0xea, // ГЄ
  2369. 0x013d: 0xee, // Г®
  2370. 0x013e: 0xf4, // Гґ
  2371. 0x013f: 0xfb, // Г»
  2372. 0x0220: 0xc1, // ГЃ
  2373. 0x0221: 0xc9, // Г‰
  2374. 0x0222: 0xd3, // Г“
  2375. 0x0223: 0xda, // Гљ
  2376. 0x0224: 0xdc, // Гњ
  2377. 0x0225: 0xfc, // Гј
  2378. 0x0226: 0x2018, // ‘
  2379. 0x0227: 0xa1, // ВЎ
  2380. 0x0228: 0x2a, // *
  2381. 0x0229: 0x27, // '
  2382. 0x022a: 0x2014, // —
  2383. 0x022b: 0xa9, // В©
  2384. 0x022c: 0x2120, // в„ 
  2385. 0x022d: 0x2022, // •
  2386. 0x022e: 0x201c, // “
  2387. 0x022f: 0x201d, // ”
  2388. 0x0230: 0xc0, // ГЂ
  2389. 0x0231: 0xc2, // Г‚
  2390. 0x0232: 0xc7, // Г‡
  2391. 0x0233: 0xc8, // Г€
  2392. 0x0234: 0xca, // ГЉ
  2393. 0x0235: 0xcb, // Г‹
  2394. 0x0236: 0xeb, // Г«
  2395. 0x0237: 0xce, // ГЋ
  2396. 0x0238: 0xcf, // ГЏ
  2397. 0x0239: 0xef, // ГЇ
  2398. 0x023a: 0xd4, // Г”
  2399. 0x023b: 0xd9, // Г™
  2400. 0x023c: 0xf9, // Г№
  2401. 0x023d: 0xdb, // Г›
  2402. 0x023e: 0xab, // В«
  2403. 0x023f: 0xbb, // В»
  2404. 0x0320: 0xc3, // Гѓ
  2405. 0x0321: 0xe3, // ГЈ
  2406. 0x0322: 0xcd, // ГЌ
  2407. 0x0323: 0xcc, // ГЊ
  2408. 0x0324: 0xec, // Г¬
  2409. 0x0325: 0xd2, // Г’
  2410. 0x0326: 0xf2, // ГІ
  2411. 0x0327: 0xd5, // Г•
  2412. 0x0328: 0xf5, // Гµ
  2413. 0x0329: 0x7b, // {
  2414. 0x032a: 0x7d, // }
  2415. 0x032b: 0x5c, // \
  2416. 0x032c: 0x5e, // ^
  2417. 0x032d: 0x5f, // _
  2418. 0x032e: 0x7c, // |
  2419. 0x032f: 0x7e, // ~
  2420. 0x0330: 0xc4, // Г„
  2421. 0x0331: 0xe4, // Г¤
  2422. 0x0332: 0xd6, // Г–
  2423. 0x0333: 0xf6, // Г¶
  2424. 0x0334: 0xdf, // Гџ
  2425. 0x0335: 0xa5, // ВҐ
  2426. 0x0336: 0xa4, // В¤
  2427. 0x0337: 0x2502, // в”‚
  2428. 0x0338: 0xc5, // Г…
  2429. 0x0339: 0xe5, // ГҐ
  2430. 0x033a: 0xd8, // Ø
  2431. 0x033b: 0xf8, // Гё
  2432. 0x033c: 0x250c, // в”Њ
  2433. 0x033d: 0x2510, // в”ђ
  2434. 0x033e: 0x2514, // в””
  2435. 0x033f: 0x2518 // ┘
  2436. };
  2437.  
  2438. var getCharFromCode = function(code) {
  2439. if (code === null) {
  2440. return '';
  2441. }
  2442. code = CHARACTER_TRANSLATION[code] || code;
  2443. return String.fromCharCode(code);
  2444. };
  2445.  
  2446. // the index of the last row in a CEA-608 display buffer
  2447. var BOTTOM_ROW = 14;
  2448.  
  2449. // This array is used for mapping PACs -> row #, since there's no way of
  2450. // getting it through bit logic.
  2451. var ROWS = [0x1100, 0x1120, 0x1200, 0x1220, 0x1500, 0x1520, 0x1600, 0x1620,
  2452. 0x1700, 0x1720, 0x1000, 0x1300, 0x1320, 0x1400, 0x1420];
  2453.  
  2454. // CEA-608 captions are rendered onto a 34x15 matrix of character
  2455. // cells. The "bottom" row is the last element in the outer array.
  2456. var createDisplayBuffer = function() {
  2457. var result = [], i = BOTTOM_ROW + 1;
  2458. while (i--) {
  2459. result.push('');
  2460. }
  2461. return result;
  2462. };
  2463.  
  2464. var Cea608Stream = function(field, dataChannel) {
  2465. Cea608Stream.prototype.init.call(this);
  2466.  
  2467. this.field_ = field || 0;
  2468. this.dataChannel_ = dataChannel || 0;
  2469.  
  2470. this.name_ = 'CC' + (((this.field_ << 1) | this.dataChannel_) + 1);
  2471.  
  2472. this.setConstants();
  2473. this.reset();
  2474.  
  2475. this.push = function(packet) {
  2476. var data, swap, char0, char1, text;
  2477. // remove the parity bits
  2478. data = packet.ccData & 0x7f7f;
  2479.  
  2480. // ignore duplicate control codes; the spec demands they're sent twice
  2481. if (data === this.lastControlCode_) {
  2482. this.lastControlCode_ = null;
  2483. return;
  2484. }
  2485.  
  2486. // Store control codes
  2487. if ((data & 0xf000) === 0x1000) {
  2488. this.lastControlCode_ = data;
  2489. } else if (data !== this.PADDING_) {
  2490. this.lastControlCode_ = null;
  2491. }
  2492.  
  2493. char0 = data >>> 8;
  2494. char1 = data & 0xff;
  2495.  
  2496. if (data === this.PADDING_) {
  2497. return;
  2498.  
  2499. } else if (data === this.RESUME_CAPTION_LOADING_) {
  2500. this.mode_ = 'popOn';
  2501.  
  2502. } else if (data === this.END_OF_CAPTION_) {
  2503. // If an EOC is received while in paint-on mode, the displayed caption
  2504. // text should be swapped to non-displayed memory as if it was a pop-on
  2505. // caption. Because of that, we should explicitly switch back to pop-on
  2506. // mode
  2507. this.mode_ = 'popOn';
  2508. this.clearFormatting(packet.pts);
  2509. // if a caption was being displayed, it's gone now
  2510. this.flushDisplayed(packet.pts);
  2511.  
  2512. // flip memory
  2513. swap = this.displayed_;
  2514. this.displayed_ = this.nonDisplayed_;
  2515. this.nonDisplayed_ = swap;
  2516.  
  2517. // start measuring the time to display the caption
  2518. this.startPts_ = packet.pts;
  2519.  
  2520. } else if (data === this.ROLL_UP_2_ROWS_) {
  2521. this.rollUpRows_ = 2;
  2522. this.setRollUp(packet.pts);
  2523. } else if (data === this.ROLL_UP_3_ROWS_) {
  2524. this.rollUpRows_ = 3;
  2525. this.setRollUp(packet.pts);
  2526. } else if (data === this.ROLL_UP_4_ROWS_) {
  2527. this.rollUpRows_ = 4;
  2528. this.setRollUp(packet.pts);
  2529. } else if (data === this.CARRIAGE_RETURN_) {
  2530. this.clearFormatting(packet.pts);
  2531. this.flushDisplayed(packet.pts);
  2532. this.shiftRowsUp_();
  2533. this.startPts_ = packet.pts;
  2534.  
  2535. } else if (data === this.BACKSPACE_) {
  2536. if (this.mode_ === 'popOn') {
  2537. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  2538. } else {
  2539. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  2540. }
  2541. } else if (data === this.ERASE_DISPLAYED_MEMORY_) {
  2542. this.flushDisplayed(packet.pts);
  2543. this.displayed_ = createDisplayBuffer();
  2544. } else if (data === this.ERASE_NON_DISPLAYED_MEMORY_) {
  2545. this.nonDisplayed_ = createDisplayBuffer();
  2546.  
  2547. } else if (data === this.RESUME_DIRECT_CAPTIONING_) {
  2548. if (this.mode_ !== 'paintOn') {
  2549. // NOTE: This should be removed when proper caption positioning is
  2550. // implemented
  2551. this.flushDisplayed(packet.pts);
  2552. this.displayed_ = createDisplayBuffer();
  2553. }
  2554. this.mode_ = 'paintOn';
  2555. this.startPts_ = packet.pts;
  2556.  
  2557. // Append special characters to caption text
  2558. } else if (this.isSpecialCharacter(char0, char1)) {
  2559. // Bitmask char0 so that we can apply character transformations
  2560. // regardless of field and data channel.
  2561. // Then byte-shift to the left and OR with char1 so we can pass the
  2562. // entire character code to `getCharFromCode`.
  2563. char0 = (char0 & 0x03) << 8;
  2564. text = getCharFromCode(char0 | char1);
  2565. this[this.mode_](packet.pts, text);
  2566. this.column_++;
  2567.  
  2568. // Append extended characters to caption text
  2569. } else if (this.isExtCharacter(char0, char1)) {
  2570. // Extended characters always follow their "non-extended" equivalents.
  2571. // IE if a "ГЁ" is desired, you'll always receive "eГЁ"; non-compliant
  2572. // decoders are supposed to drop the "ГЁ", while compliant decoders
  2573. // backspace the "e" and insert "ГЁ".
  2574.  
  2575. // Delete the previous character
  2576. if (this.mode_ === 'popOn') {
  2577. this.nonDisplayed_[this.row_] = this.nonDisplayed_[this.row_].slice(0, -1);
  2578. } else {
  2579. this.displayed_[this.row_] = this.displayed_[this.row_].slice(0, -1);
  2580. }
  2581.  
  2582. // Bitmask char0 so that we can apply character transformations
  2583. // regardless of field and data channel.
  2584. // Then byte-shift to the left and OR with char1 so we can pass the
  2585. // entire character code to `getCharFromCode`.
  2586. char0 = (char0 & 0x03) << 8;
  2587. text = getCharFromCode(char0 | char1);
  2588. this[this.mode_](packet.pts, text);
  2589. this.column_++;
  2590.  
  2591. // Process mid-row codes
  2592. } else if (this.isMidRowCode(char0, char1)) {
  2593. // Attributes are not additive, so clear all formatting
  2594. this.clearFormatting(packet.pts);
  2595.  
  2596. // According to the standard, mid-row codes
  2597. // should be replaced with spaces, so add one now
  2598. this[this.mode_](packet.pts, ' ');
  2599. this.column_++;
  2600.  
  2601. if ((char1 & 0xe) === 0xe) {
  2602. this.addFormatting(packet.pts, ['i']);
  2603. }
  2604.  
  2605. if ((char1 & 0x1) === 0x1) {
  2606. this.addFormatting(packet.pts, ['u']);
  2607. }
  2608.  
  2609. // Detect offset control codes and adjust cursor
  2610. } else if (this.isOffsetControlCode(char0, char1)) {
  2611. // Cursor position is set by indent PAC (see below) in 4-column
  2612. // increments, with an additional offset code of 1-3 to reach any
  2613. // of the 32 columns specified by CEA-608. So all we need to do
  2614. // here is increment the column cursor by the given offset.
  2615. this.column_ += (char1 & 0x03);
  2616.  
  2617. // Detect PACs (Preamble Address Codes)
  2618. } else if (this.isPAC(char0, char1)) {
  2619.  
  2620. // There's no logic for PAC -> row mapping, so we have to just
  2621. // find the row code in an array and use its index :(
  2622. var row = ROWS.indexOf(data & 0x1f20);
  2623.  
  2624. // Configure the caption window if we're in roll-up mode
  2625. if (this.mode_ === 'rollUp') {
  2626. // This implies that the base row is incorrectly set.
  2627. // As per the recommendation in CEA-608(Base Row Implementation), defer to the number
  2628. // of roll-up rows set.
  2629. if (row - this.rollUpRows_ + 1 < 0) {
  2630. row = this.rollUpRows_ - 1;
  2631. }
  2632.  
  2633. this.setRollUp(packet.pts, row);
  2634. }
  2635.  
  2636. if (row !== this.row_) {
  2637. // formatting is only persistent for current row
  2638. this.clearFormatting(packet.pts);
  2639. this.row_ = row;
  2640. }
  2641. // All PACs can apply underline, so detect and apply
  2642. // (All odd-numbered second bytes set underline)
  2643. if ((char1 & 0x1) && (this.formatting_.indexOf('u') === -1)) {
  2644. this.addFormatting(packet.pts, ['u']);
  2645. }
  2646.  
  2647. if ((data & 0x10) === 0x10) {
  2648. // We've got an indent level code. Each successive even number
  2649. // increments the column cursor by 4, so we can get the desired
  2650. // column position by bit-shifting to the right (to get n/2)
  2651. // and multiplying by 4.
  2652. this.column_ = ((data & 0xe) >> 1) * 4;
  2653. }
  2654.  
  2655. if (this.isColorPAC(char1)) {
  2656. // it's a color code, though we only support white, which
  2657. // can be either normal or italicized. white italics can be
  2658. // either 0x4e or 0x6e depending on the row, so we just
  2659. // bitwise-and with 0xe to see if italics should be turned on
  2660. if ((char1 & 0xe) === 0xe) {
  2661. this.addFormatting(packet.pts, ['i']);
  2662. }
  2663. }
  2664.  
  2665. // We have a normal character in char0, and possibly one in char1
  2666. } else if (this.isNormalChar(char0)) {
  2667. if (char1 === 0x00) {
  2668. char1 = null;
  2669. }
  2670. text = getCharFromCode(char0);
  2671. text += getCharFromCode(char1);
  2672. this[this.mode_](packet.pts, text);
  2673. this.column_ += text.length;
  2674.  
  2675. } // finish data processing
  2676.  
  2677. };
  2678. };
  2679. Cea608Stream.prototype = new Stream();
  2680. // Trigger a cue point that captures the current state of the
  2681. // display buffer
  2682. Cea608Stream.prototype.flushDisplayed = function(pts) {
  2683. var content = this.displayed_
  2684. // remove spaces from the start and end of the string
  2685. .map(function(row) {
  2686. try {
  2687. return row.trim();
  2688. } catch (e) {
  2689. // Ordinarily, this shouldn't happen. However, caption
  2690. // parsing errors should not throw exceptions and
  2691. // break playback.
  2692. // eslint-disable-next-line no-console
  2693. console.error('Skipping malformed caption.');
  2694. return '';
  2695. }
  2696. })
  2697. // combine all text rows to display in one cue
  2698. .join('\n')
  2699. // and remove blank rows from the start and end, but not the middle
  2700. .replace(/^\n+|\n+$/g, '');
  2701.  
  2702. if (content.length) {
  2703. this.trigger('data', {
  2704. startPts: this.startPts_,
  2705. endPts: pts,
  2706. text: content,
  2707. stream: this.name_
  2708. });
  2709. }
  2710. };
  2711.  
  2712. /**
  2713. * Zero out the data, used for startup and on seek
  2714. */
  2715. Cea608Stream.prototype.reset = function() {
  2716. this.mode_ = 'popOn';
  2717. // When in roll-up mode, the index of the last row that will
  2718. // actually display captions. If a caption is shifted to a row
  2719. // with a lower index than this, it is cleared from the display
  2720. // buffer
  2721. this.topRow_ = 0;
  2722. this.startPts_ = 0;
  2723. this.displayed_ = createDisplayBuffer();
  2724. this.nonDisplayed_ = createDisplayBuffer();
  2725. this.lastControlCode_ = null;
  2726.  
  2727. // Track row and column for proper line-breaking and spacing
  2728. this.column_ = 0;
  2729. this.row_ = BOTTOM_ROW;
  2730. this.rollUpRows_ = 2;
  2731.  
  2732. // This variable holds currently-applied formatting
  2733. this.formatting_ = [];
  2734. };
  2735.  
  2736. /**
  2737. * Sets up control code and related constants for this instance
  2738. */
  2739. Cea608Stream.prototype.setConstants = function() {
  2740. // The following attributes have these uses:
  2741. // ext_ : char0 for mid-row codes, and the base for extended
  2742. // chars (ext_+0, ext_+1, and ext_+2 are char0s for
  2743. // extended codes)
  2744. // control_: char0 for control codes, except byte-shifted to the
  2745. // left so that we can do this.control_ | CONTROL_CODE
  2746. // offset_: char0 for tab offset codes
  2747. //
  2748. // It's also worth noting that control codes, and _only_ control codes,
  2749. // differ between field 1 and field2. Field 2 control codes are always
  2750. // their field 1 value plus 1. That's why there's the "| field" on the
  2751. // control value.
  2752. if (this.dataChannel_ === 0) {
  2753. this.BASE_ = 0x10;
  2754. this.EXT_ = 0x11;
  2755. this.CONTROL_ = (0x14 | this.field_) << 8;
  2756. this.OFFSET_ = 0x17;
  2757. } else if (this.dataChannel_ === 1) {
  2758. this.BASE_ = 0x18;
  2759. this.EXT_ = 0x19;
  2760. this.CONTROL_ = (0x1c | this.field_) << 8;
  2761. this.OFFSET_ = 0x1f;
  2762. }
  2763.  
  2764. // Constants for the LSByte command codes recognized by Cea608Stream. This
  2765. // list is not exhaustive. For a more comprehensive listing and semantics see
  2766. // http://www.gpo.gov/fdsys/pkg/CFR-2010-title47-vol1/pdf/CFR-2010-title47-vol1-sec15-119.pdf
  2767. // Padding
  2768. this.PADDING_ = 0x0000;
  2769. // Pop-on Mode
  2770. this.RESUME_CAPTION_LOADING_ = this.CONTROL_ | 0x20;
  2771. this.END_OF_CAPTION_ = this.CONTROL_ | 0x2f;
  2772. // Roll-up Mode
  2773. this.ROLL_UP_2_ROWS_ = this.CONTROL_ | 0x25;
  2774. this.ROLL_UP_3_ROWS_ = this.CONTROL_ | 0x26;
  2775. this.ROLL_UP_4_ROWS_ = this.CONTROL_ | 0x27;
  2776. this.CARRIAGE_RETURN_ = this.CONTROL_ | 0x2d;
  2777. // paint-on mode
  2778. this.RESUME_DIRECT_CAPTIONING_ = this.CONTROL_ | 0x29;
  2779. // Erasure
  2780. this.BACKSPACE_ = this.CONTROL_ | 0x21;
  2781. this.ERASE_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2c;
  2782. this.ERASE_NON_DISPLAYED_MEMORY_ = this.CONTROL_ | 0x2e;
  2783. };
  2784.  
  2785. /**
  2786. * Detects if the 2-byte packet data is a special character
  2787. *
  2788. * Special characters have a second byte in the range 0x30 to 0x3f,
  2789. * with the first byte being 0x11 (for data channel 1) or 0x19 (for
  2790. * data channel 2).
  2791. *
  2792. * @param {Integer} char0 The first byte
  2793. * @param {Integer} char1 The second byte
  2794. * @return {Boolean} Whether the 2 bytes are an special character
  2795. */
  2796. Cea608Stream.prototype.isSpecialCharacter = function(char0, char1) {
  2797. return (char0 === this.EXT_ && char1 >= 0x30 && char1 <= 0x3f);
  2798. };
  2799.  
  2800. /**
  2801. * Detects if the 2-byte packet data is an extended character
  2802. *
  2803. * Extended characters have a second byte in the range 0x20 to 0x3f,
  2804. * with the first byte being 0x12 or 0x13 (for data channel 1) or
  2805. * 0x1a or 0x1b (for data channel 2).
  2806. *
  2807. * @param {Integer} char0 The first byte
  2808. * @param {Integer} char1 The second byte
  2809. * @return {Boolean} Whether the 2 bytes are an extended character
  2810. */
  2811. Cea608Stream.prototype.isExtCharacter = function(char0, char1) {
  2812. return ((char0 === (this.EXT_ + 1) || char0 === (this.EXT_ + 2)) &&
  2813. (char1 >= 0x20 && char1 <= 0x3f));
  2814. };
  2815.  
  2816. /**
  2817. * Detects if the 2-byte packet is a mid-row code
  2818. *
  2819. * Mid-row codes have a second byte in the range 0x20 to 0x2f, with
  2820. * the first byte being 0x11 (for data channel 1) or 0x19 (for data
  2821. * channel 2).
  2822. *
  2823. * @param {Integer} char0 The first byte
  2824. * @param {Integer} char1 The second byte
  2825. * @return {Boolean} Whether the 2 bytes are a mid-row code
  2826. */
  2827. Cea608Stream.prototype.isMidRowCode = function(char0, char1) {
  2828. return (char0 === this.EXT_ && (char1 >= 0x20 && char1 <= 0x2f));
  2829. };
  2830.  
  2831. /**
  2832. * Detects if the 2-byte packet is an offset control code
  2833. *
  2834. * Offset control codes have a second byte in the range 0x21 to 0x23,
  2835. * with the first byte being 0x17 (for data channel 1) or 0x1f (for
  2836. * data channel 2).
  2837. *
  2838. * @param {Integer} char0 The first byte
  2839. * @param {Integer} char1 The second byte
  2840. * @return {Boolean} Whether the 2 bytes are an offset control code
  2841. */
  2842. Cea608Stream.prototype.isOffsetControlCode = function(char0, char1) {
  2843. return (char0 === this.OFFSET_ && (char1 >= 0x21 && char1 <= 0x23));
  2844. };
  2845.  
  2846. /**
  2847. * Detects if the 2-byte packet is a Preamble Address Code
  2848. *
  2849. * PACs have a first byte in the range 0x10 to 0x17 (for data channel 1)
  2850. * or 0x18 to 0x1f (for data channel 2), with the second byte in the
  2851. * range 0x40 to 0x7f.
  2852. *
  2853. * @param {Integer} char0 The first byte
  2854. * @param {Integer} char1 The second byte
  2855. * @return {Boolean} Whether the 2 bytes are a PAC
  2856. */
  2857. Cea608Stream.prototype.isPAC = function(char0, char1) {
  2858. return (char0 >= this.BASE_ && char0 < (this.BASE_ + 8) &&
  2859. (char1 >= 0x40 && char1 <= 0x7f));
  2860. };
  2861.  
  2862. /**
  2863. * Detects if a packet's second byte is in the range of a PAC color code
  2864. *
  2865. * PAC color codes have the second byte be in the range 0x40 to 0x4f, or
  2866. * 0x60 to 0x6f.
  2867. *
  2868. * @param {Integer} char1 The second byte
  2869. * @return {Boolean} Whether the byte is a color PAC
  2870. */
  2871. Cea608Stream.prototype.isColorPAC = function(char1) {
  2872. return ((char1 >= 0x40 && char1 <= 0x4f) || (char1 >= 0x60 && char1 <= 0x7f));
  2873. };
  2874.  
  2875. /**
  2876. * Detects if a single byte is in the range of a normal character
  2877. *
  2878. * Normal text bytes are in the range 0x20 to 0x7f.
  2879. *
  2880. * @param {Integer} char The byte
  2881. * @return {Boolean} Whether the byte is a normal character
  2882. */
  2883. Cea608Stream.prototype.isNormalChar = function(char) {
  2884. return (char >= 0x20 && char <= 0x7f);
  2885. };
  2886.  
  2887. /**
  2888. * Configures roll-up
  2889. *
  2890. * @param {Integer} pts Current PTS
  2891. * @param {Integer} newBaseRow Used by PACs to slide the current window to
  2892. * a new position
  2893. */
  2894. Cea608Stream.prototype.setRollUp = function(pts, newBaseRow) {
  2895. // Reset the base row to the bottom row when switching modes
  2896. if (this.mode_ !== 'rollUp') {
  2897. this.row_ = BOTTOM_ROW;
  2898. this.mode_ = 'rollUp';
  2899. // Spec says to wipe memories when switching to roll-up
  2900. this.flushDisplayed(pts);
  2901. this.nonDisplayed_ = createDisplayBuffer();
  2902. this.displayed_ = createDisplayBuffer();
  2903. }
  2904.  
  2905. if (newBaseRow !== undefined && newBaseRow !== this.row_) {
  2906. // move currently displayed captions (up or down) to the new base row
  2907. for (var i = 0; i < this.rollUpRows_; i++) {
  2908. this.displayed_[newBaseRow - i] = this.displayed_[this.row_ - i];
  2909. this.displayed_[this.row_ - i] = '';
  2910. }
  2911. }
  2912.  
  2913. if (newBaseRow === undefined) {
  2914. newBaseRow = this.row_;
  2915. }
  2916.  
  2917. this.topRow_ = newBaseRow - this.rollUpRows_ + 1;
  2918. };
  2919.  
  2920. // Adds the opening HTML tag for the passed character to the caption text,
  2921. // and keeps track of it for later closing
  2922. Cea608Stream.prototype.addFormatting = function(pts, format) {
  2923. this.formatting_ = this.formatting_.concat(format);
  2924. var text = format.reduce(function(text, format) {
  2925. return text + '<' + format + '>';
  2926. }, '');
  2927. this[this.mode_](pts, text);
  2928. };
  2929.  
  2930. // Adds HTML closing tags for current formatting to caption text and
  2931. // clears remembered formatting
  2932. Cea608Stream.prototype.clearFormatting = function(pts) {
  2933. if (!this.formatting_.length) {
  2934. return;
  2935. }
  2936. var text = this.formatting_.reverse().reduce(function(text, format) {
  2937. return text + '</' + format + '>';
  2938. }, '');
  2939. this.formatting_ = [];
  2940. this[this.mode_](pts, text);
  2941. };
  2942.  
  2943. // Mode Implementations
  2944. Cea608Stream.prototype.popOn = function(pts, text) {
  2945. var baseRow = this.nonDisplayed_[this.row_];
  2946.  
  2947. // buffer characters
  2948. baseRow += text;
  2949. this.nonDisplayed_[this.row_] = baseRow;
  2950. };
  2951.  
  2952. Cea608Stream.prototype.rollUp = function(pts, text) {
  2953. var baseRow = this.displayed_[this.row_];
  2954.  
  2955. baseRow += text;
  2956. this.displayed_[this.row_] = baseRow;
  2957.  
  2958. };
  2959.  
  2960. Cea608Stream.prototype.shiftRowsUp_ = function() {
  2961. var i;
  2962. // clear out inactive rows
  2963. for (i = 0; i < this.topRow_; i++) {
  2964. this.displayed_[i] = '';
  2965. }
  2966. for (i = this.row_ + 1; i < BOTTOM_ROW + 1; i++) {
  2967. this.displayed_[i] = '';
  2968. }
  2969. // shift displayed rows up
  2970. for (i = this.topRow_; i < this.row_; i++) {
  2971. this.displayed_[i] = this.displayed_[i + 1];
  2972. }
  2973. // clear out the bottom row
  2974. this.displayed_[this.row_] = '';
  2975. };
  2976.  
  2977. Cea608Stream.prototype.paintOn = function(pts, text) {
  2978. var baseRow = this.displayed_[this.row_];
  2979.  
  2980. baseRow += text;
  2981. this.displayed_[this.row_] = baseRow;
  2982. };
  2983.  
  2984. // exports
  2985. module.exports = {
  2986. CaptionStream: CaptionStream,
  2987. Cea608Stream: Cea608Stream
  2988. };
  2989.  
  2990. },{"33":33,"40":40}],15:[function(require,module,exports){
  2991. /**
  2992. * mux.js
  2993. *
  2994. * Copyright (c) Brightcove
  2995. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  2996. */
  2997. module.exports = require(16);
  2998.  
  2999. },{"16":16}],16:[function(require,module,exports){
  3000. /**
  3001. * mux.js
  3002. *
  3003. * Copyright (c) Brightcove
  3004. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3005. *
  3006. * A stream-based mp2t to mp4 converter. This utility can be used to
  3007. * deliver mp4s to a SourceBuffer on platforms that support native
  3008. * Media Source Extensions.
  3009. */
  3010. 'use strict';
  3011. var Stream = require(40),
  3012. CaptionStream = require(14),
  3013. StreamTypes = require(19),
  3014. TimestampRolloverStream = require(20).TimestampRolloverStream;
  3015.  
  3016. var m2tsStreamTypes = require(19);
  3017.  
  3018. // object types
  3019. var TransportPacketStream, TransportParseStream, ElementaryStream;
  3020.  
  3021. // constants
  3022. var
  3023. MP2T_PACKET_LENGTH = 188, // bytes
  3024. SYNC_BYTE = 0x47;
  3025.  
  3026. /**
  3027. * Splits an incoming stream of binary data into MPEG-2 Transport
  3028. * Stream packets.
  3029. */
  3030. TransportPacketStream = function() {
  3031. var
  3032. buffer = new Uint8Array(MP2T_PACKET_LENGTH),
  3033. bytesInBuffer = 0;
  3034.  
  3035. TransportPacketStream.prototype.init.call(this);
  3036.  
  3037. // Deliver new bytes to the stream.
  3038.  
  3039. /**
  3040. * Split a stream of data into M2TS packets
  3041. **/
  3042. this.push = function(bytes) {
  3043. var
  3044. startIndex = 0,
  3045. endIndex = MP2T_PACKET_LENGTH,
  3046. everything;
  3047.  
  3048. // If there are bytes remaining from the last segment, prepend them to the
  3049. // bytes that were pushed in
  3050. if (bytesInBuffer) {
  3051. everything = new Uint8Array(bytes.byteLength + bytesInBuffer);
  3052. everything.set(buffer.subarray(0, bytesInBuffer));
  3053. everything.set(bytes, bytesInBuffer);
  3054. bytesInBuffer = 0;
  3055. } else {
  3056. everything = bytes;
  3057. }
  3058.  
  3059. // While we have enough data for a packet
  3060. while (endIndex < everything.byteLength) {
  3061. // Look for a pair of start and end sync bytes in the data..
  3062. if (everything[startIndex] === SYNC_BYTE && everything[endIndex] === SYNC_BYTE) {
  3063. // We found a packet so emit it and jump one whole packet forward in
  3064. // the stream
  3065. this.trigger('data', everything.subarray(startIndex, endIndex));
  3066. startIndex += MP2T_PACKET_LENGTH;
  3067. endIndex += MP2T_PACKET_LENGTH;
  3068. continue;
  3069. }
  3070. // If we get here, we have somehow become de-synchronized and we need to step
  3071. // forward one byte at a time until we find a pair of sync bytes that denote
  3072. // a packet
  3073. startIndex++;
  3074. endIndex++;
  3075. }
  3076.  
  3077. // If there was some data left over at the end of the segment that couldn't
  3078. // possibly be a whole packet, keep it because it might be the start of a packet
  3079. // that continues in the next segment
  3080. if (startIndex < everything.byteLength) {
  3081. buffer.set(everything.subarray(startIndex), 0);
  3082. bytesInBuffer = everything.byteLength - startIndex;
  3083. }
  3084. };
  3085.  
  3086. /**
  3087. * Passes identified M2TS packets to the TransportParseStream to be parsed
  3088. **/
  3089. this.flush = function() {
  3090. // If the buffer contains a whole packet when we are being flushed, emit it
  3091. // and empty the buffer. Otherwise hold onto the data because it may be
  3092. // important for decoding the next segment
  3093. if (bytesInBuffer === MP2T_PACKET_LENGTH && buffer[0] === SYNC_BYTE) {
  3094. this.trigger('data', buffer);
  3095. bytesInBuffer = 0;
  3096. }
  3097. this.trigger('done');
  3098. };
  3099.  
  3100. this.endTimeline = function() {
  3101. this.flush();
  3102. this.trigger('endedtimeline');
  3103. };
  3104.  
  3105. this.reset = function() {
  3106. bytesInBuffer = 0;
  3107. this.trigger('reset');
  3108. };
  3109. };
  3110. TransportPacketStream.prototype = new Stream();
  3111.  
  3112. /**
  3113. * Accepts an MP2T TransportPacketStream and emits data events with parsed
  3114. * forms of the individual transport stream packets.
  3115. */
  3116. TransportParseStream = function() {
  3117. var parsePsi, parsePat, parsePmt, self;
  3118. TransportParseStream.prototype.init.call(this);
  3119. self = this;
  3120.  
  3121. this.packetsWaitingForPmt = [];
  3122. this.programMapTable = undefined;
  3123.  
  3124. parsePsi = function(payload, psi) {
  3125. var offset = 0;
  3126.  
  3127. // PSI packets may be split into multiple sections and those
  3128. // sections may be split into multiple packets. If a PSI
  3129. // section starts in this packet, the payload_unit_start_indicator
  3130. // will be true and the first byte of the payload will indicate
  3131. // the offset from the current position to the start of the
  3132. // section.
  3133. if (psi.payloadUnitStartIndicator) {
  3134. offset += payload[offset] + 1;
  3135. }
  3136.  
  3137. if (psi.type === 'pat') {
  3138. parsePat(payload.subarray(offset), psi);
  3139. } else {
  3140. parsePmt(payload.subarray(offset), psi);
  3141. }
  3142. };
  3143.  
  3144. parsePat = function(payload, pat) {
  3145. pat.section_number = payload[7]; // eslint-disable-line camelcase
  3146. pat.last_section_number = payload[8]; // eslint-disable-line camelcase
  3147.  
  3148. // skip the PSI header and parse the first PMT entry
  3149. self.pmtPid = (payload[10] & 0x1F) << 8 | payload[11];
  3150. pat.pmtPid = self.pmtPid;
  3151. };
  3152.  
  3153. /**
  3154. * Parse out the relevant fields of a Program Map Table (PMT).
  3155. * @param payload {Uint8Array} the PMT-specific portion of an MP2T
  3156. * packet. The first byte in this array should be the table_id
  3157. * field.
  3158. * @param pmt {object} the object that should be decorated with
  3159. * fields parsed from the PMT.
  3160. */
  3161. parsePmt = function(payload, pmt) {
  3162. var sectionLength, tableEnd, programInfoLength, offset;
  3163.  
  3164. // PMTs can be sent ahead of the time when they should actually
  3165. // take effect. We don't believe this should ever be the case
  3166. // for HLS but we'll ignore "forward" PMT declarations if we see
  3167. // them. Future PMT declarations have the current_next_indicator
  3168. // set to zero.
  3169. if (!(payload[5] & 0x01)) {
  3170. return;
  3171. }
  3172.  
  3173. // overwrite any existing program map table
  3174. self.programMapTable = {
  3175. video: null,
  3176. audio: null,
  3177. 'timed-metadata': {}
  3178. };
  3179.  
  3180. // the mapping table ends at the end of the current section
  3181. sectionLength = (payload[1] & 0x0f) << 8 | payload[2];
  3182. tableEnd = 3 + sectionLength - 4;
  3183.  
  3184. // to determine where the table is, we have to figure out how
  3185. // long the program info descriptors are
  3186. programInfoLength = (payload[10] & 0x0f) << 8 | payload[11];
  3187.  
  3188. // advance the offset to the first entry in the mapping table
  3189. offset = 12 + programInfoLength;
  3190. while (offset < tableEnd) {
  3191. var streamType = payload[offset];
  3192. var pid = (payload[offset + 1] & 0x1F) << 8 | payload[offset + 2];
  3193.  
  3194. // only map a single elementary_pid for audio and video stream types
  3195. // TODO: should this be done for metadata too? for now maintain behavior of
  3196. // multiple metadata streams
  3197. if (streamType === StreamTypes.H264_STREAM_TYPE &&
  3198. self.programMapTable.video === null) {
  3199. self.programMapTable.video = pid;
  3200. } else if (streamType === StreamTypes.ADTS_STREAM_TYPE &&
  3201. self.programMapTable.audio === null) {
  3202. self.programMapTable.audio = pid;
  3203. } else if (streamType === StreamTypes.METADATA_STREAM_TYPE) {
  3204. // map pid to stream type for metadata streams
  3205. self.programMapTable['timed-metadata'][pid] = streamType;
  3206. }
  3207.  
  3208. // move to the next table entry
  3209. // skip past the elementary stream descriptors, if present
  3210. offset += ((payload[offset + 3] & 0x0F) << 8 | payload[offset + 4]) + 5;
  3211. }
  3212.  
  3213. // record the map on the packet as well
  3214. pmt.programMapTable = self.programMapTable;
  3215. };
  3216.  
  3217. /**
  3218. * Deliver a new MP2T packet to the next stream in the pipeline.
  3219. */
  3220. this.push = function(packet) {
  3221. var
  3222. result = {},
  3223. offset = 4;
  3224.  
  3225. result.payloadUnitStartIndicator = !!(packet[1] & 0x40);
  3226.  
  3227. // pid is a 13-bit field starting at the last bit of packet[1]
  3228. result.pid = packet[1] & 0x1f;
  3229. result.pid <<= 8;
  3230. result.pid |= packet[2];
  3231.  
  3232. // if an adaption field is present, its length is specified by the
  3233. // fifth byte of the TS packet header. The adaptation field is
  3234. // used to add stuffing to PES packets that don't fill a complete
  3235. // TS packet, and to specify some forms of timing and control data
  3236. // that we do not currently use.
  3237. if (((packet[3] & 0x30) >>> 4) > 0x01) {
  3238. offset += packet[offset] + 1;
  3239. }
  3240.  
  3241. // parse the rest of the packet based on the type
  3242. if (result.pid === 0) {
  3243. result.type = 'pat';
  3244. parsePsi(packet.subarray(offset), result);
  3245. this.trigger('data', result);
  3246. } else if (result.pid === this.pmtPid) {
  3247. result.type = 'pmt';
  3248. parsePsi(packet.subarray(offset), result);
  3249. this.trigger('data', result);
  3250.  
  3251. // if there are any packets waiting for a PMT to be found, process them now
  3252. while (this.packetsWaitingForPmt.length) {
  3253. this.processPes_.apply(this, this.packetsWaitingForPmt.shift());
  3254. }
  3255. } else if (this.programMapTable === undefined) {
  3256. // When we have not seen a PMT yet, defer further processing of
  3257. // PES packets until one has been parsed
  3258. this.packetsWaitingForPmt.push([packet, offset, result]);
  3259. } else {
  3260. this.processPes_(packet, offset, result);
  3261. }
  3262. };
  3263.  
  3264. this.processPes_ = function(packet, offset, result) {
  3265. // set the appropriate stream type
  3266. if (result.pid === this.programMapTable.video) {
  3267. result.streamType = StreamTypes.H264_STREAM_TYPE;
  3268. } else if (result.pid === this.programMapTable.audio) {
  3269. result.streamType = StreamTypes.ADTS_STREAM_TYPE;
  3270. } else {
  3271. // if not video or audio, it is timed-metadata or unknown
  3272. // if unknown, streamType will be undefined
  3273. result.streamType = this.programMapTable['timed-metadata'][result.pid];
  3274. }
  3275.  
  3276. result.type = 'pes';
  3277. result.data = packet.subarray(offset);
  3278. this.trigger('data', result);
  3279. };
  3280. };
  3281. TransportParseStream.prototype = new Stream();
  3282. TransportParseStream.STREAM_TYPES = {
  3283. h264: 0x1b,
  3284. adts: 0x0f
  3285. };
  3286.  
  3287. /**
  3288. * Reconsistutes program elementary stream (PES) packets from parsed
  3289. * transport stream packets. That is, if you pipe an
  3290. * mp2t.TransportParseStream into a mp2t.ElementaryStream, the output
  3291. * events will be events which capture the bytes for individual PES
  3292. * packets plus relevant metadata that has been extracted from the
  3293. * container.
  3294. */
  3295. ElementaryStream = function() {
  3296. var
  3297. self = this,
  3298. // PES packet fragments
  3299. video = {
  3300. data: [],
  3301. size: 0
  3302. },
  3303. audio = {
  3304. data: [],
  3305. size: 0
  3306. },
  3307. timedMetadata = {
  3308. data: [],
  3309. size: 0
  3310. },
  3311. programMapTable,
  3312. parsePes = function(payload, pes) {
  3313. var ptsDtsFlags;
  3314.  
  3315. // get the packet length, this will be 0 for video
  3316. pes.packetLength = 6 + ((payload[4] << 8) | payload[5]);
  3317.  
  3318. // find out if this packets starts a new keyframe
  3319. pes.dataAlignmentIndicator = (payload[6] & 0x04) !== 0;
  3320. // PES packets may be annotated with a PTS value, or a PTS value
  3321. // and a DTS value. Determine what combination of values is
  3322. // available to work with.
  3323. ptsDtsFlags = payload[7];
  3324.  
  3325. // PTS and DTS are normally stored as a 33-bit number. Javascript
  3326. // performs all bitwise operations on 32-bit integers but javascript
  3327. // supports a much greater range (52-bits) of integer using standard
  3328. // mathematical operations.
  3329. // We construct a 31-bit value using bitwise operators over the 31
  3330. // most significant bits and then multiply by 4 (equal to a left-shift
  3331. // of 2) before we add the final 2 least significant bits of the
  3332. // timestamp (equal to an OR.)
  3333. if (ptsDtsFlags & 0xC0) {
  3334. // the PTS and DTS are not written out directly. For information
  3335. // on how they are encoded, see
  3336. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  3337. pes.pts = (payload[9] & 0x0E) << 27 |
  3338. (payload[10] & 0xFF) << 20 |
  3339. (payload[11] & 0xFE) << 12 |
  3340. (payload[12] & 0xFF) << 5 |
  3341. (payload[13] & 0xFE) >>> 3;
  3342. pes.pts *= 4; // Left shift by 2
  3343. pes.pts += (payload[13] & 0x06) >>> 1; // OR by the two LSBs
  3344. pes.dts = pes.pts;
  3345. if (ptsDtsFlags & 0x40) {
  3346. pes.dts = (payload[14] & 0x0E) << 27 |
  3347. (payload[15] & 0xFF) << 20 |
  3348. (payload[16] & 0xFE) << 12 |
  3349. (payload[17] & 0xFF) << 5 |
  3350. (payload[18] & 0xFE) >>> 3;
  3351. pes.dts *= 4; // Left shift by 2
  3352. pes.dts += (payload[18] & 0x06) >>> 1; // OR by the two LSBs
  3353. }
  3354. }
  3355. // the data section starts immediately after the PES header.
  3356. // pes_header_data_length specifies the number of header bytes
  3357. // that follow the last byte of the field.
  3358. pes.data = payload.subarray(9 + payload[8]);
  3359. },
  3360. /**
  3361. * Pass completely parsed PES packets to the next stream in the pipeline
  3362. **/
  3363. flushStream = function(stream, type, forceFlush) {
  3364. var
  3365. packetData = new Uint8Array(stream.size),
  3366. event = {
  3367. type: type
  3368. },
  3369. i = 0,
  3370. offset = 0,
  3371. packetFlushable = false,
  3372. fragment;
  3373.  
  3374. // do nothing if there is not enough buffered data for a complete
  3375. // PES header
  3376. if (!stream.data.length || stream.size < 9) {
  3377. return;
  3378. }
  3379. event.trackId = stream.data[0].pid;
  3380.  
  3381. // reassemble the packet
  3382. for (i = 0; i < stream.data.length; i++) {
  3383. fragment = stream.data[i];
  3384.  
  3385. packetData.set(fragment.data, offset);
  3386. offset += fragment.data.byteLength;
  3387. }
  3388.  
  3389. // parse assembled packet's PES header
  3390. parsePes(packetData, event);
  3391.  
  3392. // non-video PES packets MUST have a non-zero PES_packet_length
  3393. // check that there is enough stream data to fill the packet
  3394. packetFlushable = type === 'video' || event.packetLength <= stream.size;
  3395.  
  3396. // flush pending packets if the conditions are right
  3397. if (forceFlush || packetFlushable) {
  3398. stream.size = 0;
  3399. stream.data.length = 0;
  3400. }
  3401.  
  3402. // only emit packets that are complete. this is to avoid assembling
  3403. // incomplete PES packets due to poor segmentation
  3404. if (packetFlushable) {
  3405. self.trigger('data', event);
  3406. }
  3407. };
  3408.  
  3409. ElementaryStream.prototype.init.call(this);
  3410.  
  3411. /**
  3412. * Identifies M2TS packet types and parses PES packets using metadata
  3413. * parsed from the PMT
  3414. **/
  3415. this.push = function(data) {
  3416. ({
  3417. pat: function() {
  3418. // we have to wait for the PMT to arrive as well before we
  3419. // have any meaningful metadata
  3420. },
  3421. pes: function() {
  3422. var stream, streamType;
  3423.  
  3424. switch (data.streamType) {
  3425. case StreamTypes.H264_STREAM_TYPE:
  3426. case m2tsStreamTypes.H264_STREAM_TYPE:
  3427. stream = video;
  3428. streamType = 'video';
  3429. break;
  3430. case StreamTypes.ADTS_STREAM_TYPE:
  3431. stream = audio;
  3432. streamType = 'audio';
  3433. break;
  3434. case StreamTypes.METADATA_STREAM_TYPE:
  3435. stream = timedMetadata;
  3436. streamType = 'timed-metadata';
  3437. break;
  3438. default:
  3439. // ignore unknown stream types
  3440. return;
  3441. }
  3442.  
  3443. // if a new packet is starting, we can flush the completed
  3444. // packet
  3445. if (data.payloadUnitStartIndicator) {
  3446. flushStream(stream, streamType, true);
  3447. }
  3448.  
  3449. // buffer this fragment until we are sure we've received the
  3450. // complete payload
  3451. stream.data.push(data);
  3452. stream.size += data.data.byteLength;
  3453. },
  3454. pmt: function() {
  3455. var
  3456. event = {
  3457. type: 'metadata',
  3458. tracks: []
  3459. };
  3460.  
  3461. programMapTable = data.programMapTable;
  3462.  
  3463. // translate audio and video streams to tracks
  3464. if (programMapTable.video !== null) {
  3465. event.tracks.push({
  3466. timelineStartInfo: {
  3467. baseMediaDecodeTime: 0
  3468. },
  3469. id: +programMapTable.video,
  3470. codec: 'avc',
  3471. type: 'video'
  3472. });
  3473. }
  3474. if (programMapTable.audio !== null) {
  3475. event.tracks.push({
  3476. timelineStartInfo: {
  3477. baseMediaDecodeTime: 0
  3478. },
  3479. id: +programMapTable.audio,
  3480. codec: 'adts',
  3481. type: 'audio'
  3482. });
  3483. }
  3484.  
  3485. self.trigger('data', event);
  3486. }
  3487. })[data.type]();
  3488. };
  3489.  
  3490. this.reset = function() {
  3491. video.size = 0;
  3492. video.data.length = 0;
  3493. audio.size = 0;
  3494. audio.data.length = 0;
  3495. this.trigger('reset');
  3496. };
  3497.  
  3498. /**
  3499. * Flush any remaining input. Video PES packets may be of variable
  3500. * length. Normally, the start of a new video packet can trigger the
  3501. * finalization of the previous packet. That is not possible if no
  3502. * more video is forthcoming, however. In that case, some other
  3503. * mechanism (like the end of the file) has to be employed. When it is
  3504. * clear that no additional data is forthcoming, calling this method
  3505. * will flush the buffered packets.
  3506. */
  3507. this.flushStreams_ = function() {
  3508. // !!THIS ORDER IS IMPORTANT!!
  3509. // video first then audio
  3510. flushStream(video, 'video');
  3511. flushStream(audio, 'audio');
  3512. flushStream(timedMetadata, 'timed-metadata');
  3513. };
  3514.  
  3515. this.flush = function() {
  3516. this.flushStreams_();
  3517. this.trigger('done');
  3518. };
  3519. };
  3520. ElementaryStream.prototype = new Stream();
  3521.  
  3522. var m2ts = {
  3523. PAT_PID: 0x0000,
  3524. MP2T_PACKET_LENGTH: MP2T_PACKET_LENGTH,
  3525. TransportPacketStream: TransportPacketStream,
  3526. TransportParseStream: TransportParseStream,
  3527. ElementaryStream: ElementaryStream,
  3528. TimestampRolloverStream: TimestampRolloverStream,
  3529. CaptionStream: CaptionStream.CaptionStream,
  3530. Cea608Stream: CaptionStream.Cea608Stream,
  3531. MetadataStream: require(17)
  3532. };
  3533.  
  3534. for (var type in StreamTypes) {
  3535. if (StreamTypes.hasOwnProperty(type)) {
  3536. m2ts[type] = StreamTypes[type];
  3537. }
  3538. }
  3539.  
  3540. module.exports = m2ts;
  3541.  
  3542. },{"14":14,"17":17,"19":19,"20":20,"40":40}],17:[function(require,module,exports){
  3543. /**
  3544. * mux.js
  3545. *
  3546. * Copyright (c) Brightcove
  3547. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3548. *
  3549. * Accepts program elementary stream (PES) data events and parses out
  3550. * ID3 metadata from them, if present.
  3551. * @see http://id3.org/id3v2.3.0
  3552. */
  3553. 'use strict';
  3554. var
  3555. Stream = require(40),
  3556. StreamTypes = require(19),
  3557. // return a percent-encoded representation of the specified byte range
  3558. // @see http://en.wikipedia.org/wiki/Percent-encoding
  3559. percentEncode = function(bytes, start, end) {
  3560. var i, result = '';
  3561. for (i = start; i < end; i++) {
  3562. result += '%' + ('00' + bytes[i].toString(16)).slice(-2);
  3563. }
  3564. return result;
  3565. },
  3566. // return the string representation of the specified byte range,
  3567. // interpreted as UTf-8.
  3568. parseUtf8 = function(bytes, start, end) {
  3569. return decodeURIComponent(percentEncode(bytes, start, end));
  3570. },
  3571. // return the string representation of the specified byte range,
  3572. // interpreted as ISO-8859-1.
  3573. parseIso88591 = function(bytes, start, end) {
  3574. return unescape(percentEncode(bytes, start, end)); // jshint ignore:line
  3575. },
  3576. parseSyncSafeInteger = function(data) {
  3577. return (data[0] << 21) |
  3578. (data[1] << 14) |
  3579. (data[2] << 7) |
  3580. (data[3]);
  3581. },
  3582. tagParsers = {
  3583. TXXX: function(tag) {
  3584. var i;
  3585. if (tag.data[0] !== 3) {
  3586. // ignore frames with unrecognized character encodings
  3587. return;
  3588. }
  3589.  
  3590. for (i = 1; i < tag.data.length; i++) {
  3591. if (tag.data[i] === 0) {
  3592. // parse the text fields
  3593. tag.description = parseUtf8(tag.data, 1, i);
  3594. // do not include the null terminator in the tag value
  3595. tag.value = parseUtf8(tag.data, i + 1, tag.data.length).replace(/\0*$/, '');
  3596. break;
  3597. }
  3598. }
  3599. tag.data = tag.value;
  3600. },
  3601. WXXX: function(tag) {
  3602. var i;
  3603. if (tag.data[0] !== 3) {
  3604. // ignore frames with unrecognized character encodings
  3605. return;
  3606. }
  3607.  
  3608. for (i = 1; i < tag.data.length; i++) {
  3609. if (tag.data[i] === 0) {
  3610. // parse the description and URL fields
  3611. tag.description = parseUtf8(tag.data, 1, i);
  3612. tag.url = parseUtf8(tag.data, i + 1, tag.data.length);
  3613. break;
  3614. }
  3615. }
  3616. },
  3617. PRIV: function(tag) {
  3618. var i;
  3619.  
  3620. for (i = 0; i < tag.data.length; i++) {
  3621. if (tag.data[i] === 0) {
  3622. // parse the description and URL fields
  3623. tag.owner = parseIso88591(tag.data, 0, i);
  3624. break;
  3625. }
  3626. }
  3627. tag.privateData = tag.data.subarray(i + 1);
  3628. tag.data = tag.privateData;
  3629. }
  3630. },
  3631. MetadataStream;
  3632.  
  3633. MetadataStream = function(options) {
  3634. var
  3635. settings = {
  3636. debug: !!(options && options.debug),
  3637.  
  3638. // the bytes of the program-level descriptor field in MP2T
  3639. // see ISO/IEC 13818-1:2013 (E), section 2.6 "Program and
  3640. // program element descriptors"
  3641. descriptor: options && options.descriptor
  3642. },
  3643. // the total size in bytes of the ID3 tag being parsed
  3644. tagSize = 0,
  3645. // tag data that is not complete enough to be parsed
  3646. buffer = [],
  3647. // the total number of bytes currently in the buffer
  3648. bufferSize = 0,
  3649. i;
  3650.  
  3651. MetadataStream.prototype.init.call(this);
  3652.  
  3653. // calculate the text track in-band metadata track dispatch type
  3654. // https://html.spec.whatwg.org/multipage/embedded-content.html#steps-to-expose-a-media-resource-specific-text-track
  3655. this.dispatchType = StreamTypes.METADATA_STREAM_TYPE.toString(16);
  3656. if (settings.descriptor) {
  3657. for (i = 0; i < settings.descriptor.length; i++) {
  3658. this.dispatchType += ('00' + settings.descriptor[i].toString(16)).slice(-2);
  3659. }
  3660. }
  3661.  
  3662. this.push = function(chunk) {
  3663. var tag, frameStart, frameSize, frame, i, frameHeader;
  3664. if (chunk.type !== 'timed-metadata') {
  3665. return;
  3666. }
  3667.  
  3668. // if data_alignment_indicator is set in the PES header,
  3669. // we must have the start of a new ID3 tag. Assume anything
  3670. // remaining in the buffer was malformed and throw it out
  3671. if (chunk.dataAlignmentIndicator) {
  3672. bufferSize = 0;
  3673. buffer.length = 0;
  3674. }
  3675.  
  3676. // ignore events that don't look like ID3 data
  3677. if (buffer.length === 0 &&
  3678. (chunk.data.length < 10 ||
  3679. chunk.data[0] !== 'I'.charCodeAt(0) ||
  3680. chunk.data[1] !== 'D'.charCodeAt(0) ||
  3681. chunk.data[2] !== '3'.charCodeAt(0))) {
  3682. if (settings.debug) {
  3683. // eslint-disable-next-line no-console
  3684. console.log('Skipping unrecognized metadata packet');
  3685. }
  3686. return;
  3687. }
  3688.  
  3689. // add this chunk to the data we've collected so far
  3690.  
  3691. buffer.push(chunk);
  3692. bufferSize += chunk.data.byteLength;
  3693.  
  3694. // grab the size of the entire frame from the ID3 header
  3695. if (buffer.length === 1) {
  3696. // the frame size is transmitted as a 28-bit integer in the
  3697. // last four bytes of the ID3 header.
  3698. // The most significant bit of each byte is dropped and the
  3699. // results concatenated to recover the actual value.
  3700. tagSize = parseSyncSafeInteger(chunk.data.subarray(6, 10));
  3701.  
  3702. // ID3 reports the tag size excluding the header but it's more
  3703. // convenient for our comparisons to include it
  3704. tagSize += 10;
  3705. }
  3706.  
  3707. // if the entire frame has not arrived, wait for more data
  3708. if (bufferSize < tagSize) {
  3709. return;
  3710. }
  3711.  
  3712. // collect the entire frame so it can be parsed
  3713. tag = {
  3714. data: new Uint8Array(tagSize),
  3715. frames: [],
  3716. pts: buffer[0].pts,
  3717. dts: buffer[0].dts
  3718. };
  3719. for (i = 0; i < tagSize;) {
  3720. tag.data.set(buffer[0].data.subarray(0, tagSize - i), i);
  3721. i += buffer[0].data.byteLength;
  3722. bufferSize -= buffer[0].data.byteLength;
  3723. buffer.shift();
  3724. }
  3725.  
  3726. // find the start of the first frame and the end of the tag
  3727. frameStart = 10;
  3728. if (tag.data[5] & 0x40) {
  3729. // advance the frame start past the extended header
  3730. frameStart += 4; // header size field
  3731. frameStart += parseSyncSafeInteger(tag.data.subarray(10, 14));
  3732.  
  3733. // clip any padding off the end
  3734. tagSize -= parseSyncSafeInteger(tag.data.subarray(16, 20));
  3735. }
  3736.  
  3737. // parse one or more ID3 frames
  3738. // http://id3.org/id3v2.3.0#ID3v2_frame_overview
  3739. do {
  3740. // determine the number of bytes in this frame
  3741. frameSize = parseSyncSafeInteger(tag.data.subarray(frameStart + 4, frameStart + 8));
  3742. if (frameSize < 1) {
  3743. // eslint-disable-next-line no-console
  3744. return console.log('Malformed ID3 frame encountered. Skipping metadata parsing.');
  3745. }
  3746. frameHeader = String.fromCharCode(tag.data[frameStart],
  3747. tag.data[frameStart + 1],
  3748. tag.data[frameStart + 2],
  3749. tag.data[frameStart + 3]);
  3750.  
  3751.  
  3752. frame = {
  3753. id: frameHeader,
  3754. data: tag.data.subarray(frameStart + 10, frameStart + frameSize + 10)
  3755. };
  3756. frame.key = frame.id;
  3757. if (tagParsers[frame.id]) {
  3758. tagParsers[frame.id](frame);
  3759.  
  3760. // handle the special PRIV frame used to indicate the start
  3761. // time for raw AAC data
  3762. if (frame.owner === 'com.apple.streaming.transportStreamTimestamp') {
  3763. var
  3764. d = frame.data,
  3765. size = ((d[3] & 0x01) << 30) |
  3766. (d[4] << 22) |
  3767. (d[5] << 14) |
  3768. (d[6] << 6) |
  3769. (d[7] >>> 2);
  3770.  
  3771. size *= 4;
  3772. size += d[7] & 0x03;
  3773. frame.timeStamp = size;
  3774. // in raw AAC, all subsequent data will be timestamped based
  3775. // on the value of this frame
  3776. // we couldn't have known the appropriate pts and dts before
  3777. // parsing this ID3 tag so set those values now
  3778. if (tag.pts === undefined && tag.dts === undefined) {
  3779. tag.pts = frame.timeStamp;
  3780. tag.dts = frame.timeStamp;
  3781. }
  3782. this.trigger('timestamp', frame);
  3783. }
  3784. }
  3785. tag.frames.push(frame);
  3786.  
  3787. frameStart += 10; // advance past the frame header
  3788. frameStart += frameSize; // advance past the frame body
  3789. } while (frameStart < tagSize);
  3790. this.trigger('data', tag);
  3791. };
  3792. };
  3793. MetadataStream.prototype = new Stream();
  3794.  
  3795. module.exports = MetadataStream;
  3796.  
  3797. },{"19":19,"40":40}],18:[function(require,module,exports){
  3798. /**
  3799. * mux.js
  3800. *
  3801. * Copyright (c) Brightcove
  3802. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  3803. *
  3804. * Utilities to detect basic properties and metadata about TS Segments.
  3805. */
  3806. 'use strict';
  3807.  
  3808. var StreamTypes = require(19);
  3809.  
  3810. var parsePid = function(packet) {
  3811. var pid = packet[1] & 0x1f;
  3812. pid <<= 8;
  3813. pid |= packet[2];
  3814. return pid;
  3815. };
  3816.  
  3817. var parsePayloadUnitStartIndicator = function(packet) {
  3818. return !!(packet[1] & 0x40);
  3819. };
  3820.  
  3821. var parseAdaptionField = function(packet) {
  3822. var offset = 0;
  3823. // if an adaption field is present, its length is specified by the
  3824. // fifth byte of the TS packet header. The adaptation field is
  3825. // used to add stuffing to PES packets that don't fill a complete
  3826. // TS packet, and to specify some forms of timing and control data
  3827. // that we do not currently use.
  3828. if (((packet[3] & 0x30) >>> 4) > 0x01) {
  3829. offset += packet[4] + 1;
  3830. }
  3831. return offset;
  3832. };
  3833.  
  3834. var parseType = function(packet, pmtPid) {
  3835. var pid = parsePid(packet);
  3836. if (pid === 0) {
  3837. return 'pat';
  3838. } else if (pid === pmtPid) {
  3839. return 'pmt';
  3840. } else if (pmtPid) {
  3841. return 'pes';
  3842. }
  3843. return null;
  3844. };
  3845.  
  3846. var parsePat = function(packet) {
  3847. var pusi = parsePayloadUnitStartIndicator(packet);
  3848. var offset = 4 + parseAdaptionField(packet);
  3849.  
  3850. if (pusi) {
  3851. offset += packet[offset] + 1;
  3852. }
  3853.  
  3854. return (packet[offset + 10] & 0x1f) << 8 | packet[offset + 11];
  3855. };
  3856.  
  3857. var parsePmt = function(packet) {
  3858. var programMapTable = {};
  3859. var pusi = parsePayloadUnitStartIndicator(packet);
  3860. var payloadOffset = 4 + parseAdaptionField(packet);
  3861.  
  3862. if (pusi) {
  3863. payloadOffset += packet[payloadOffset] + 1;
  3864. }
  3865.  
  3866. // PMTs can be sent ahead of the time when they should actually
  3867. // take effect. We don't believe this should ever be the case
  3868. // for HLS but we'll ignore "forward" PMT declarations if we see
  3869. // them. Future PMT declarations have the current_next_indicator
  3870. // set to zero.
  3871. if (!(packet[payloadOffset + 5] & 0x01)) {
  3872. return;
  3873. }
  3874.  
  3875. var sectionLength, tableEnd, programInfoLength;
  3876. // the mapping table ends at the end of the current section
  3877. sectionLength = (packet[payloadOffset + 1] & 0x0f) << 8 | packet[payloadOffset + 2];
  3878. tableEnd = 3 + sectionLength - 4;
  3879.  
  3880. // to determine where the table is, we have to figure out how
  3881. // long the program info descriptors are
  3882. programInfoLength = (packet[payloadOffset + 10] & 0x0f) << 8 | packet[payloadOffset + 11];
  3883.  
  3884. // advance the offset to the first entry in the mapping table
  3885. var offset = 12 + programInfoLength;
  3886. while (offset < tableEnd) {
  3887. var i = payloadOffset + offset;
  3888. // add an entry that maps the elementary_pid to the stream_type
  3889. programMapTable[(packet[i + 1] & 0x1F) << 8 | packet[i + 2]] = packet[i];
  3890.  
  3891. // move to the next table entry
  3892. // skip past the elementary stream descriptors, if present
  3893. offset += ((packet[i + 3] & 0x0F) << 8 | packet[i + 4]) + 5;
  3894. }
  3895. return programMapTable;
  3896. };
  3897.  
  3898. var parsePesType = function(packet, programMapTable) {
  3899. var pid = parsePid(packet);
  3900. var type = programMapTable[pid];
  3901. switch (type) {
  3902. case StreamTypes.H264_STREAM_TYPE:
  3903. return 'video';
  3904. case StreamTypes.ADTS_STREAM_TYPE:
  3905. return 'audio';
  3906. case StreamTypes.METADATA_STREAM_TYPE:
  3907. return 'timed-metadata';
  3908. default:
  3909. return null;
  3910. }
  3911. };
  3912.  
  3913. var parsePesTime = function(packet) {
  3914. var pusi = parsePayloadUnitStartIndicator(packet);
  3915. if (!pusi) {
  3916. return null;
  3917. }
  3918.  
  3919. var offset = 4 + parseAdaptionField(packet);
  3920.  
  3921. if (offset >= packet.byteLength) {
  3922. // From the H 222.0 MPEG-TS spec
  3923. // "For transport stream packets carrying PES packets, stuffing is needed when there
  3924. // is insufficient PES packet data to completely fill the transport stream packet
  3925. // payload bytes. Stuffing is accomplished by defining an adaptation field longer than
  3926. // the sum of the lengths of the data elements in it, so that the payload bytes
  3927. // remaining after the adaptation field exactly accommodates the available PES packet
  3928. // data."
  3929. //
  3930. // If the offset is >= the length of the packet, then the packet contains no data
  3931. // and instead is just adaption field stuffing bytes
  3932. return null;
  3933. }
  3934.  
  3935. var pes = null;
  3936. var ptsDtsFlags;
  3937.  
  3938. // PES packets may be annotated with a PTS value, or a PTS value
  3939. // and a DTS value. Determine what combination of values is
  3940. // available to work with.
  3941. ptsDtsFlags = packet[offset + 7];
  3942.  
  3943. // PTS and DTS are normally stored as a 33-bit number. Javascript
  3944. // performs all bitwise operations on 32-bit integers but javascript
  3945. // supports a much greater range (52-bits) of integer using standard
  3946. // mathematical operations.
  3947. // We construct a 31-bit value using bitwise operators over the 31
  3948. // most significant bits and then multiply by 4 (equal to a left-shift
  3949. // of 2) before we add the final 2 least significant bits of the
  3950. // timestamp (equal to an OR.)
  3951. if (ptsDtsFlags & 0xC0) {
  3952. pes = {};
  3953. // the PTS and DTS are not written out directly. For information
  3954. // on how they are encoded, see
  3955. // http://dvd.sourceforge.net/dvdinfo/pes-hdr.html
  3956. pes.pts = (packet[offset + 9] & 0x0E) << 27 |
  3957. (packet[offset + 10] & 0xFF) << 20 |
  3958. (packet[offset + 11] & 0xFE) << 12 |
  3959. (packet[offset + 12] & 0xFF) << 5 |
  3960. (packet[offset + 13] & 0xFE) >>> 3;
  3961. pes.pts *= 4; // Left shift by 2
  3962. pes.pts += (packet[offset + 13] & 0x06) >>> 1; // OR by the two LSBs
  3963. pes.dts = pes.pts;
  3964. if (ptsDtsFlags & 0x40) {
  3965. pes.dts = (packet[offset + 14] & 0x0E) << 27 |
  3966. (packet[offset + 15] & 0xFF) << 20 |
  3967. (packet[offset + 16] & 0xFE) << 12 |
  3968. (packet[offset + 17] & 0xFF) << 5 |
  3969. (packet[offset + 18] & 0xFE) >>> 3;
  3970. pes.dts *= 4; // Left shift by 2
  3971. pes.dts += (packet[offset + 18] & 0x06) >>> 1; // OR by the two LSBs
  3972. }
  3973. }
  3974. return pes;
  3975. };
  3976.  
  3977. var parseNalUnitType = function(type) {
  3978. switch (type) {
  3979. case 0x05:
  3980. return 'slice_layer_without_partitioning_rbsp_idr';
  3981. case 0x06:
  3982. return 'sei_rbsp';
  3983. case 0x07:
  3984. return 'seq_parameter_set_rbsp';
  3985. case 0x08:
  3986. return 'pic_parameter_set_rbsp';
  3987. case 0x09:
  3988. return 'access_unit_delimiter_rbsp';
  3989. default:
  3990. return null;
  3991. }
  3992. };
  3993.  
  3994. var videoPacketContainsKeyFrame = function(packet) {
  3995. var offset = 4 + parseAdaptionField(packet);
  3996. var frameBuffer = packet.subarray(offset);
  3997. var frameI = 0;
  3998. var frameSyncPoint = 0;
  3999. var foundKeyFrame = false;
  4000. var nalType;
  4001.  
  4002. // advance the sync point to a NAL start, if necessary
  4003. for (; frameSyncPoint < frameBuffer.byteLength - 3; frameSyncPoint++) {
  4004. if (frameBuffer[frameSyncPoint + 2] === 1) {
  4005. // the sync point is properly aligned
  4006. frameI = frameSyncPoint + 5;
  4007. break;
  4008. }
  4009. }
  4010.  
  4011. while (frameI < frameBuffer.byteLength) {
  4012. // look at the current byte to determine if we've hit the end of
  4013. // a NAL unit boundary
  4014. switch (frameBuffer[frameI]) {
  4015. case 0:
  4016. // skip past non-sync sequences
  4017. if (frameBuffer[frameI - 1] !== 0) {
  4018. frameI += 2;
  4019. break;
  4020. } else if (frameBuffer[frameI - 2] !== 0) {
  4021. frameI++;
  4022. break;
  4023. }
  4024.  
  4025. if (frameSyncPoint + 3 !== frameI - 2) {
  4026. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  4027. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  4028. foundKeyFrame = true;
  4029. }
  4030. }
  4031.  
  4032. // drop trailing zeroes
  4033. do {
  4034. frameI++;
  4035. } while (frameBuffer[frameI] !== 1 && frameI < frameBuffer.length);
  4036. frameSyncPoint = frameI - 2;
  4037. frameI += 3;
  4038. break;
  4039. case 1:
  4040. // skip past non-sync sequences
  4041. if (frameBuffer[frameI - 1] !== 0 ||
  4042. frameBuffer[frameI - 2] !== 0) {
  4043. frameI += 3;
  4044. break;
  4045. }
  4046.  
  4047. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  4048. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  4049. foundKeyFrame = true;
  4050. }
  4051. frameSyncPoint = frameI - 2;
  4052. frameI += 3;
  4053. break;
  4054. default:
  4055. // the current byte isn't a one or zero, so it cannot be part
  4056. // of a sync sequence
  4057. frameI += 3;
  4058. break;
  4059. }
  4060. }
  4061. frameBuffer = frameBuffer.subarray(frameSyncPoint);
  4062. frameI -= frameSyncPoint;
  4063. frameSyncPoint = 0;
  4064. // parse the final nal
  4065. if (frameBuffer && frameBuffer.byteLength > 3) {
  4066. nalType = parseNalUnitType(frameBuffer[frameSyncPoint + 3] & 0x1f);
  4067. if (nalType === 'slice_layer_without_partitioning_rbsp_idr') {
  4068. foundKeyFrame = true;
  4069. }
  4070. }
  4071.  
  4072. return foundKeyFrame;
  4073. };
  4074.  
  4075.  
  4076. module.exports = {
  4077. parseType: parseType,
  4078. parsePat: parsePat,
  4079. parsePmt: parsePmt,
  4080. parsePayloadUnitStartIndicator: parsePayloadUnitStartIndicator,
  4081. parsePesType: parsePesType,
  4082. parsePesTime: parsePesTime,
  4083. videoPacketContainsKeyFrame: videoPacketContainsKeyFrame
  4084. };
  4085.  
  4086. },{"19":19}],19:[function(require,module,exports){
  4087. /**
  4088. * mux.js
  4089. *
  4090. * Copyright (c) Brightcove
  4091. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4092. */
  4093. 'use strict';
  4094.  
  4095. module.exports = {
  4096. H264_STREAM_TYPE: 0x1B,
  4097. ADTS_STREAM_TYPE: 0x0F,
  4098. METADATA_STREAM_TYPE: 0x15
  4099. };
  4100.  
  4101. },{}],20:[function(require,module,exports){
  4102. /**
  4103. * mux.js
  4104. *
  4105. * Copyright (c) Brightcove
  4106. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4107. *
  4108. * Accepts program elementary stream (PES) data events and corrects
  4109. * decode and presentation time stamps to account for a rollover
  4110. * of the 33 bit value.
  4111. */
  4112.  
  4113. 'use strict';
  4114.  
  4115. var Stream = require(40);
  4116.  
  4117. var MAX_TS = 8589934592;
  4118.  
  4119. var RO_THRESH = 4294967296;
  4120.  
  4121. var handleRollover = function(value, reference) {
  4122. var direction = 1;
  4123.  
  4124. if (value > reference) {
  4125. // If the current timestamp value is greater than our reference timestamp and we detect a
  4126. // timestamp rollover, this means the roll over is happening in the opposite direction.
  4127. // Example scenario: Enter a long stream/video just after a rollover occurred. The reference
  4128. // point will be set to a small number, e.g. 1. The user then seeks backwards over the
  4129. // rollover point. In loading this segment, the timestamp values will be very large,
  4130. // e.g. 2^33 - 1. Since this comes before the data we loaded previously, we want to adjust
  4131. // the time stamp to be `value - 2^33`.
  4132. direction = -1;
  4133. }
  4134.  
  4135. // Note: A seek forwards or back that is greater than the RO_THRESH (2^32, ~13 hours) will
  4136. // cause an incorrect adjustment.
  4137. while (Math.abs(reference - value) > RO_THRESH) {
  4138. value += (direction * MAX_TS);
  4139. }
  4140.  
  4141. return value;
  4142. };
  4143.  
  4144. var TimestampRolloverStream = function(type) {
  4145. var lastDTS, referenceDTS;
  4146.  
  4147. TimestampRolloverStream.prototype.init.call(this);
  4148.  
  4149. this.type_ = type;
  4150.  
  4151. this.push = function(data) {
  4152. if (data.type !== this.type_) {
  4153. return;
  4154. }
  4155.  
  4156. if (referenceDTS === undefined) {
  4157. referenceDTS = data.dts;
  4158. }
  4159.  
  4160. data.dts = handleRollover(data.dts, referenceDTS);
  4161. data.pts = handleRollover(data.pts, referenceDTS);
  4162.  
  4163. lastDTS = data.dts;
  4164.  
  4165. this.trigger('data', data);
  4166. };
  4167.  
  4168. this.flush = function() {
  4169. referenceDTS = lastDTS;
  4170. this.trigger('done');
  4171. };
  4172.  
  4173. this.endTimeline = function() {
  4174. this.flush();
  4175. this.trigger('endedtimeline');
  4176. };
  4177.  
  4178. this.discontinuity = function() {
  4179. referenceDTS = void 0;
  4180. lastDTS = void 0;
  4181. };
  4182.  
  4183. this.reset = function() {
  4184. this.discontinuity();
  4185. this.trigger('reset');
  4186. };
  4187. };
  4188.  
  4189. TimestampRolloverStream.prototype = new Stream();
  4190.  
  4191. module.exports = {
  4192. TimestampRolloverStream: TimestampRolloverStream,
  4193. handleRollover: handleRollover
  4194. };
  4195.  
  4196. },{"40":40}],21:[function(require,module,exports){
  4197. /**
  4198. * mux.js
  4199. *
  4200. * Copyright (c) Brightcove
  4201. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4202. */
  4203. var coneOfSilence = require(6);
  4204. var clock = require(38);
  4205.  
  4206. /**
  4207. * Sum the `byteLength` properties of the data in each AAC frame
  4208. */
  4209. var sumFrameByteLengths = function(array) {
  4210. var
  4211. i,
  4212. currentObj,
  4213. sum = 0;
  4214.  
  4215. // sum the byteLength's all each nal unit in the frame
  4216. for (i = 0; i < array.length; i++) {
  4217. currentObj = array[i];
  4218. sum += currentObj.data.byteLength;
  4219. }
  4220.  
  4221. return sum;
  4222. };
  4223.  
  4224. // Possibly pad (prefix) the audio track with silence if appending this track
  4225. // would lead to the introduction of a gap in the audio buffer
  4226. var prefixWithSilence = function(
  4227. track,
  4228. frames,
  4229. audioAppendStartTs,
  4230. videoBaseMediaDecodeTime
  4231. ) {
  4232. var
  4233. baseMediaDecodeTimeTs,
  4234. frameDuration = 0,
  4235. audioGapDuration = 0,
  4236. audioFillFrameCount = 0,
  4237. audioFillDuration = 0,
  4238. silentFrame,
  4239. i,
  4240. firstFrame;
  4241.  
  4242. if (!frames.length) {
  4243. return;
  4244. }
  4245.  
  4246. baseMediaDecodeTimeTs =
  4247. clock.audioTsToVideoTs(track.baseMediaDecodeTime, track.samplerate);
  4248. // determine frame clock duration based on sample rate, round up to avoid overfills
  4249. frameDuration = Math.ceil(clock.ONE_SECOND_IN_TS / (track.samplerate / 1024));
  4250.  
  4251. if (audioAppendStartTs && videoBaseMediaDecodeTime) {
  4252. // insert the shortest possible amount (audio gap or audio to video gap)
  4253. audioGapDuration =
  4254. baseMediaDecodeTimeTs - Math.max(audioAppendStartTs, videoBaseMediaDecodeTime);
  4255. // number of full frames in the audio gap
  4256. audioFillFrameCount = Math.floor(audioGapDuration / frameDuration);
  4257. audioFillDuration = audioFillFrameCount * frameDuration;
  4258. }
  4259.  
  4260. // don't attempt to fill gaps smaller than a single frame or larger
  4261. // than a half second
  4262. if (audioFillFrameCount < 1 || audioFillDuration > clock.ONE_SECOND_IN_TS / 2) {
  4263. return;
  4264. }
  4265.  
  4266. silentFrame = coneOfSilence[track.samplerate];
  4267.  
  4268. if (!silentFrame) {
  4269. // we don't have a silent frame pregenerated for the sample rate, so use a frame
  4270. // from the content instead
  4271. silentFrame = frames[0].data;
  4272. }
  4273.  
  4274. for (i = 0; i < audioFillFrameCount; i++) {
  4275. firstFrame = frames[0];
  4276.  
  4277. frames.splice(0, 0, {
  4278. data: silentFrame,
  4279. dts: firstFrame.dts - frameDuration,
  4280. pts: firstFrame.pts - frameDuration
  4281. });
  4282. }
  4283.  
  4284. track.baseMediaDecodeTime -=
  4285. Math.floor(clock.videoTsToAudioTs(audioFillDuration, track.samplerate));
  4286. };
  4287.  
  4288. // If the audio segment extends before the earliest allowed dts
  4289. // value, remove AAC frames until starts at or after the earliest
  4290. // allowed DTS so that we don't end up with a negative baseMedia-
  4291. // DecodeTime for the audio track
  4292. var trimAdtsFramesByEarliestDts = function(adtsFrames, track, earliestAllowedDts) {
  4293. if (track.minSegmentDts >= earliestAllowedDts) {
  4294. return adtsFrames;
  4295. }
  4296.  
  4297. // We will need to recalculate the earliest segment Dts
  4298. track.minSegmentDts = Infinity;
  4299.  
  4300. return adtsFrames.filter(function(currentFrame) {
  4301. // If this is an allowed frame, keep it and record it's Dts
  4302. if (currentFrame.dts >= earliestAllowedDts) {
  4303. track.minSegmentDts = Math.min(track.minSegmentDts, currentFrame.dts);
  4304. track.minSegmentPts = track.minSegmentDts;
  4305. return true;
  4306. }
  4307. // Otherwise, discard it
  4308. return false;
  4309. });
  4310. };
  4311.  
  4312. // generate the track's raw mdat data from an array of frames
  4313. var generateSampleTable = function(frames) {
  4314. var
  4315. i,
  4316. currentFrame,
  4317. samples = [];
  4318.  
  4319. for (i = 0; i < frames.length; i++) {
  4320. currentFrame = frames[i];
  4321. samples.push({
  4322. size: currentFrame.data.byteLength,
  4323. duration: 1024 // For AAC audio, all samples contain 1024 samples
  4324. });
  4325. }
  4326. return samples;
  4327. };
  4328.  
  4329. // generate the track's sample table from an array of frames
  4330. var concatenateFrameData = function(frames) {
  4331. var
  4332. i,
  4333. currentFrame,
  4334. dataOffset = 0,
  4335. data = new Uint8Array(sumFrameByteLengths(frames));
  4336.  
  4337. for (i = 0; i < frames.length; i++) {
  4338. currentFrame = frames[i];
  4339.  
  4340. data.set(currentFrame.data, dataOffset);
  4341. dataOffset += currentFrame.data.byteLength;
  4342. }
  4343. return data;
  4344. };
  4345.  
  4346. module.exports = {
  4347. prefixWithSilence: prefixWithSilence,
  4348. trimAdtsFramesByEarliestDts: trimAdtsFramesByEarliestDts,
  4349. generateSampleTable: generateSampleTable,
  4350. concatenateFrameData: concatenateFrameData
  4351. };
  4352.  
  4353. },{"38":38,"6":6}],22:[function(require,module,exports){
  4354. /**
  4355. * mux.js
  4356. *
  4357. * Copyright (c) Brightcove
  4358. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4359. *
  4360. * Reads in-band CEA-708 captions out of FMP4 segments.
  4361. * @see https://en.wikipedia.org/wiki/CEA-708
  4362. */
  4363. 'use strict';
  4364.  
  4365. var discardEmulationPreventionBytes = require(33).discardEmulationPreventionBytes;
  4366. var CaptionStream = require(14).CaptionStream;
  4367. var probe = require(26);
  4368. var inspect = require(35);
  4369.  
  4370. /**
  4371. * Maps an offset in the mdat to a sample based on the the size of the samples.
  4372. * Assumes that `parseSamples` has been called first.
  4373. *
  4374. * @param {Number} offset - The offset into the mdat
  4375. * @param {Object[]} samples - An array of samples, parsed using `parseSamples`
  4376. * @return {?Object} The matching sample, or null if no match was found.
  4377. *
  4378. * @see ISO-BMFF-12/2015, Section 8.8.8
  4379. **/
  4380. var mapToSample = function(offset, samples) {
  4381. var approximateOffset = offset;
  4382.  
  4383. for (var i = 0; i < samples.length; i++) {
  4384. var sample = samples[i];
  4385.  
  4386. if (approximateOffset < sample.size) {
  4387. return sample;
  4388. }
  4389.  
  4390. approximateOffset -= sample.size;
  4391. }
  4392.  
  4393. return null;
  4394. };
  4395.  
  4396. /**
  4397. * Finds SEI nal units contained in a Media Data Box.
  4398. * Assumes that `parseSamples` has been called first.
  4399. *
  4400. * @param {Uint8Array} avcStream - The bytes of the mdat
  4401. * @param {Object[]} samples - The samples parsed out by `parseSamples`
  4402. * @param {Number} trackId - The trackId of this video track
  4403. * @return {Object[]} seiNals - the parsed SEI NALUs found.
  4404. * The contents of the seiNal should match what is expected by
  4405. * CaptionStream.push (nalUnitType, size, data, escapedRBSP, pts, dts)
  4406. *
  4407. * @see ISO-BMFF-12/2015, Section 8.1.1
  4408. * @see Rec. ITU-T H.264, 7.3.2.3.1
  4409. **/
  4410. var findSeiNals = function(avcStream, samples, trackId) {
  4411. var
  4412. avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  4413. result = [],
  4414. seiNal,
  4415. i,
  4416. length,
  4417. lastMatchedSample;
  4418.  
  4419. for (i = 0; i + 4 < avcStream.length; i += length) {
  4420. length = avcView.getUint32(i);
  4421. i += 4;
  4422.  
  4423. // Bail if this doesn't appear to be an H264 stream
  4424. if (length <= 0) {
  4425. continue;
  4426. }
  4427.  
  4428. switch (avcStream[i] & 0x1F) {
  4429. case 0x06:
  4430. var data = avcStream.subarray(i + 1, i + 1 + length);
  4431. var matchingSample = mapToSample(i, samples);
  4432.  
  4433. seiNal = {
  4434. nalUnitType: 'sei_rbsp',
  4435. size: length,
  4436. data: data,
  4437. escapedRBSP: discardEmulationPreventionBytes(data),
  4438. trackId: trackId
  4439. };
  4440.  
  4441. if (matchingSample) {
  4442. seiNal.pts = matchingSample.pts;
  4443. seiNal.dts = matchingSample.dts;
  4444. lastMatchedSample = matchingSample;
  4445. } else {
  4446. // If a matching sample cannot be found, use the last
  4447. // sample's values as they should be as close as possible
  4448. seiNal.pts = lastMatchedSample.pts;
  4449. seiNal.dts = lastMatchedSample.dts;
  4450. }
  4451.  
  4452. result.push(seiNal);
  4453. break;
  4454. default:
  4455. break;
  4456. }
  4457. }
  4458.  
  4459. return result;
  4460. };
  4461.  
  4462. /**
  4463. * Parses sample information out of Track Run Boxes and calculates
  4464. * the absolute presentation and decode timestamps of each sample.
  4465. *
  4466. * @param {Array<Uint8Array>} truns - The Trun Run boxes to be parsed
  4467. * @param {Number} baseMediaDecodeTime - base media decode time from tfdt
  4468. @see ISO-BMFF-12/2015, Section 8.8.12
  4469. * @param {Object} tfhd - The parsed Track Fragment Header
  4470. * @see inspect.parseTfhd
  4471. * @return {Object[]} the parsed samples
  4472. *
  4473. * @see ISO-BMFF-12/2015, Section 8.8.8
  4474. **/
  4475. var parseSamples = function(truns, baseMediaDecodeTime, tfhd) {
  4476. var currentDts = baseMediaDecodeTime;
  4477. var defaultSampleDuration = tfhd.defaultSampleDuration || 0;
  4478. var defaultSampleSize = tfhd.defaultSampleSize || 0;
  4479. var trackId = tfhd.trackId;
  4480. var allSamples = [];
  4481.  
  4482. truns.forEach(function(trun) {
  4483. // Note: We currently do not parse the sample table as well
  4484. // as the trun. It's possible some sources will require this.
  4485. // moov > trak > mdia > minf > stbl
  4486. var trackRun = inspect.parseTrun(trun);
  4487. var samples = trackRun.samples;
  4488.  
  4489. samples.forEach(function(sample) {
  4490. if (sample.duration === undefined) {
  4491. sample.duration = defaultSampleDuration;
  4492. }
  4493. if (sample.size === undefined) {
  4494. sample.size = defaultSampleSize;
  4495. }
  4496. sample.trackId = trackId;
  4497. sample.dts = currentDts;
  4498. if (sample.compositionTimeOffset === undefined) {
  4499. sample.compositionTimeOffset = 0;
  4500. }
  4501. sample.pts = currentDts + sample.compositionTimeOffset;
  4502.  
  4503. currentDts += sample.duration;
  4504. });
  4505.  
  4506. allSamples = allSamples.concat(samples);
  4507. });
  4508.  
  4509. return allSamples;
  4510. };
  4511.  
  4512. /**
  4513. * Parses out caption nals from an FMP4 segment's video tracks.
  4514. *
  4515. * @param {Uint8Array} segment - The bytes of a single segment
  4516. * @param {Number} videoTrackId - The trackId of a video track in the segment
  4517. * @return {Object.<Number, Object[]>} A mapping of video trackId to
  4518. * a list of seiNals found in that track
  4519. **/
  4520. var parseCaptionNals = function(segment, videoTrackId) {
  4521. // To get the samples
  4522. var trafs = probe.findBox(segment, ['moof', 'traf']);
  4523. // To get SEI NAL units
  4524. var mdats = probe.findBox(segment, ['mdat']);
  4525. var captionNals = {};
  4526. var mdatTrafPairs = [];
  4527.  
  4528. // Pair up each traf with a mdat as moofs and mdats are in pairs
  4529. mdats.forEach(function(mdat, index) {
  4530. var matchingTraf = trafs[index];
  4531. mdatTrafPairs.push({
  4532. mdat: mdat,
  4533. traf: matchingTraf
  4534. });
  4535. });
  4536.  
  4537. mdatTrafPairs.forEach(function(pair) {
  4538. var mdat = pair.mdat;
  4539. var traf = pair.traf;
  4540. var tfhd = probe.findBox(traf, ['tfhd']);
  4541. // Exactly 1 tfhd per traf
  4542. var headerInfo = inspect.parseTfhd(tfhd[0]);
  4543. var trackId = headerInfo.trackId;
  4544. var tfdt = probe.findBox(traf, ['tfdt']);
  4545. // Either 0 or 1 tfdt per traf
  4546. var baseMediaDecodeTime = (tfdt.length > 0) ? inspect.parseTfdt(tfdt[0]).baseMediaDecodeTime : 0;
  4547. var truns = probe.findBox(traf, ['trun']);
  4548. var samples;
  4549. var seiNals;
  4550.  
  4551. // Only parse video data for the chosen video track
  4552. if (videoTrackId === trackId && truns.length > 0) {
  4553. samples = parseSamples(truns, baseMediaDecodeTime, headerInfo);
  4554.  
  4555. seiNals = findSeiNals(mdat, samples, trackId);
  4556.  
  4557. if (!captionNals[trackId]) {
  4558. captionNals[trackId] = [];
  4559. }
  4560.  
  4561. captionNals[trackId] = captionNals[trackId].concat(seiNals);
  4562. }
  4563. });
  4564.  
  4565. return captionNals;
  4566. };
  4567.  
  4568. /**
  4569. * Parses out inband captions from an MP4 container and returns
  4570. * caption objects that can be used by WebVTT and the TextTrack API.
  4571. * @see https://developer.mozilla.org/en-US/docs/Web/API/VTTCue
  4572. * @see https://developer.mozilla.org/en-US/docs/Web/API/TextTrack
  4573. * Assumes that `probe.getVideoTrackIds` and `probe.timescale` have been called first
  4574. *
  4575. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  4576. * @param {Number} trackId - The id of the video track to parse
  4577. * @param {Number} timescale - The timescale for the video track from the init segment
  4578. *
  4579. * @return {?Object[]} parsedCaptions - A list of captions or null if no video tracks
  4580. * @return {Number} parsedCaptions[].startTime - The time to show the caption in seconds
  4581. * @return {Number} parsedCaptions[].endTime - The time to stop showing the caption in seconds
  4582. * @return {String} parsedCaptions[].text - The visible content of the caption
  4583. **/
  4584. var parseEmbeddedCaptions = function(segment, trackId, timescale) {
  4585. var seiNals;
  4586.  
  4587. if (!trackId) {
  4588. return null;
  4589. }
  4590.  
  4591. seiNals = parseCaptionNals(segment, trackId);
  4592.  
  4593. return {
  4594. seiNals: seiNals[trackId],
  4595. timescale: timescale
  4596. };
  4597. };
  4598.  
  4599. /**
  4600. * Converts SEI NALUs into captions that can be used by video.js
  4601. **/
  4602. var CaptionParser = function() {
  4603. var isInitialized = false;
  4604. var captionStream;
  4605.  
  4606. // Stores segments seen before trackId and timescale are set
  4607. var segmentCache;
  4608. // Stores video track ID of the track being parsed
  4609. var trackId;
  4610. // Stores the timescale of the track being parsed
  4611. var timescale;
  4612. // Stores captions parsed so far
  4613. var parsedCaptions;
  4614. // Stores whether we are receiving partial data or not
  4615. var parsingPartial;
  4616.  
  4617. /**
  4618. * A method to indicate whether a CaptionParser has been initalized
  4619. * @returns {Boolean}
  4620. **/
  4621. this.isInitialized = function() {
  4622. return isInitialized;
  4623. };
  4624.  
  4625. /**
  4626. * Initializes the underlying CaptionStream, SEI NAL parsing
  4627. * and management, and caption collection
  4628. **/
  4629. this.init = function(options) {
  4630. captionStream = new CaptionStream();
  4631. isInitialized = true;
  4632. parsingPartial = options ? options.isPartial : false;
  4633.  
  4634. // Collect dispatched captions
  4635. captionStream.on('data', function(event) {
  4636. // Convert to seconds in the source's timescale
  4637. event.startTime = event.startPts / timescale;
  4638. event.endTime = event.endPts / timescale;
  4639.  
  4640. parsedCaptions.captions.push(event);
  4641. parsedCaptions.captionStreams[event.stream] = true;
  4642. });
  4643. };
  4644.  
  4645. /**
  4646. * Determines if a new video track will be selected
  4647. * or if the timescale changed
  4648. * @return {Boolean}
  4649. **/
  4650. this.isNewInit = function(videoTrackIds, timescales) {
  4651. if ((videoTrackIds && videoTrackIds.length === 0) ||
  4652. (timescales && typeof timescales === 'object' &&
  4653. Object.keys(timescales).length === 0)) {
  4654. return false;
  4655. }
  4656.  
  4657. return trackId !== videoTrackIds[0] ||
  4658. timescale !== timescales[trackId];
  4659. };
  4660.  
  4661. /**
  4662. * Parses out SEI captions and interacts with underlying
  4663. * CaptionStream to return dispatched captions
  4664. *
  4665. * @param {Uint8Array} segment - The fmp4 segment containing embedded captions
  4666. * @param {Number[]} videoTrackIds - A list of video tracks found in the init segment
  4667. * @param {Object.<Number, Number>} timescales - The timescales found in the init segment
  4668. * @see parseEmbeddedCaptions
  4669. * @see m2ts/caption-stream.js
  4670. **/
  4671. this.parse = function(segment, videoTrackIds, timescales) {
  4672. var parsedData;
  4673.  
  4674. if (!this.isInitialized()) {
  4675. return null;
  4676.  
  4677. // This is not likely to be a video segment
  4678. } else if (!videoTrackIds || !timescales) {
  4679. return null;
  4680.  
  4681. } else if (this.isNewInit(videoTrackIds, timescales)) {
  4682. // Use the first video track only as there is no
  4683. // mechanism to switch to other video tracks
  4684. trackId = videoTrackIds[0];
  4685. timescale = timescales[trackId];
  4686.  
  4687. // If an init segment has not been seen yet, hold onto segment
  4688. // data until we have one
  4689. } else if (!trackId || !timescale) {
  4690. segmentCache.push(segment);
  4691. return null;
  4692. }
  4693.  
  4694. // Now that a timescale and trackId is set, parse cached segments
  4695. while (segmentCache.length > 0) {
  4696. var cachedSegment = segmentCache.shift();
  4697.  
  4698. this.parse(cachedSegment, videoTrackIds, timescales);
  4699. }
  4700.  
  4701. parsedData = parseEmbeddedCaptions(segment, trackId, timescale);
  4702.  
  4703. if (parsedData === null || !parsedData.seiNals) {
  4704. return null;
  4705. }
  4706.  
  4707. this.pushNals(parsedData.seiNals);
  4708. // Force the parsed captions to be dispatched
  4709. this.flushStream();
  4710.  
  4711. return parsedCaptions;
  4712. };
  4713.  
  4714. /**
  4715. * Pushes SEI NALUs onto CaptionStream
  4716. * @param {Object[]} nals - A list of SEI nals parsed using `parseCaptionNals`
  4717. * Assumes that `parseCaptionNals` has been called first
  4718. * @see m2ts/caption-stream.js
  4719. **/
  4720. this.pushNals = function(nals) {
  4721. if (!this.isInitialized() || !nals || nals.length === 0) {
  4722. return null;
  4723. }
  4724.  
  4725. nals.forEach(function(nal) {
  4726. captionStream.push(nal);
  4727. });
  4728. };
  4729.  
  4730. /**
  4731. * Flushes underlying CaptionStream to dispatch processed, displayable captions
  4732. * @see m2ts/caption-stream.js
  4733. **/
  4734. this.flushStream = function() {
  4735. if (!this.isInitialized()) {
  4736. return null;
  4737. }
  4738.  
  4739. if (!parsingPartial) {
  4740. captionStream.flush();
  4741. } else {
  4742. captionStream.partialFlush();
  4743. }
  4744. };
  4745.  
  4746. /**
  4747. * Reset caption buckets for new data
  4748. **/
  4749. this.clearParsedCaptions = function() {
  4750. parsedCaptions.captions = [];
  4751. parsedCaptions.captionStreams = {};
  4752. };
  4753.  
  4754. /**
  4755. * Resets underlying CaptionStream
  4756. * @see m2ts/caption-stream.js
  4757. **/
  4758. this.resetCaptionStream = function() {
  4759. if (!this.isInitialized()) {
  4760. return null;
  4761. }
  4762.  
  4763. captionStream.reset();
  4764. };
  4765.  
  4766. /**
  4767. * Convenience method to clear all captions flushed from the
  4768. * CaptionStream and still being parsed
  4769. * @see m2ts/caption-stream.js
  4770. **/
  4771. this.clearAllCaptions = function() {
  4772. this.clearParsedCaptions();
  4773. this.resetCaptionStream();
  4774. };
  4775.  
  4776. /**
  4777. * Reset caption parser
  4778. **/
  4779. this.reset = function() {
  4780. segmentCache = [];
  4781. trackId = null;
  4782. timescale = null;
  4783.  
  4784. if (!parsedCaptions) {
  4785. parsedCaptions = {
  4786. captions: [],
  4787. // CC1, CC2, CC3, CC4
  4788. captionStreams: {}
  4789. };
  4790. } else {
  4791. this.clearParsedCaptions();
  4792. }
  4793.  
  4794. this.resetCaptionStream();
  4795. };
  4796.  
  4797. this.reset();
  4798. };
  4799.  
  4800. module.exports = CaptionParser;
  4801.  
  4802. },{"14":14,"26":26,"33":33,"35":35}],23:[function(require,module,exports){
  4803. /**
  4804. * mux.js
  4805. *
  4806. * Copyright (c) Brightcove
  4807. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  4808. */
  4809. // Convert an array of nal units into an array of frames with each frame being
  4810. // composed of the nal units that make up that frame
  4811. // Also keep track of cummulative data about the frame from the nal units such
  4812. // as the frame duration, starting pts, etc.
  4813. var groupNalsIntoFrames = function(nalUnits) {
  4814. var
  4815. i,
  4816. currentNal,
  4817. currentFrame = [],
  4818. frames = [];
  4819.  
  4820. // TODO added for LHLS, make sure this is OK
  4821. frames.byteLength = 0;
  4822. frames.nalCount = 0;
  4823. frames.duration = 0;
  4824.  
  4825. currentFrame.byteLength = 0;
  4826.  
  4827. for (i = 0; i < nalUnits.length; i++) {
  4828. currentNal = nalUnits[i];
  4829.  
  4830. // Split on 'aud'-type nal units
  4831. if (currentNal.nalUnitType === 'access_unit_delimiter_rbsp') {
  4832. // Since the very first nal unit is expected to be an AUD
  4833. // only push to the frames array when currentFrame is not empty
  4834. if (currentFrame.length) {
  4835. currentFrame.duration = currentNal.dts - currentFrame.dts;
  4836. // TODO added for LHLS, make sure this is OK
  4837. frames.byteLength += currentFrame.byteLength;
  4838. frames.nalCount += currentFrame.length;
  4839. frames.duration += currentFrame.duration;
  4840. frames.push(currentFrame);
  4841. }
  4842. currentFrame = [currentNal];
  4843. currentFrame.byteLength = currentNal.data.byteLength;
  4844. currentFrame.pts = currentNal.pts;
  4845. currentFrame.dts = currentNal.dts;
  4846. } else {
  4847. // Specifically flag key frames for ease of use later
  4848. if (currentNal.nalUnitType === 'slice_layer_without_partitioning_rbsp_idr') {
  4849. currentFrame.keyFrame = true;
  4850. }
  4851. currentFrame.duration = currentNal.dts - currentFrame.dts;
  4852. currentFrame.byteLength += currentNal.data.byteLength;
  4853. currentFrame.push(currentNal);
  4854. }
  4855. }
  4856.  
  4857. // For the last frame, use the duration of the previous frame if we
  4858. // have nothing better to go on
  4859. if (frames.length &&
  4860. (!currentFrame.duration ||
  4861. currentFrame.duration <= 0)) {
  4862. currentFrame.duration = frames[frames.length - 1].duration;
  4863. }
  4864.  
  4865. // Push the final frame
  4866. // TODO added for LHLS, make sure this is OK
  4867. frames.byteLength += currentFrame.byteLength;
  4868. frames.nalCount += currentFrame.length;
  4869. frames.duration += currentFrame.duration;
  4870.  
  4871. frames.push(currentFrame);
  4872. return frames;
  4873. };
  4874.  
  4875. // Convert an array of frames into an array of Gop with each Gop being composed
  4876. // of the frames that make up that Gop
  4877. // Also keep track of cummulative data about the Gop from the frames such as the
  4878. // Gop duration, starting pts, etc.
  4879. var groupFramesIntoGops = function(frames) {
  4880. var
  4881. i,
  4882. currentFrame,
  4883. currentGop = [],
  4884. gops = [];
  4885.  
  4886. // We must pre-set some of the values on the Gop since we
  4887. // keep running totals of these values
  4888. currentGop.byteLength = 0;
  4889. currentGop.nalCount = 0;
  4890. currentGop.duration = 0;
  4891. currentGop.pts = frames[0].pts;
  4892. currentGop.dts = frames[0].dts;
  4893.  
  4894. // store some metadata about all the Gops
  4895. gops.byteLength = 0;
  4896. gops.nalCount = 0;
  4897. gops.duration = 0;
  4898. gops.pts = frames[0].pts;
  4899. gops.dts = frames[0].dts;
  4900.  
  4901. for (i = 0; i < frames.length; i++) {
  4902. currentFrame = frames[i];
  4903.  
  4904. if (currentFrame.keyFrame) {
  4905. // Since the very first frame is expected to be an keyframe
  4906. // only push to the gops array when currentGop is not empty
  4907. if (currentGop.length) {
  4908. gops.push(currentGop);
  4909. gops.byteLength += currentGop.byteLength;
  4910. gops.nalCount += currentGop.nalCount;
  4911. gops.duration += currentGop.duration;
  4912. }
  4913.  
  4914. currentGop = [currentFrame];
  4915. currentGop.nalCount = currentFrame.length;
  4916. currentGop.byteLength = currentFrame.byteLength;
  4917. currentGop.pts = currentFrame.pts;
  4918. currentGop.dts = currentFrame.dts;
  4919. currentGop.duration = currentFrame.duration;
  4920. } else {
  4921. currentGop.duration += currentFrame.duration;
  4922. currentGop.nalCount += currentFrame.length;
  4923. currentGop.byteLength += currentFrame.byteLength;
  4924. currentGop.push(currentFrame);
  4925. }
  4926. }
  4927.  
  4928. if (gops.length && currentGop.duration <= 0) {
  4929. currentGop.duration = gops[gops.length - 1].duration;
  4930. }
  4931. gops.byteLength += currentGop.byteLength;
  4932. gops.nalCount += currentGop.nalCount;
  4933. gops.duration += currentGop.duration;
  4934.  
  4935. // push the final Gop
  4936. gops.push(currentGop);
  4937. return gops;
  4938. };
  4939.  
  4940. /*
  4941. * Search for the first keyframe in the GOPs and throw away all frames
  4942. * until that keyframe. Then extend the duration of the pulled keyframe
  4943. * and pull the PTS and DTS of the keyframe so that it covers the time
  4944. * range of the frames that were disposed.
  4945. *
  4946. * @param {Array} gops video GOPs
  4947. * @returns {Array} modified video GOPs
  4948. */
  4949. var extendFirstKeyFrame = function(gops) {
  4950. var currentGop;
  4951.  
  4952. if (!gops[0][0].keyFrame && gops.length > 1) {
  4953. // Remove the first GOP
  4954. currentGop = gops.shift();
  4955.  
  4956. gops.byteLength -= currentGop.byteLength;
  4957. gops.nalCount -= currentGop.nalCount;
  4958.  
  4959. // Extend the first frame of what is now the
  4960. // first gop to cover the time period of the
  4961. // frames we just removed
  4962. gops[0][0].dts = currentGop.dts;
  4963. gops[0][0].pts = currentGop.pts;
  4964. gops[0][0].duration += currentGop.duration;
  4965. }
  4966.  
  4967. return gops;
  4968. };
  4969.  
  4970. /**
  4971. * Default sample object
  4972. * see ISO/IEC 14496-12:2012, section 8.6.4.3
  4973. */
  4974. var createDefaultSample = function() {
  4975. return {
  4976. size: 0,
  4977. flags: {
  4978. isLeading: 0,
  4979. dependsOn: 1,
  4980. isDependedOn: 0,
  4981. hasRedundancy: 0,
  4982. degradationPriority: 0,
  4983. isNonSyncSample: 1
  4984. }
  4985. };
  4986. };
  4987.  
  4988. /*
  4989. * Collates information from a video frame into an object for eventual
  4990. * entry into an MP4 sample table.
  4991. *
  4992. * @param {Object} frame the video frame
  4993. * @param {Number} dataOffset the byte offset to position the sample
  4994. * @return {Object} object containing sample table info for a frame
  4995. */
  4996. var sampleForFrame = function(frame, dataOffset) {
  4997. var sample = createDefaultSample();
  4998.  
  4999. sample.dataOffset = dataOffset;
  5000. sample.compositionTimeOffset = frame.pts - frame.dts;
  5001. sample.duration = frame.duration;
  5002. sample.size = 4 * frame.length; // Space for nal unit size
  5003. sample.size += frame.byteLength;
  5004.  
  5005. if (frame.keyFrame) {
  5006. sample.flags.dependsOn = 2;
  5007. sample.flags.isNonSyncSample = 0;
  5008. }
  5009.  
  5010. return sample;
  5011. };
  5012.  
  5013. // generate the track's sample table from an array of gops
  5014. var generateSampleTable = function(gops, baseDataOffset) {
  5015. var
  5016. h, i,
  5017. sample,
  5018. currentGop,
  5019. currentFrame,
  5020. dataOffset = baseDataOffset || 0,
  5021. samples = [];
  5022.  
  5023. for (h = 0; h < gops.length; h++) {
  5024. currentGop = gops[h];
  5025.  
  5026. for (i = 0; i < currentGop.length; i++) {
  5027. currentFrame = currentGop[i];
  5028.  
  5029. sample = sampleForFrame(currentFrame, dataOffset);
  5030.  
  5031. dataOffset += sample.size;
  5032.  
  5033. samples.push(sample);
  5034. }
  5035. }
  5036. return samples;
  5037. };
  5038.  
  5039. // generate the track's raw mdat data from an array of gops
  5040. var concatenateNalData = function(gops) {
  5041. var
  5042. h, i, j,
  5043. currentGop,
  5044. currentFrame,
  5045. currentNal,
  5046. dataOffset = 0,
  5047. nalsByteLength = gops.byteLength,
  5048. numberOfNals = gops.nalCount,
  5049. totalByteLength = nalsByteLength + 4 * numberOfNals,
  5050. data = new Uint8Array(totalByteLength),
  5051. view = new DataView(data.buffer);
  5052.  
  5053. // For each Gop..
  5054. for (h = 0; h < gops.length; h++) {
  5055. currentGop = gops[h];
  5056.  
  5057. // For each Frame..
  5058. for (i = 0; i < currentGop.length; i++) {
  5059. currentFrame = currentGop[i];
  5060.  
  5061. // For each NAL..
  5062. for (j = 0; j < currentFrame.length; j++) {
  5063. currentNal = currentFrame[j];
  5064.  
  5065. view.setUint32(dataOffset, currentNal.data.byteLength);
  5066. dataOffset += 4;
  5067. data.set(currentNal.data, dataOffset);
  5068. dataOffset += currentNal.data.byteLength;
  5069. }
  5070. }
  5071. }
  5072. return data;
  5073. };
  5074.  
  5075. // generate the track's sample table from a frame
  5076. var generateSampleTableForFrame = function(frame, baseDataOffset) {
  5077. var
  5078. sample,
  5079. dataOffset = baseDataOffset || 0,
  5080. samples = [];
  5081.  
  5082. sample = sampleForFrame(frame, dataOffset);
  5083. samples.push(sample);
  5084.  
  5085. return samples;
  5086. };
  5087.  
  5088. // generate the track's raw mdat data from a frame
  5089. var concatenateNalDataForFrame = function(frame) {
  5090. var
  5091. i,
  5092. currentNal,
  5093. dataOffset = 0,
  5094. nalsByteLength = frame.byteLength,
  5095. numberOfNals = frame.length,
  5096. totalByteLength = nalsByteLength + 4 * numberOfNals,
  5097. data = new Uint8Array(totalByteLength),
  5098. view = new DataView(data.buffer);
  5099.  
  5100. // For each NAL..
  5101. for (i = 0; i < frame.length; i++) {
  5102. currentNal = frame[i];
  5103.  
  5104. view.setUint32(dataOffset, currentNal.data.byteLength);
  5105. dataOffset += 4;
  5106. data.set(currentNal.data, dataOffset);
  5107. dataOffset += currentNal.data.byteLength;
  5108. }
  5109.  
  5110. return data;
  5111. };
  5112.  
  5113. module.exports = {
  5114. groupNalsIntoFrames: groupNalsIntoFrames,
  5115. groupFramesIntoGops: groupFramesIntoGops,
  5116. extendFirstKeyFrame: extendFirstKeyFrame,
  5117. generateSampleTable: generateSampleTable,
  5118. concatenateNalData: concatenateNalData,
  5119. generateSampleTableForFrame: generateSampleTableForFrame,
  5120. concatenateNalDataForFrame: concatenateNalDataForFrame
  5121. };
  5122.  
  5123. },{}],24:[function(require,module,exports){
  5124. /**
  5125. * mux.js
  5126. *
  5127. * Copyright (c) Brightcove
  5128. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5129. */
  5130. module.exports = {
  5131. generator: require(25),
  5132. probe: require(26),
  5133. Transmuxer: require(28).Transmuxer,
  5134. AudioSegmentStream: require(28).AudioSegmentStream,
  5135. VideoSegmentStream: require(28).VideoSegmentStream,
  5136. CaptionParser: require(22)
  5137. };
  5138.  
  5139. },{"22":22,"25":25,"26":26,"28":28}],25:[function(require,module,exports){
  5140. /**
  5141. * mux.js
  5142. *
  5143. * Copyright (c) Brightcove
  5144. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5145. *
  5146. * Functions that generate fragmented MP4s suitable for use with Media
  5147. * Source Extensions.
  5148. */
  5149. 'use strict';
  5150.  
  5151. var UINT32_MAX = Math.pow(2, 32) - 1;
  5152.  
  5153. var box, dinf, esds, ftyp, mdat, mfhd, minf, moof, moov, mvex, mvhd,
  5154. trak, tkhd, mdia, mdhd, hdlr, sdtp, stbl, stsd, traf, trex,
  5155. trun, types, MAJOR_BRAND, MINOR_VERSION, AVC1_BRAND, VIDEO_HDLR,
  5156. AUDIO_HDLR, HDLR_TYPES, VMHD, SMHD, DREF, STCO, STSC, STSZ, STTS;
  5157.  
  5158. // pre-calculate constants
  5159. (function() {
  5160. var i;
  5161. types = {
  5162. avc1: [], // codingname
  5163. avcC: [],
  5164. btrt: [],
  5165. dinf: [],
  5166. dref: [],
  5167. esds: [],
  5168. ftyp: [],
  5169. hdlr: [],
  5170. mdat: [],
  5171. mdhd: [],
  5172. mdia: [],
  5173. mfhd: [],
  5174. minf: [],
  5175. moof: [],
  5176. moov: [],
  5177. mp4a: [], // codingname
  5178. mvex: [],
  5179. mvhd: [],
  5180. sdtp: [],
  5181. smhd: [],
  5182. stbl: [],
  5183. stco: [],
  5184. stsc: [],
  5185. stsd: [],
  5186. stsz: [],
  5187. stts: [],
  5188. styp: [],
  5189. tfdt: [],
  5190. tfhd: [],
  5191. traf: [],
  5192. trak: [],
  5193. trun: [],
  5194. trex: [],
  5195. tkhd: [],
  5196. vmhd: []
  5197. };
  5198.  
  5199. // In environments where Uint8Array is undefined (e.g., IE8), skip set up so that we
  5200. // don't throw an error
  5201. if (typeof Uint8Array === 'undefined') {
  5202. return;
  5203. }
  5204.  
  5205. for (i in types) {
  5206. if (types.hasOwnProperty(i)) {
  5207. types[i] = [
  5208. i.charCodeAt(0),
  5209. i.charCodeAt(1),
  5210. i.charCodeAt(2),
  5211. i.charCodeAt(3)
  5212. ];
  5213. }
  5214. }
  5215.  
  5216. MAJOR_BRAND = new Uint8Array([
  5217. 'i'.charCodeAt(0),
  5218. 's'.charCodeAt(0),
  5219. 'o'.charCodeAt(0),
  5220. 'm'.charCodeAt(0)
  5221. ]);
  5222. AVC1_BRAND = new Uint8Array([
  5223. 'a'.charCodeAt(0),
  5224. 'v'.charCodeAt(0),
  5225. 'c'.charCodeAt(0),
  5226. '1'.charCodeAt(0)
  5227. ]);
  5228. MINOR_VERSION = new Uint8Array([0, 0, 0, 1]);
  5229. VIDEO_HDLR = new Uint8Array([
  5230. 0x00, // version 0
  5231. 0x00, 0x00, 0x00, // flags
  5232. 0x00, 0x00, 0x00, 0x00, // pre_defined
  5233. 0x76, 0x69, 0x64, 0x65, // handler_type: 'vide'
  5234. 0x00, 0x00, 0x00, 0x00, // reserved
  5235. 0x00, 0x00, 0x00, 0x00, // reserved
  5236. 0x00, 0x00, 0x00, 0x00, // reserved
  5237. 0x56, 0x69, 0x64, 0x65,
  5238. 0x6f, 0x48, 0x61, 0x6e,
  5239. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'VideoHandler'
  5240. ]);
  5241. AUDIO_HDLR = new Uint8Array([
  5242. 0x00, // version 0
  5243. 0x00, 0x00, 0x00, // flags
  5244. 0x00, 0x00, 0x00, 0x00, // pre_defined
  5245. 0x73, 0x6f, 0x75, 0x6e, // handler_type: 'soun'
  5246. 0x00, 0x00, 0x00, 0x00, // reserved
  5247. 0x00, 0x00, 0x00, 0x00, // reserved
  5248. 0x00, 0x00, 0x00, 0x00, // reserved
  5249. 0x53, 0x6f, 0x75, 0x6e,
  5250. 0x64, 0x48, 0x61, 0x6e,
  5251. 0x64, 0x6c, 0x65, 0x72, 0x00 // name: 'SoundHandler'
  5252. ]);
  5253. HDLR_TYPES = {
  5254. video: VIDEO_HDLR,
  5255. audio: AUDIO_HDLR
  5256. };
  5257. DREF = new Uint8Array([
  5258. 0x00, // version 0
  5259. 0x00, 0x00, 0x00, // flags
  5260. 0x00, 0x00, 0x00, 0x01, // entry_count
  5261. 0x00, 0x00, 0x00, 0x0c, // entry_size
  5262. 0x75, 0x72, 0x6c, 0x20, // 'url' type
  5263. 0x00, // version 0
  5264. 0x00, 0x00, 0x01 // entry_flags
  5265. ]);
  5266. SMHD = new Uint8Array([
  5267. 0x00, // version
  5268. 0x00, 0x00, 0x00, // flags
  5269. 0x00, 0x00, // balance, 0 means centered
  5270. 0x00, 0x00 // reserved
  5271. ]);
  5272. STCO = new Uint8Array([
  5273. 0x00, // version
  5274. 0x00, 0x00, 0x00, // flags
  5275. 0x00, 0x00, 0x00, 0x00 // entry_count
  5276. ]);
  5277. STSC = STCO;
  5278. STSZ = new Uint8Array([
  5279. 0x00, // version
  5280. 0x00, 0x00, 0x00, // flags
  5281. 0x00, 0x00, 0x00, 0x00, // sample_size
  5282. 0x00, 0x00, 0x00, 0x00 // sample_count
  5283. ]);
  5284. STTS = STCO;
  5285. VMHD = new Uint8Array([
  5286. 0x00, // version
  5287. 0x00, 0x00, 0x01, // flags
  5288. 0x00, 0x00, // graphicsmode
  5289. 0x00, 0x00,
  5290. 0x00, 0x00,
  5291. 0x00, 0x00 // opcolor
  5292. ]);
  5293. }());
  5294.  
  5295. box = function(type) {
  5296. var
  5297. payload = [],
  5298. size = 0,
  5299. i,
  5300. result,
  5301. view;
  5302.  
  5303. for (i = 1; i < arguments.length; i++) {
  5304. payload.push(arguments[i]);
  5305. }
  5306.  
  5307. i = payload.length;
  5308.  
  5309. // calculate the total size we need to allocate
  5310. while (i--) {
  5311. size += payload[i].byteLength;
  5312. }
  5313. result = new Uint8Array(size + 8);
  5314. view = new DataView(result.buffer, result.byteOffset, result.byteLength);
  5315. view.setUint32(0, result.byteLength);
  5316. result.set(type, 4);
  5317.  
  5318. // copy the payload into the result
  5319. for (i = 0, size = 8; i < payload.length; i++) {
  5320. result.set(payload[i], size);
  5321. size += payload[i].byteLength;
  5322. }
  5323. return result;
  5324. };
  5325.  
  5326. dinf = function() {
  5327. return box(types.dinf, box(types.dref, DREF));
  5328. };
  5329.  
  5330. esds = function(track) {
  5331. return box(types.esds, new Uint8Array([
  5332. 0x00, // version
  5333. 0x00, 0x00, 0x00, // flags
  5334.  
  5335. // ES_Descriptor
  5336. 0x03, // tag, ES_DescrTag
  5337. 0x19, // length
  5338. 0x00, 0x00, // ES_ID
  5339. 0x00, // streamDependenceFlag, URL_flag, reserved, streamPriority
  5340.  
  5341. // DecoderConfigDescriptor
  5342. 0x04, // tag, DecoderConfigDescrTag
  5343. 0x11, // length
  5344. 0x40, // object type
  5345. 0x15, // streamType
  5346. 0x00, 0x06, 0x00, // bufferSizeDB
  5347. 0x00, 0x00, 0xda, 0xc0, // maxBitrate
  5348. 0x00, 0x00, 0xda, 0xc0, // avgBitrate
  5349.  
  5350. // DecoderSpecificInfo
  5351. 0x05, // tag, DecoderSpecificInfoTag
  5352. 0x02, // length
  5353. // ISO/IEC 14496-3, AudioSpecificConfig
  5354. // for samplingFrequencyIndex see ISO/IEC 13818-7:2006, 8.1.3.2.2, Table 35
  5355. (track.audioobjecttype << 3) | (track.samplingfrequencyindex >>> 1),
  5356. (track.samplingfrequencyindex << 7) | (track.channelcount << 3),
  5357. 0x06, 0x01, 0x02 // GASpecificConfig
  5358. ]));
  5359. };
  5360.  
  5361. ftyp = function() {
  5362. return box(types.ftyp, MAJOR_BRAND, MINOR_VERSION, MAJOR_BRAND, AVC1_BRAND);
  5363. };
  5364.  
  5365. hdlr = function(type) {
  5366. return box(types.hdlr, HDLR_TYPES[type]);
  5367. };
  5368. mdat = function(data) {
  5369. return box(types.mdat, data);
  5370. };
  5371. mdhd = function(track) {
  5372. var result = new Uint8Array([
  5373. 0x00, // version 0
  5374. 0x00, 0x00, 0x00, // flags
  5375. 0x00, 0x00, 0x00, 0x02, // creation_time
  5376. 0x00, 0x00, 0x00, 0x03, // modification_time
  5377. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  5378.  
  5379. (track.duration >>> 24) & 0xFF,
  5380. (track.duration >>> 16) & 0xFF,
  5381. (track.duration >>> 8) & 0xFF,
  5382. track.duration & 0xFF, // duration
  5383. 0x55, 0xc4, // 'und' language (undetermined)
  5384. 0x00, 0x00
  5385. ]);
  5386.  
  5387. // Use the sample rate from the track metadata, when it is
  5388. // defined. The sample rate can be parsed out of an ADTS header, for
  5389. // instance.
  5390. if (track.samplerate) {
  5391. result[12] = (track.samplerate >>> 24) & 0xFF;
  5392. result[13] = (track.samplerate >>> 16) & 0xFF;
  5393. result[14] = (track.samplerate >>> 8) & 0xFF;
  5394. result[15] = (track.samplerate) & 0xFF;
  5395. }
  5396.  
  5397. return box(types.mdhd, result);
  5398. };
  5399. mdia = function(track) {
  5400. return box(types.mdia, mdhd(track), hdlr(track.type), minf(track));
  5401. };
  5402. mfhd = function(sequenceNumber) {
  5403. return box(types.mfhd, new Uint8Array([
  5404. 0x00,
  5405. 0x00, 0x00, 0x00, // flags
  5406. (sequenceNumber & 0xFF000000) >> 24,
  5407. (sequenceNumber & 0xFF0000) >> 16,
  5408. (sequenceNumber & 0xFF00) >> 8,
  5409. sequenceNumber & 0xFF // sequence_number
  5410. ]));
  5411. };
  5412. minf = function(track) {
  5413. return box(types.minf,
  5414. track.type === 'video' ? box(types.vmhd, VMHD) : box(types.smhd, SMHD),
  5415. dinf(),
  5416. stbl(track));
  5417. };
  5418. moof = function(sequenceNumber, tracks) {
  5419. var
  5420. trackFragments = [],
  5421. i = tracks.length;
  5422. // build traf boxes for each track fragment
  5423. while (i--) {
  5424. trackFragments[i] = traf(tracks[i]);
  5425. }
  5426. return box.apply(null, [
  5427. types.moof,
  5428. mfhd(sequenceNumber)
  5429. ].concat(trackFragments));
  5430. };
  5431. /**
  5432. * Returns a movie box.
  5433. * @param tracks {array} the tracks associated with this movie
  5434. * @see ISO/IEC 14496-12:2012(E), section 8.2.1
  5435. */
  5436. moov = function(tracks) {
  5437. var
  5438. i = tracks.length,
  5439. boxes = [];
  5440.  
  5441. while (i--) {
  5442. boxes[i] = trak(tracks[i]);
  5443. }
  5444.  
  5445. return box.apply(null, [types.moov, mvhd(0xffffffff)].concat(boxes).concat(mvex(tracks)));
  5446. };
  5447. mvex = function(tracks) {
  5448. var
  5449. i = tracks.length,
  5450. boxes = [];
  5451.  
  5452. while (i--) {
  5453. boxes[i] = trex(tracks[i]);
  5454. }
  5455. return box.apply(null, [types.mvex].concat(boxes));
  5456. };
  5457. mvhd = function(duration) {
  5458. var
  5459. bytes = new Uint8Array([
  5460. 0x00, // version 0
  5461. 0x00, 0x00, 0x00, // flags
  5462. 0x00, 0x00, 0x00, 0x01, // creation_time
  5463. 0x00, 0x00, 0x00, 0x02, // modification_time
  5464. 0x00, 0x01, 0x5f, 0x90, // timescale, 90,000 "ticks" per second
  5465. (duration & 0xFF000000) >> 24,
  5466. (duration & 0xFF0000) >> 16,
  5467. (duration & 0xFF00) >> 8,
  5468. duration & 0xFF, // duration
  5469. 0x00, 0x01, 0x00, 0x00, // 1.0 rate
  5470. 0x01, 0x00, // 1.0 volume
  5471. 0x00, 0x00, // reserved
  5472. 0x00, 0x00, 0x00, 0x00, // reserved
  5473. 0x00, 0x00, 0x00, 0x00, // reserved
  5474. 0x00, 0x01, 0x00, 0x00,
  5475. 0x00, 0x00, 0x00, 0x00,
  5476. 0x00, 0x00, 0x00, 0x00,
  5477. 0x00, 0x00, 0x00, 0x00,
  5478. 0x00, 0x01, 0x00, 0x00,
  5479. 0x00, 0x00, 0x00, 0x00,
  5480. 0x00, 0x00, 0x00, 0x00,
  5481. 0x00, 0x00, 0x00, 0x00,
  5482. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  5483. 0x00, 0x00, 0x00, 0x00,
  5484. 0x00, 0x00, 0x00, 0x00,
  5485. 0x00, 0x00, 0x00, 0x00,
  5486. 0x00, 0x00, 0x00, 0x00,
  5487. 0x00, 0x00, 0x00, 0x00,
  5488. 0x00, 0x00, 0x00, 0x00, // pre_defined
  5489. 0xff, 0xff, 0xff, 0xff // next_track_ID
  5490. ]);
  5491. return box(types.mvhd, bytes);
  5492. };
  5493.  
  5494. sdtp = function(track) {
  5495. var
  5496. samples = track.samples || [],
  5497. bytes = new Uint8Array(4 + samples.length),
  5498. flags,
  5499. i;
  5500.  
  5501. // leave the full box header (4 bytes) all zero
  5502.  
  5503. // write the sample table
  5504. for (i = 0; i < samples.length; i++) {
  5505. flags = samples[i].flags;
  5506.  
  5507. bytes[i + 4] = (flags.dependsOn << 4) |
  5508. (flags.isDependedOn << 2) |
  5509. (flags.hasRedundancy);
  5510. }
  5511.  
  5512. return box(types.sdtp,
  5513. bytes);
  5514. };
  5515.  
  5516. stbl = function(track) {
  5517. return box(types.stbl,
  5518. stsd(track),
  5519. box(types.stts, STTS),
  5520. box(types.stsc, STSC),
  5521. box(types.stsz, STSZ),
  5522. box(types.stco, STCO));
  5523. };
  5524.  
  5525. (function() {
  5526. var videoSample, audioSample;
  5527.  
  5528. stsd = function(track) {
  5529.  
  5530. return box(types.stsd, new Uint8Array([
  5531. 0x00, // version 0
  5532. 0x00, 0x00, 0x00, // flags
  5533. 0x00, 0x00, 0x00, 0x01
  5534. ]), track.type === 'video' ? videoSample(track) : audioSample(track));
  5535. };
  5536.  
  5537. videoSample = function(track) {
  5538. var
  5539. sps = track.sps || [],
  5540. pps = track.pps || [],
  5541. sequenceParameterSets = [],
  5542. pictureParameterSets = [],
  5543. i;
  5544.  
  5545. // assemble the SPSs
  5546. for (i = 0; i < sps.length; i++) {
  5547. sequenceParameterSets.push((sps[i].byteLength & 0xFF00) >>> 8);
  5548. sequenceParameterSets.push((sps[i].byteLength & 0xFF)); // sequenceParameterSetLength
  5549. sequenceParameterSets = sequenceParameterSets.concat(Array.prototype.slice.call(sps[i])); // SPS
  5550. }
  5551.  
  5552. // assemble the PPSs
  5553. for (i = 0; i < pps.length; i++) {
  5554. pictureParameterSets.push((pps[i].byteLength & 0xFF00) >>> 8);
  5555. pictureParameterSets.push((pps[i].byteLength & 0xFF));
  5556. pictureParameterSets = pictureParameterSets.concat(Array.prototype.slice.call(pps[i]));
  5557. }
  5558.  
  5559. return box(types.avc1, new Uint8Array([
  5560. 0x00, 0x00, 0x00,
  5561. 0x00, 0x00, 0x00, // reserved
  5562. 0x00, 0x01, // data_reference_index
  5563. 0x00, 0x00, // pre_defined
  5564. 0x00, 0x00, // reserved
  5565. 0x00, 0x00, 0x00, 0x00,
  5566. 0x00, 0x00, 0x00, 0x00,
  5567. 0x00, 0x00, 0x00, 0x00, // pre_defined
  5568. (track.width & 0xff00) >> 8,
  5569. track.width & 0xff, // width
  5570. (track.height & 0xff00) >> 8,
  5571. track.height & 0xff, // height
  5572. 0x00, 0x48, 0x00, 0x00, // horizresolution
  5573. 0x00, 0x48, 0x00, 0x00, // vertresolution
  5574. 0x00, 0x00, 0x00, 0x00, // reserved
  5575. 0x00, 0x01, // frame_count
  5576. 0x13,
  5577. 0x76, 0x69, 0x64, 0x65,
  5578. 0x6f, 0x6a, 0x73, 0x2d,
  5579. 0x63, 0x6f, 0x6e, 0x74,
  5580. 0x72, 0x69, 0x62, 0x2d,
  5581. 0x68, 0x6c, 0x73, 0x00,
  5582. 0x00, 0x00, 0x00, 0x00,
  5583. 0x00, 0x00, 0x00, 0x00,
  5584. 0x00, 0x00, 0x00, // compressorname
  5585. 0x00, 0x18, // depth = 24
  5586. 0x11, 0x11 // pre_defined = -1
  5587. ]), box(types.avcC, new Uint8Array([
  5588. 0x01, // configurationVersion
  5589. track.profileIdc, // AVCProfileIndication
  5590. track.profileCompatibility, // profile_compatibility
  5591. track.levelIdc, // AVCLevelIndication
  5592. 0xff // lengthSizeMinusOne, hard-coded to 4 bytes
  5593. ].concat([
  5594. sps.length // numOfSequenceParameterSets
  5595. ]).concat(sequenceParameterSets).concat([
  5596. pps.length // numOfPictureParameterSets
  5597. ]).concat(pictureParameterSets))), // "PPS"
  5598. box(types.btrt, new Uint8Array([
  5599. 0x00, 0x1c, 0x9c, 0x80, // bufferSizeDB
  5600. 0x00, 0x2d, 0xc6, 0xc0, // maxBitrate
  5601. 0x00, 0x2d, 0xc6, 0xc0
  5602. ])) // avgBitrate
  5603. );
  5604. };
  5605.  
  5606. audioSample = function(track) {
  5607. return box(types.mp4a, new Uint8Array([
  5608.  
  5609. // SampleEntry, ISO/IEC 14496-12
  5610. 0x00, 0x00, 0x00,
  5611. 0x00, 0x00, 0x00, // reserved
  5612. 0x00, 0x01, // data_reference_index
  5613.  
  5614. // AudioSampleEntry, ISO/IEC 14496-12
  5615. 0x00, 0x00, 0x00, 0x00, // reserved
  5616. 0x00, 0x00, 0x00, 0x00, // reserved
  5617. (track.channelcount & 0xff00) >> 8,
  5618. (track.channelcount & 0xff), // channelcount
  5619.  
  5620. (track.samplesize & 0xff00) >> 8,
  5621. (track.samplesize & 0xff), // samplesize
  5622. 0x00, 0x00, // pre_defined
  5623. 0x00, 0x00, // reserved
  5624.  
  5625. (track.samplerate & 0xff00) >> 8,
  5626. (track.samplerate & 0xff),
  5627. 0x00, 0x00 // samplerate, 16.16
  5628.  
  5629. // MP4AudioSampleEntry, ISO/IEC 14496-14
  5630. ]), esds(track));
  5631. };
  5632. }());
  5633.  
  5634. tkhd = function(track) {
  5635. var result = new Uint8Array([
  5636. 0x00, // version 0
  5637. 0x00, 0x00, 0x07, // flags
  5638. 0x00, 0x00, 0x00, 0x00, // creation_time
  5639. 0x00, 0x00, 0x00, 0x00, // modification_time
  5640. (track.id & 0xFF000000) >> 24,
  5641. (track.id & 0xFF0000) >> 16,
  5642. (track.id & 0xFF00) >> 8,
  5643. track.id & 0xFF, // track_ID
  5644. 0x00, 0x00, 0x00, 0x00, // reserved
  5645. (track.duration & 0xFF000000) >> 24,
  5646. (track.duration & 0xFF0000) >> 16,
  5647. (track.duration & 0xFF00) >> 8,
  5648. track.duration & 0xFF, // duration
  5649. 0x00, 0x00, 0x00, 0x00,
  5650. 0x00, 0x00, 0x00, 0x00, // reserved
  5651. 0x00, 0x00, // layer
  5652. 0x00, 0x00, // alternate_group
  5653. 0x01, 0x00, // non-audio track volume
  5654. 0x00, 0x00, // reserved
  5655. 0x00, 0x01, 0x00, 0x00,
  5656. 0x00, 0x00, 0x00, 0x00,
  5657. 0x00, 0x00, 0x00, 0x00,
  5658. 0x00, 0x00, 0x00, 0x00,
  5659. 0x00, 0x01, 0x00, 0x00,
  5660. 0x00, 0x00, 0x00, 0x00,
  5661. 0x00, 0x00, 0x00, 0x00,
  5662. 0x00, 0x00, 0x00, 0x00,
  5663. 0x40, 0x00, 0x00, 0x00, // transformation: unity matrix
  5664. (track.width & 0xFF00) >> 8,
  5665. track.width & 0xFF,
  5666. 0x00, 0x00, // width
  5667. (track.height & 0xFF00) >> 8,
  5668. track.height & 0xFF,
  5669. 0x00, 0x00 // height
  5670. ]);
  5671.  
  5672. return box(types.tkhd, result);
  5673. };
  5674.  
  5675. /**
  5676. * Generate a track fragment (traf) box. A traf box collects metadata
  5677. * about tracks in a movie fragment (moof) box.
  5678. */
  5679. traf = function(track) {
  5680. var trackFragmentHeader, trackFragmentDecodeTime, trackFragmentRun,
  5681. sampleDependencyTable, dataOffset,
  5682. upperWordBaseMediaDecodeTime, lowerWordBaseMediaDecodeTime;
  5683.  
  5684. trackFragmentHeader = box(types.tfhd, new Uint8Array([
  5685. 0x00, // version 0
  5686. 0x00, 0x00, 0x3a, // flags
  5687. (track.id & 0xFF000000) >> 24,
  5688. (track.id & 0xFF0000) >> 16,
  5689. (track.id & 0xFF00) >> 8,
  5690. (track.id & 0xFF), // track_ID
  5691. 0x00, 0x00, 0x00, 0x01, // sample_description_index
  5692. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  5693. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  5694. 0x00, 0x00, 0x00, 0x00 // default_sample_flags
  5695. ]));
  5696.  
  5697. upperWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime / (UINT32_MAX + 1));
  5698. lowerWordBaseMediaDecodeTime = Math.floor(track.baseMediaDecodeTime % (UINT32_MAX + 1));
  5699.  
  5700. trackFragmentDecodeTime = box(types.tfdt, new Uint8Array([
  5701. 0x01, // version 1
  5702. 0x00, 0x00, 0x00, // flags
  5703. // baseMediaDecodeTime
  5704. (upperWordBaseMediaDecodeTime >>> 24) & 0xFF,
  5705. (upperWordBaseMediaDecodeTime >>> 16) & 0xFF,
  5706. (upperWordBaseMediaDecodeTime >>> 8) & 0xFF,
  5707. upperWordBaseMediaDecodeTime & 0xFF,
  5708. (lowerWordBaseMediaDecodeTime >>> 24) & 0xFF,
  5709. (lowerWordBaseMediaDecodeTime >>> 16) & 0xFF,
  5710. (lowerWordBaseMediaDecodeTime >>> 8) & 0xFF,
  5711. lowerWordBaseMediaDecodeTime & 0xFF
  5712. ]));
  5713.  
  5714. // the data offset specifies the number of bytes from the start of
  5715. // the containing moof to the first payload byte of the associated
  5716. // mdat
  5717. dataOffset = (32 + // tfhd
  5718. 20 + // tfdt
  5719. 8 + // traf header
  5720. 16 + // mfhd
  5721. 8 + // moof header
  5722. 8); // mdat header
  5723.  
  5724. // audio tracks require less metadata
  5725. if (track.type === 'audio') {
  5726. trackFragmentRun = trun(track, dataOffset);
  5727. return box(types.traf,
  5728. trackFragmentHeader,
  5729. trackFragmentDecodeTime,
  5730. trackFragmentRun);
  5731. }
  5732.  
  5733. // video tracks should contain an independent and disposable samples
  5734. // box (sdtp)
  5735. // generate one and adjust offsets to match
  5736. sampleDependencyTable = sdtp(track);
  5737. trackFragmentRun = trun(track,
  5738. sampleDependencyTable.length + dataOffset);
  5739. return box(types.traf,
  5740. trackFragmentHeader,
  5741. trackFragmentDecodeTime,
  5742. trackFragmentRun,
  5743. sampleDependencyTable);
  5744. };
  5745.  
  5746. /**
  5747. * Generate a track box.
  5748. * @param track {object} a track definition
  5749. * @return {Uint8Array} the track box
  5750. */
  5751. trak = function(track) {
  5752. track.duration = track.duration || 0xffffffff;
  5753. return box(types.trak,
  5754. tkhd(track),
  5755. mdia(track));
  5756. };
  5757.  
  5758. trex = function(track) {
  5759. var result = new Uint8Array([
  5760. 0x00, // version 0
  5761. 0x00, 0x00, 0x00, // flags
  5762. (track.id & 0xFF000000) >> 24,
  5763. (track.id & 0xFF0000) >> 16,
  5764. (track.id & 0xFF00) >> 8,
  5765. (track.id & 0xFF), // track_ID
  5766. 0x00, 0x00, 0x00, 0x01, // default_sample_description_index
  5767. 0x00, 0x00, 0x00, 0x00, // default_sample_duration
  5768. 0x00, 0x00, 0x00, 0x00, // default_sample_size
  5769. 0x00, 0x01, 0x00, 0x01 // default_sample_flags
  5770. ]);
  5771. // the last two bytes of default_sample_flags is the sample
  5772. // degradation priority, a hint about the importance of this sample
  5773. // relative to others. Lower the degradation priority for all sample
  5774. // types other than video.
  5775. if (track.type !== 'video') {
  5776. result[result.length - 1] = 0x00;
  5777. }
  5778.  
  5779. return box(types.trex, result);
  5780. };
  5781.  
  5782. (function() {
  5783. var audioTrun, videoTrun, trunHeader;
  5784.  
  5785. // This method assumes all samples are uniform. That is, if a
  5786. // duration is present for the first sample, it will be present for
  5787. // all subsequent samples.
  5788. // see ISO/IEC 14496-12:2012, Section 8.8.8.1
  5789. trunHeader = function(samples, offset) {
  5790. var durationPresent = 0, sizePresent = 0,
  5791. flagsPresent = 0, compositionTimeOffset = 0;
  5792.  
  5793. // trun flag constants
  5794. if (samples.length) {
  5795. if (samples[0].duration !== undefined) {
  5796. durationPresent = 0x1;
  5797. }
  5798. if (samples[0].size !== undefined) {
  5799. sizePresent = 0x2;
  5800. }
  5801. if (samples[0].flags !== undefined) {
  5802. flagsPresent = 0x4;
  5803. }
  5804. if (samples[0].compositionTimeOffset !== undefined) {
  5805. compositionTimeOffset = 0x8;
  5806. }
  5807. }
  5808.  
  5809. return [
  5810. 0x00, // version 0
  5811. 0x00,
  5812. durationPresent | sizePresent | flagsPresent | compositionTimeOffset,
  5813. 0x01, // flags
  5814. (samples.length & 0xFF000000) >>> 24,
  5815. (samples.length & 0xFF0000) >>> 16,
  5816. (samples.length & 0xFF00) >>> 8,
  5817. samples.length & 0xFF, // sample_count
  5818. (offset & 0xFF000000) >>> 24,
  5819. (offset & 0xFF0000) >>> 16,
  5820. (offset & 0xFF00) >>> 8,
  5821. offset & 0xFF // data_offset
  5822. ];
  5823. };
  5824.  
  5825. videoTrun = function(track, offset) {
  5826. var bytes, samples, sample, i;
  5827.  
  5828. samples = track.samples || [];
  5829. offset += 8 + 12 + (16 * samples.length);
  5830.  
  5831. bytes = trunHeader(samples, offset);
  5832.  
  5833. for (i = 0; i < samples.length; i++) {
  5834. sample = samples[i];
  5835. bytes = bytes.concat([
  5836. (sample.duration & 0xFF000000) >>> 24,
  5837. (sample.duration & 0xFF0000) >>> 16,
  5838. (sample.duration & 0xFF00) >>> 8,
  5839. sample.duration & 0xFF, // sample_duration
  5840. (sample.size & 0xFF000000) >>> 24,
  5841. (sample.size & 0xFF0000) >>> 16,
  5842. (sample.size & 0xFF00) >>> 8,
  5843. sample.size & 0xFF, // sample_size
  5844. (sample.flags.isLeading << 2) | sample.flags.dependsOn,
  5845. (sample.flags.isDependedOn << 6) |
  5846. (sample.flags.hasRedundancy << 4) |
  5847. (sample.flags.paddingValue << 1) |
  5848. sample.flags.isNonSyncSample,
  5849. sample.flags.degradationPriority & 0xF0 << 8,
  5850. sample.flags.degradationPriority & 0x0F, // sample_flags
  5851. (sample.compositionTimeOffset & 0xFF000000) >>> 24,
  5852. (sample.compositionTimeOffset & 0xFF0000) >>> 16,
  5853. (sample.compositionTimeOffset & 0xFF00) >>> 8,
  5854. sample.compositionTimeOffset & 0xFF // sample_composition_time_offset
  5855. ]);
  5856. }
  5857. return box(types.trun, new Uint8Array(bytes));
  5858. };
  5859.  
  5860. audioTrun = function(track, offset) {
  5861. var bytes, samples, sample, i;
  5862.  
  5863. samples = track.samples || [];
  5864. offset += 8 + 12 + (8 * samples.length);
  5865.  
  5866. bytes = trunHeader(samples, offset);
  5867.  
  5868. for (i = 0; i < samples.length; i++) {
  5869. sample = samples[i];
  5870. bytes = bytes.concat([
  5871. (sample.duration & 0xFF000000) >>> 24,
  5872. (sample.duration & 0xFF0000) >>> 16,
  5873. (sample.duration & 0xFF00) >>> 8,
  5874. sample.duration & 0xFF, // sample_duration
  5875. (sample.size & 0xFF000000) >>> 24,
  5876. (sample.size & 0xFF0000) >>> 16,
  5877. (sample.size & 0xFF00) >>> 8,
  5878. sample.size & 0xFF]); // sample_size
  5879. }
  5880.  
  5881. return box(types.trun, new Uint8Array(bytes));
  5882. };
  5883.  
  5884. trun = function(track, offset) {
  5885. if (track.type === 'audio') {
  5886. return audioTrun(track, offset);
  5887. }
  5888.  
  5889. return videoTrun(track, offset);
  5890. };
  5891. }());
  5892.  
  5893. module.exports = {
  5894. ftyp: ftyp,
  5895. mdat: mdat,
  5896. moof: moof,
  5897. moov: moov,
  5898. initSegment: function(tracks) {
  5899. var
  5900. fileType = ftyp(),
  5901. movie = moov(tracks),
  5902. result;
  5903.  
  5904. result = new Uint8Array(fileType.byteLength + movie.byteLength);
  5905. result.set(fileType);
  5906. result.set(movie, fileType.byteLength);
  5907. return result;
  5908. }
  5909. };
  5910.  
  5911. },{}],26:[function(require,module,exports){
  5912. /**
  5913. * mux.js
  5914. *
  5915. * Copyright (c) Brightcove
  5916. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  5917. *
  5918. * Utilities to detect basic properties and metadata about MP4s.
  5919. */
  5920. 'use strict';
  5921.  
  5922. var toUnsigned = require(37).toUnsigned;
  5923. var findBox, parseType, timescale, startTime, getVideoTrackIds;
  5924.  
  5925. // Find the data for a box specified by its path
  5926. findBox = function(data, path) {
  5927. var results = [],
  5928. i, size, type, end, subresults;
  5929.  
  5930. if (!path.length) {
  5931. // short-circuit the search for empty paths
  5932. return null;
  5933. }
  5934.  
  5935. for (i = 0; i < data.byteLength;) {
  5936. size = toUnsigned(data[i] << 24 |
  5937. data[i + 1] << 16 |
  5938. data[i + 2] << 8 |
  5939. data[i + 3]);
  5940.  
  5941. type = parseType(data.subarray(i + 4, i + 8));
  5942.  
  5943. end = size > 1 ? i + size : data.byteLength;
  5944.  
  5945. if (type === path[0]) {
  5946. if (path.length === 1) {
  5947. // this is the end of the path and we've found the box we were
  5948. // looking for
  5949. results.push(data.subarray(i + 8, end));
  5950. } else {
  5951. // recursively search for the next box along the path
  5952. subresults = findBox(data.subarray(i + 8, end), path.slice(1));
  5953. if (subresults.length) {
  5954. results = results.concat(subresults);
  5955. }
  5956. }
  5957. }
  5958. i = end;
  5959. }
  5960.  
  5961. // we've finished searching all of data
  5962. return results;
  5963. };
  5964.  
  5965. /**
  5966. * Returns the string representation of an ASCII encoded four byte buffer.
  5967. * @param buffer {Uint8Array} a four-byte buffer to translate
  5968. * @return {string} the corresponding string
  5969. */
  5970. parseType = function(buffer) {
  5971. var result = '';
  5972. result += String.fromCharCode(buffer[0]);
  5973. result += String.fromCharCode(buffer[1]);
  5974. result += String.fromCharCode(buffer[2]);
  5975. result += String.fromCharCode(buffer[3]);
  5976. return result;
  5977. };
  5978.  
  5979. /**
  5980. * Parses an MP4 initialization segment and extracts the timescale
  5981. * values for any declared tracks. Timescale values indicate the
  5982. * number of clock ticks per second to assume for time-based values
  5983. * elsewhere in the MP4.
  5984. *
  5985. * To determine the start time of an MP4, you need two pieces of
  5986. * information: the timescale unit and the earliest base media decode
  5987. * time. Multiple timescales can be specified within an MP4 but the
  5988. * base media decode time is always expressed in the timescale from
  5989. * the media header box for the track:
  5990. * ```
  5991. * moov > trak > mdia > mdhd.timescale
  5992. * ```
  5993. * @param init {Uint8Array} the bytes of the init segment
  5994. * @return {object} a hash of track ids to timescale values or null if
  5995. * the init segment is malformed.
  5996. */
  5997. timescale = function(init) {
  5998. var
  5999. result = {},
  6000. traks = findBox(init, ['moov', 'trak']);
  6001.  
  6002. // mdhd timescale
  6003. return traks.reduce(function(result, trak) {
  6004. var tkhd, version, index, id, mdhd;
  6005.  
  6006. tkhd = findBox(trak, ['tkhd'])[0];
  6007. if (!tkhd) {
  6008. return null;
  6009. }
  6010. version = tkhd[0];
  6011. index = version === 0 ? 12 : 20;
  6012. id = toUnsigned(tkhd[index] << 24 |
  6013. tkhd[index + 1] << 16 |
  6014. tkhd[index + 2] << 8 |
  6015. tkhd[index + 3]);
  6016.  
  6017. mdhd = findBox(trak, ['mdia', 'mdhd'])[0];
  6018. if (!mdhd) {
  6019. return null;
  6020. }
  6021. version = mdhd[0];
  6022. index = version === 0 ? 12 : 20;
  6023. result[id] = toUnsigned(mdhd[index] << 24 |
  6024. mdhd[index + 1] << 16 |
  6025. mdhd[index + 2] << 8 |
  6026. mdhd[index + 3]);
  6027. return result;
  6028. }, result);
  6029. };
  6030.  
  6031. /**
  6032. * Determine the base media decode start time, in seconds, for an MP4
  6033. * fragment. If multiple fragments are specified, the earliest time is
  6034. * returned.
  6035. *
  6036. * The base media decode time can be parsed from track fragment
  6037. * metadata:
  6038. * ```
  6039. * moof > traf > tfdt.baseMediaDecodeTime
  6040. * ```
  6041. * It requires the timescale value from the mdhd to interpret.
  6042. *
  6043. * @param timescale {object} a hash of track ids to timescale values.
  6044. * @return {number} the earliest base media decode start time for the
  6045. * fragment, in seconds
  6046. */
  6047. startTime = function(timescale, fragment) {
  6048. var trafs, baseTimes, result;
  6049.  
  6050. // we need info from two childrend of each track fragment box
  6051. trafs = findBox(fragment, ['moof', 'traf']);
  6052.  
  6053. // determine the start times for each track
  6054. baseTimes = [].concat.apply([], trafs.map(function(traf) {
  6055. return findBox(traf, ['tfhd']).map(function(tfhd) {
  6056. var id, scale, baseTime;
  6057.  
  6058. // get the track id from the tfhd
  6059. id = toUnsigned(tfhd[4] << 24 |
  6060. tfhd[5] << 16 |
  6061. tfhd[6] << 8 |
  6062. tfhd[7]);
  6063. // assume a 90kHz clock if no timescale was specified
  6064. scale = timescale[id] || 90e3;
  6065.  
  6066. // get the base media decode time from the tfdt
  6067. baseTime = findBox(traf, ['tfdt']).map(function(tfdt) {
  6068. var version, result;
  6069.  
  6070. version = tfdt[0];
  6071. result = toUnsigned(tfdt[4] << 24 |
  6072. tfdt[5] << 16 |
  6073. tfdt[6] << 8 |
  6074. tfdt[7]);
  6075. if (version === 1) {
  6076. result *= Math.pow(2, 32);
  6077. result += toUnsigned(tfdt[8] << 24 |
  6078. tfdt[9] << 16 |
  6079. tfdt[10] << 8 |
  6080. tfdt[11]);
  6081. }
  6082. return result;
  6083. })[0];
  6084. baseTime = baseTime || Infinity;
  6085.  
  6086. // convert base time to seconds
  6087. return baseTime / scale;
  6088. });
  6089. }));
  6090.  
  6091. // return the minimum
  6092. result = Math.min.apply(null, baseTimes);
  6093. return isFinite(result) ? result : 0;
  6094. };
  6095.  
  6096. /**
  6097. * Find the trackIds of the video tracks in this source.
  6098. * Found by parsing the Handler Reference and Track Header Boxes:
  6099. * moov > trak > mdia > hdlr
  6100. * moov > trak > tkhd
  6101. *
  6102. * @param {Uint8Array} init - The bytes of the init segment for this source
  6103. * @return {Number[]} A list of trackIds
  6104. *
  6105. * @see ISO-BMFF-12/2015, Section 8.4.3
  6106. **/
  6107. getVideoTrackIds = function(init) {
  6108. var traks = findBox(init, ['moov', 'trak']);
  6109. var videoTrackIds = [];
  6110.  
  6111. traks.forEach(function(trak) {
  6112. var hdlrs = findBox(trak, ['mdia', 'hdlr']);
  6113. var tkhds = findBox(trak, ['tkhd']);
  6114.  
  6115. hdlrs.forEach(function(hdlr, index) {
  6116. var handlerType = parseType(hdlr.subarray(8, 12));
  6117. var tkhd = tkhds[index];
  6118. var view;
  6119. var version;
  6120. var trackId;
  6121.  
  6122. if (handlerType === 'vide') {
  6123. view = new DataView(tkhd.buffer, tkhd.byteOffset, tkhd.byteLength);
  6124. version = view.getUint8(0);
  6125. trackId = (version === 0) ? view.getUint32(12) : view.getUint32(20);
  6126.  
  6127. videoTrackIds.push(trackId);
  6128. }
  6129. });
  6130. });
  6131.  
  6132. return videoTrackIds;
  6133. };
  6134.  
  6135. module.exports = {
  6136. findBox: findBox,
  6137. parseType: parseType,
  6138. timescale: timescale,
  6139. startTime: startTime,
  6140. videoTrackIds: getVideoTrackIds
  6141. };
  6142.  
  6143. },{"37":37}],27:[function(require,module,exports){
  6144. /**
  6145. * mux.js
  6146. *
  6147. * Copyright (c) Brightcove
  6148. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6149. */
  6150. var ONE_SECOND_IN_TS = require(38).ONE_SECOND_IN_TS;
  6151.  
  6152. /**
  6153. * Store information about the start and end of the track and the
  6154. * duration for each frame/sample we process in order to calculate
  6155. * the baseMediaDecodeTime
  6156. */
  6157. var collectDtsInfo = function(track, data) {
  6158. if (typeof data.pts === 'number') {
  6159. if (track.timelineStartInfo.pts === undefined) {
  6160. track.timelineStartInfo.pts = data.pts;
  6161. }
  6162.  
  6163. if (track.minSegmentPts === undefined) {
  6164. track.minSegmentPts = data.pts;
  6165. } else {
  6166. track.minSegmentPts = Math.min(track.minSegmentPts, data.pts);
  6167. }
  6168.  
  6169. if (track.maxSegmentPts === undefined) {
  6170. track.maxSegmentPts = data.pts;
  6171. } else {
  6172. track.maxSegmentPts = Math.max(track.maxSegmentPts, data.pts);
  6173. }
  6174. }
  6175.  
  6176. if (typeof data.dts === 'number') {
  6177. if (track.timelineStartInfo.dts === undefined) {
  6178. track.timelineStartInfo.dts = data.dts;
  6179. }
  6180.  
  6181. if (track.minSegmentDts === undefined) {
  6182. track.minSegmentDts = data.dts;
  6183. } else {
  6184. track.minSegmentDts = Math.min(track.minSegmentDts, data.dts);
  6185. }
  6186.  
  6187. if (track.maxSegmentDts === undefined) {
  6188. track.maxSegmentDts = data.dts;
  6189. } else {
  6190. track.maxSegmentDts = Math.max(track.maxSegmentDts, data.dts);
  6191. }
  6192. }
  6193. };
  6194.  
  6195. /**
  6196. * Clear values used to calculate the baseMediaDecodeTime between
  6197. * tracks
  6198. */
  6199. var clearDtsInfo = function(track) {
  6200. delete track.minSegmentDts;
  6201. delete track.maxSegmentDts;
  6202. delete track.minSegmentPts;
  6203. delete track.maxSegmentPts;
  6204. };
  6205.  
  6206. /**
  6207. * Calculate the track's baseMediaDecodeTime based on the earliest
  6208. * DTS the transmuxer has ever seen and the minimum DTS for the
  6209. * current track
  6210. * @param track {object} track metadata configuration
  6211. * @param keepOriginalTimestamps {boolean} If true, keep the timestamps
  6212. * in the source; false to adjust the first segment to start at 0.
  6213. */
  6214. var calculateTrackBaseMediaDecodeTime = function(track, keepOriginalTimestamps) {
  6215. var
  6216. baseMediaDecodeTime,
  6217. scale,
  6218. minSegmentDts = track.minSegmentDts;
  6219.  
  6220. // Optionally adjust the time so the first segment starts at zero.
  6221. if (!keepOriginalTimestamps) {
  6222. minSegmentDts -= track.timelineStartInfo.dts;
  6223. }
  6224.  
  6225. // track.timelineStartInfo.baseMediaDecodeTime is the location, in time, where
  6226. // we want the start of the first segment to be placed
  6227. baseMediaDecodeTime = track.timelineStartInfo.baseMediaDecodeTime;
  6228.  
  6229. // Add to that the distance this segment is from the very first
  6230. baseMediaDecodeTime += minSegmentDts;
  6231.  
  6232. // baseMediaDecodeTime must not become negative
  6233. baseMediaDecodeTime = Math.max(0, baseMediaDecodeTime);
  6234.  
  6235. if (track.type === 'audio') {
  6236. // Audio has a different clock equal to the sampling_rate so we need to
  6237. // scale the PTS values into the clock rate of the track
  6238. scale = track.samplerate / ONE_SECOND_IN_TS;
  6239. baseMediaDecodeTime *= scale;
  6240. baseMediaDecodeTime = Math.floor(baseMediaDecodeTime);
  6241. }
  6242.  
  6243. return baseMediaDecodeTime;
  6244. };
  6245.  
  6246. module.exports = {
  6247. clearDtsInfo: clearDtsInfo,
  6248. calculateTrackBaseMediaDecodeTime: calculateTrackBaseMediaDecodeTime,
  6249. collectDtsInfo: collectDtsInfo
  6250. };
  6251.  
  6252. },{"38":38}],28:[function(require,module,exports){
  6253. /**
  6254. * mux.js
  6255. *
  6256. * Copyright (c) Brightcove
  6257. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  6258. *
  6259. * A stream-based mp2t to mp4 converter. This utility can be used to
  6260. * deliver mp4s to a SourceBuffer on platforms that support native
  6261. * Media Source Extensions.
  6262. */
  6263. 'use strict';
  6264.  
  6265. var Stream = require(40);
  6266. var mp4 = require(25);
  6267. var frameUtils = require(23);
  6268. var audioFrameUtils = require(21);
  6269. var trackDecodeInfo = require(27);
  6270. var m2ts = require(16);
  6271. var clock = require(38);
  6272. var AdtsStream = require(3);
  6273. var H264Stream = require(4).H264Stream;
  6274. var AacStream = require(1);
  6275. var isLikelyAacData = require(2).isLikelyAacData;
  6276.  
  6277. var ONE_SECOND_IN_TS = 90000; // 90kHz clock
  6278.  
  6279. // constants
  6280. var AUDIO_PROPERTIES = [
  6281. 'audioobjecttype',
  6282. 'channelcount',
  6283. 'samplerate',
  6284. 'samplingfrequencyindex',
  6285. 'samplesize'
  6286. ];
  6287.  
  6288. var VIDEO_PROPERTIES = [
  6289. 'width',
  6290. 'height',
  6291. 'profileIdc',
  6292. 'levelIdc',
  6293. 'profileCompatibility'
  6294. ];
  6295.  
  6296. // object types
  6297. var VideoSegmentStream, AudioSegmentStream, Transmuxer, CoalesceStream;
  6298.  
  6299. /**
  6300. * Compare two arrays (even typed) for same-ness
  6301. */
  6302. var arrayEquals = function(a, b) {
  6303. var
  6304. i;
  6305.  
  6306. if (a.length !== b.length) {
  6307. return false;
  6308. }
  6309.  
  6310. // compare the value of each element in the array
  6311. for (i = 0; i < a.length; i++) {
  6312. if (a[i] !== b[i]) {
  6313. return false;
  6314. }
  6315. }
  6316.  
  6317. return true;
  6318. };
  6319.  
  6320. var generateVideoSegmentTimingInfo = function(
  6321. baseMediaDecodeTime,
  6322. startDts,
  6323. startPts,
  6324. endDts,
  6325. endPts,
  6326. prependedContentDuration
  6327. ) {
  6328. var
  6329. ptsOffsetFromDts = startPts - startDts,
  6330. decodeDuration = endDts - startDts,
  6331. presentationDuration = endPts - startPts;
  6332.  
  6333. // The PTS and DTS values are based on the actual stream times from the segment,
  6334. // however, the player time values will reflect a start from the baseMediaDecodeTime.
  6335. // In order to provide relevant values for the player times, base timing info on the
  6336. // baseMediaDecodeTime and the DTS and PTS durations of the segment.
  6337. return {
  6338. start: {
  6339. dts: baseMediaDecodeTime,
  6340. pts: baseMediaDecodeTime + ptsOffsetFromDts
  6341. },
  6342. end: {
  6343. dts: baseMediaDecodeTime + decodeDuration,
  6344. pts: baseMediaDecodeTime + presentationDuration
  6345. },
  6346. prependedContentDuration: prependedContentDuration,
  6347. baseMediaDecodeTime: baseMediaDecodeTime
  6348. };
  6349. };
  6350.  
  6351. /**
  6352. * Constructs a single-track, ISO BMFF media segment from AAC data
  6353. * events. The output of this stream can be fed to a SourceBuffer
  6354. * configured with a suitable initialization segment.
  6355. * @param track {object} track metadata configuration
  6356. * @param options {object} transmuxer options object
  6357. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  6358. * in the source; false to adjust the first segment to start at 0.
  6359. */
  6360. AudioSegmentStream = function(track, options) {
  6361. var
  6362. adtsFrames = [],
  6363. sequenceNumber = 0,
  6364. earliestAllowedDts = 0,
  6365. audioAppendStartTs = 0,
  6366. videoBaseMediaDecodeTime = Infinity;
  6367.  
  6368. options = options || {};
  6369.  
  6370. AudioSegmentStream.prototype.init.call(this);
  6371.  
  6372. this.push = function(data) {
  6373. trackDecodeInfo.collectDtsInfo(track, data);
  6374.  
  6375. if (track) {
  6376. AUDIO_PROPERTIES.forEach(function(prop) {
  6377. track[prop] = data[prop];
  6378. });
  6379. }
  6380.  
  6381. // buffer audio data until end() is called
  6382. adtsFrames.push(data);
  6383. };
  6384.  
  6385. this.setEarliestDts = function(earliestDts) {
  6386. earliestAllowedDts = earliestDts - track.timelineStartInfo.baseMediaDecodeTime;
  6387. };
  6388.  
  6389. this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  6390. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  6391. };
  6392.  
  6393. this.setAudioAppendStart = function(timestamp) {
  6394. audioAppendStartTs = timestamp;
  6395. };
  6396.  
  6397. this.flush = function() {
  6398. var
  6399. frames,
  6400. moof,
  6401. mdat,
  6402. boxes,
  6403. frameDuration;
  6404.  
  6405. // return early if no audio data has been observed
  6406. if (adtsFrames.length === 0) {
  6407. this.trigger('done', 'AudioSegmentStream');
  6408. return;
  6409. }
  6410.  
  6411. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(
  6412. adtsFrames, track, earliestAllowedDts);
  6413. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
  6414. track, options.keepOriginalTimestamps);
  6415.  
  6416. audioFrameUtils.prefixWithSilence(
  6417. track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);
  6418.  
  6419. // we have to build the index from byte locations to
  6420. // samples (that is, adts frames) in the audio data
  6421. track.samples = audioFrameUtils.generateSampleTable(frames);
  6422.  
  6423. // concatenate the audio data to constuct the mdat
  6424. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  6425.  
  6426. adtsFrames = [];
  6427.  
  6428. moof = mp4.moof(sequenceNumber, [track]);
  6429. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  6430.  
  6431. // bump the sequence number for next time
  6432. sequenceNumber++;
  6433.  
  6434. boxes.set(moof);
  6435. boxes.set(mdat, moof.byteLength);
  6436.  
  6437. trackDecodeInfo.clearDtsInfo(track);
  6438.  
  6439. frameDuration = Math.ceil(ONE_SECOND_IN_TS * 1024 / track.samplerate);
  6440.  
  6441. // TODO this check was added to maintain backwards compatibility (particularly with
  6442. // tests) on adding the timingInfo event. However, it seems unlikely that there's a
  6443. // valid use-case where an init segment/data should be triggered without associated
  6444. // frames. Leaving for now, but should be looked into.
  6445. if (frames.length) {
  6446. this.trigger('timingInfo', {
  6447. start: frames[0].dts,
  6448. end: frames[0].dts + (frames.length * frameDuration)
  6449. });
  6450. }
  6451. this.trigger('data', {track: track, boxes: boxes});
  6452. this.trigger('done', 'AudioSegmentStream');
  6453. };
  6454.  
  6455. this.reset = function() {
  6456. trackDecodeInfo.clearDtsInfo(track);
  6457. adtsFrames = [];
  6458. this.trigger('reset');
  6459. };
  6460. };
  6461.  
  6462. AudioSegmentStream.prototype = new Stream();
  6463.  
  6464. /**
  6465. * Constructs a single-track, ISO BMFF media segment from H264 data
  6466. * events. The output of this stream can be fed to a SourceBuffer
  6467. * configured with a suitable initialization segment.
  6468. * @param track {object} track metadata configuration
  6469. * @param options {object} transmuxer options object
  6470. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  6471. * gopsToAlignWith list when attempting to align gop pts
  6472. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  6473. * in the source; false to adjust the first segment to start at 0.
  6474. */
  6475. VideoSegmentStream = function(track, options) {
  6476. var
  6477. sequenceNumber = 0,
  6478. nalUnits = [],
  6479. gopsToAlignWith = [],
  6480. config,
  6481. pps;
  6482.  
  6483. options = options || {};
  6484.  
  6485. VideoSegmentStream.prototype.init.call(this);
  6486.  
  6487. delete track.minPTS;
  6488.  
  6489. this.gopCache_ = [];
  6490.  
  6491. /**
  6492. * Constructs a ISO BMFF segment given H264 nalUnits
  6493. * @param {Object} nalUnit A data event representing a nalUnit
  6494. * @param {String} nalUnit.nalUnitType
  6495. * @param {Object} nalUnit.config Properties for a mp4 track
  6496. * @param {Uint8Array} nalUnit.data The nalUnit bytes
  6497. * @see lib/codecs/h264.js
  6498. **/
  6499. this.push = function(nalUnit) {
  6500. trackDecodeInfo.collectDtsInfo(track, nalUnit);
  6501.  
  6502. // record the track config
  6503. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  6504. config = nalUnit.config;
  6505. track.sps = [nalUnit.data];
  6506.  
  6507. VIDEO_PROPERTIES.forEach(function(prop) {
  6508. track[prop] = config[prop];
  6509. }, this);
  6510. }
  6511.  
  6512. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
  6513. !pps) {
  6514. pps = nalUnit.data;
  6515. track.pps = [nalUnit.data];
  6516. }
  6517.  
  6518. // buffer video until flush() is called
  6519. nalUnits.push(nalUnit);
  6520. };
  6521.  
  6522. /**
  6523. * Pass constructed ISO BMFF track and boxes on to the
  6524. * next stream in the pipeline
  6525. **/
  6526. this.flush = function() {
  6527. var
  6528. frames,
  6529. gopForFusion,
  6530. gops,
  6531. moof,
  6532. mdat,
  6533. boxes,
  6534. prependedContentDuration = 0,
  6535. firstGop,
  6536. lastGop;
  6537.  
  6538. // Throw away nalUnits at the start of the byte stream until
  6539. // we find the first AUD
  6540. while (nalUnits.length) {
  6541. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  6542. break;
  6543. }
  6544. nalUnits.shift();
  6545. }
  6546.  
  6547. // Return early if no video data has been observed
  6548. if (nalUnits.length === 0) {
  6549. this.resetStream_();
  6550. this.trigger('done', 'VideoSegmentStream');
  6551. return;
  6552. }
  6553.  
  6554. // Organize the raw nal-units into arrays that represent
  6555. // higher-level constructs such as frames and gops
  6556. // (group-of-pictures)
  6557. frames = frameUtils.groupNalsIntoFrames(nalUnits);
  6558. gops = frameUtils.groupFramesIntoGops(frames);
  6559.  
  6560. // If the first frame of this fragment is not a keyframe we have
  6561. // a problem since MSE (on Chrome) requires a leading keyframe.
  6562. //
  6563. // We have two approaches to repairing this situation:
  6564. // 1) GOP-FUSION:
  6565. // This is where we keep track of the GOPS (group-of-pictures)
  6566. // from previous fragments and attempt to find one that we can
  6567. // prepend to the current fragment in order to create a valid
  6568. // fragment.
  6569. // 2) KEYFRAME-PULLING:
  6570. // Here we search for the first keyframe in the fragment and
  6571. // throw away all the frames between the start of the fragment
  6572. // and that keyframe. We then extend the duration and pull the
  6573. // PTS of the keyframe forward so that it covers the time range
  6574. // of the frames that were disposed of.
  6575. //
  6576. // #1 is far prefereable over #2 which can cause "stuttering" but
  6577. // requires more things to be just right.
  6578. if (!gops[0][0].keyFrame) {
  6579. // Search for a gop for fusion from our gopCache
  6580. gopForFusion = this.getGopForFusion_(nalUnits[0], track);
  6581.  
  6582. if (gopForFusion) {
  6583. // in order to provide more accurate timing information about the segment, save
  6584. // the number of seconds prepended to the original segment due to GOP fusion
  6585. prependedContentDuration = gopForFusion.duration;
  6586.  
  6587. gops.unshift(gopForFusion);
  6588. // Adjust Gops' metadata to account for the inclusion of the
  6589. // new gop at the beginning
  6590. gops.byteLength += gopForFusion.byteLength;
  6591. gops.nalCount += gopForFusion.nalCount;
  6592. gops.pts = gopForFusion.pts;
  6593. gops.dts = gopForFusion.dts;
  6594. gops.duration += gopForFusion.duration;
  6595. } else {
  6596. // If we didn't find a candidate gop fall back to keyframe-pulling
  6597. gops = frameUtils.extendFirstKeyFrame(gops);
  6598. }
  6599. }
  6600.  
  6601. // Trim gops to align with gopsToAlignWith
  6602. if (gopsToAlignWith.length) {
  6603. var alignedGops;
  6604.  
  6605. if (options.alignGopsAtEnd) {
  6606. alignedGops = this.alignGopsAtEnd_(gops);
  6607. } else {
  6608. alignedGops = this.alignGopsAtStart_(gops);
  6609. }
  6610.  
  6611. if (!alignedGops) {
  6612. // save all the nals in the last GOP into the gop cache
  6613. this.gopCache_.unshift({
  6614. gop: gops.pop(),
  6615. pps: track.pps,
  6616. sps: track.sps
  6617. });
  6618.  
  6619. // Keep a maximum of 6 GOPs in the cache
  6620. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  6621.  
  6622. // Clear nalUnits
  6623. nalUnits = [];
  6624.  
  6625. // return early no gops can be aligned with desired gopsToAlignWith
  6626. this.resetStream_();
  6627. this.trigger('done', 'VideoSegmentStream');
  6628. return;
  6629. }
  6630.  
  6631. // Some gops were trimmed. clear dts info so minSegmentDts and pts are correct
  6632. // when recalculated before sending off to CoalesceStream
  6633. trackDecodeInfo.clearDtsInfo(track);
  6634.  
  6635. gops = alignedGops;
  6636. }
  6637.  
  6638. trackDecodeInfo.collectDtsInfo(track, gops);
  6639.  
  6640. // First, we have to build the index from byte locations to
  6641. // samples (that is, frames) in the video data
  6642. track.samples = frameUtils.generateSampleTable(gops);
  6643.  
  6644. // Concatenate the video data and construct the mdat
  6645. mdat = mp4.mdat(frameUtils.concatenateNalData(gops));
  6646.  
  6647. track.baseMediaDecodeTime = trackDecodeInfo.calculateTrackBaseMediaDecodeTime(
  6648. track, options.keepOriginalTimestamps);
  6649.  
  6650. this.trigger('processedGopsInfo', gops.map(function(gop) {
  6651. return {
  6652. pts: gop.pts,
  6653. dts: gop.dts,
  6654. byteLength: gop.byteLength
  6655. };
  6656. }));
  6657.  
  6658. firstGop = gops[0];
  6659. lastGop = gops[gops.length - 1];
  6660.  
  6661. this.trigger(
  6662. 'segmentTimingInfo',
  6663. generateVideoSegmentTimingInfo(
  6664. track.baseMediaDecodeTime,
  6665. firstGop.dts,
  6666. firstGop.pts,
  6667. lastGop.dts + lastGop.duration,
  6668. lastGop.pts + lastGop.duration,
  6669. prependedContentDuration));
  6670.  
  6671. this.trigger('timingInfo', {
  6672. start: gops[0].dts,
  6673. end: gops[gops.length - 1].dts + gops[gops.length - 1].duration
  6674. });
  6675.  
  6676. // save all the nals in the last GOP into the gop cache
  6677. this.gopCache_.unshift({
  6678. gop: gops.pop(),
  6679. pps: track.pps,
  6680. sps: track.sps
  6681. });
  6682.  
  6683. // Keep a maximum of 6 GOPs in the cache
  6684. this.gopCache_.length = Math.min(6, this.gopCache_.length);
  6685.  
  6686. // Clear nalUnits
  6687. nalUnits = [];
  6688.  
  6689. this.trigger('baseMediaDecodeTime', track.baseMediaDecodeTime);
  6690. this.trigger('timelineStartInfo', track.timelineStartInfo);
  6691.  
  6692. moof = mp4.moof(sequenceNumber, [track]);
  6693.  
  6694. // it would be great to allocate this array up front instead of
  6695. // throwing away hundreds of media segment fragments
  6696. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  6697.  
  6698. // Bump the sequence number for next time
  6699. sequenceNumber++;
  6700.  
  6701. boxes.set(moof);
  6702. boxes.set(mdat, moof.byteLength);
  6703.  
  6704. this.trigger('data', {track: track, boxes: boxes});
  6705.  
  6706. this.resetStream_();
  6707.  
  6708. // Continue with the flush process now
  6709. this.trigger('done', 'VideoSegmentStream');
  6710. };
  6711.  
  6712. this.reset = function() {
  6713. this.resetStream_();
  6714. nalUnits = [];
  6715. this.gopCache_.length = 0;
  6716. gopsToAlignWith.length = 0;
  6717. this.trigger('reset');
  6718. };
  6719.  
  6720. this.resetStream_ = function() {
  6721. trackDecodeInfo.clearDtsInfo(track);
  6722.  
  6723. // reset config and pps because they may differ across segments
  6724. // for instance, when we are rendition switching
  6725. config = undefined;
  6726. pps = undefined;
  6727. };
  6728.  
  6729. // Search for a candidate Gop for gop-fusion from the gop cache and
  6730. // return it or return null if no good candidate was found
  6731. this.getGopForFusion_ = function(nalUnit) {
  6732. var
  6733. halfSecond = 45000, // Half-a-second in a 90khz clock
  6734. allowableOverlap = 10000, // About 3 frames @ 30fps
  6735. nearestDistance = Infinity,
  6736. dtsDistance,
  6737. nearestGopObj,
  6738. currentGop,
  6739. currentGopObj,
  6740. i;
  6741.  
  6742. // Search for the GOP nearest to the beginning of this nal unit
  6743. for (i = 0; i < this.gopCache_.length; i++) {
  6744. currentGopObj = this.gopCache_[i];
  6745. currentGop = currentGopObj.gop;
  6746.  
  6747. // Reject Gops with different SPS or PPS
  6748. if (!(track.pps && arrayEquals(track.pps[0], currentGopObj.pps[0])) ||
  6749. !(track.sps && arrayEquals(track.sps[0], currentGopObj.sps[0]))) {
  6750. continue;
  6751. }
  6752.  
  6753. // Reject Gops that would require a negative baseMediaDecodeTime
  6754. if (currentGop.dts < track.timelineStartInfo.dts) {
  6755. continue;
  6756. }
  6757.  
  6758. // The distance between the end of the gop and the start of the nalUnit
  6759. dtsDistance = (nalUnit.dts - currentGop.dts) - currentGop.duration;
  6760.  
  6761. // Only consider GOPS that start before the nal unit and end within
  6762. // a half-second of the nal unit
  6763. if (dtsDistance >= -allowableOverlap &&
  6764. dtsDistance <= halfSecond) {
  6765.  
  6766. // Always use the closest GOP we found if there is more than
  6767. // one candidate
  6768. if (!nearestGopObj ||
  6769. nearestDistance > dtsDistance) {
  6770. nearestGopObj = currentGopObj;
  6771. nearestDistance = dtsDistance;
  6772. }
  6773. }
  6774. }
  6775.  
  6776. if (nearestGopObj) {
  6777. return nearestGopObj.gop;
  6778. }
  6779. return null;
  6780. };
  6781.  
  6782. // trim gop list to the first gop found that has a matching pts with a gop in the list
  6783. // of gopsToAlignWith starting from the START of the list
  6784. this.alignGopsAtStart_ = function(gops) {
  6785. var alignIndex, gopIndex, align, gop, byteLength, nalCount, duration, alignedGops;
  6786.  
  6787. byteLength = gops.byteLength;
  6788. nalCount = gops.nalCount;
  6789. duration = gops.duration;
  6790. alignIndex = gopIndex = 0;
  6791.  
  6792. while (alignIndex < gopsToAlignWith.length && gopIndex < gops.length) {
  6793. align = gopsToAlignWith[alignIndex];
  6794. gop = gops[gopIndex];
  6795.  
  6796. if (align.pts === gop.pts) {
  6797. break;
  6798. }
  6799.  
  6800. if (gop.pts > align.pts) {
  6801. // this current gop starts after the current gop we want to align on, so increment
  6802. // align index
  6803. alignIndex++;
  6804. continue;
  6805. }
  6806.  
  6807. // current gop starts before the current gop we want to align on. so increment gop
  6808. // index
  6809. gopIndex++;
  6810. byteLength -= gop.byteLength;
  6811. nalCount -= gop.nalCount;
  6812. duration -= gop.duration;
  6813. }
  6814.  
  6815. if (gopIndex === 0) {
  6816. // no gops to trim
  6817. return gops;
  6818. }
  6819.  
  6820. if (gopIndex === gops.length) {
  6821. // all gops trimmed, skip appending all gops
  6822. return null;
  6823. }
  6824.  
  6825. alignedGops = gops.slice(gopIndex);
  6826. alignedGops.byteLength = byteLength;
  6827. alignedGops.duration = duration;
  6828. alignedGops.nalCount = nalCount;
  6829. alignedGops.pts = alignedGops[0].pts;
  6830. alignedGops.dts = alignedGops[0].dts;
  6831.  
  6832. return alignedGops;
  6833. };
  6834.  
  6835. // trim gop list to the first gop found that has a matching pts with a gop in the list
  6836. // of gopsToAlignWith starting from the END of the list
  6837. this.alignGopsAtEnd_ = function(gops) {
  6838. var alignIndex, gopIndex, align, gop, alignEndIndex, matchFound;
  6839.  
  6840. alignIndex = gopsToAlignWith.length - 1;
  6841. gopIndex = gops.length - 1;
  6842. alignEndIndex = null;
  6843. matchFound = false;
  6844.  
  6845. while (alignIndex >= 0 && gopIndex >= 0) {
  6846. align = gopsToAlignWith[alignIndex];
  6847. gop = gops[gopIndex];
  6848.  
  6849. if (align.pts === gop.pts) {
  6850. matchFound = true;
  6851. break;
  6852. }
  6853.  
  6854. if (align.pts > gop.pts) {
  6855. alignIndex--;
  6856. continue;
  6857. }
  6858.  
  6859. if (alignIndex === gopsToAlignWith.length - 1) {
  6860. // gop.pts is greater than the last alignment candidate. If no match is found
  6861. // by the end of this loop, we still want to append gops that come after this
  6862. // point
  6863. alignEndIndex = gopIndex;
  6864. }
  6865.  
  6866. gopIndex--;
  6867. }
  6868.  
  6869. if (!matchFound && alignEndIndex === null) {
  6870. return null;
  6871. }
  6872.  
  6873. var trimIndex;
  6874.  
  6875. if (matchFound) {
  6876. trimIndex = gopIndex;
  6877. } else {
  6878. trimIndex = alignEndIndex;
  6879. }
  6880.  
  6881. if (trimIndex === 0) {
  6882. return gops;
  6883. }
  6884.  
  6885. var alignedGops = gops.slice(trimIndex);
  6886. var metadata = alignedGops.reduce(function(total, gop) {
  6887. total.byteLength += gop.byteLength;
  6888. total.duration += gop.duration;
  6889. total.nalCount += gop.nalCount;
  6890. return total;
  6891. }, { byteLength: 0, duration: 0, nalCount: 0 });
  6892.  
  6893. alignedGops.byteLength = metadata.byteLength;
  6894. alignedGops.duration = metadata.duration;
  6895. alignedGops.nalCount = metadata.nalCount;
  6896. alignedGops.pts = alignedGops[0].pts;
  6897. alignedGops.dts = alignedGops[0].dts;
  6898.  
  6899. return alignedGops;
  6900. };
  6901.  
  6902. this.alignGopsWith = function(newGopsToAlignWith) {
  6903. gopsToAlignWith = newGopsToAlignWith;
  6904. };
  6905. };
  6906.  
  6907. VideoSegmentStream.prototype = new Stream();
  6908.  
  6909. /**
  6910. * A Stream that can combine multiple streams (ie. audio & video)
  6911. * into a single output segment for MSE. Also supports audio-only
  6912. * and video-only streams.
  6913. * @param options {object} transmuxer options object
  6914. * @param options.keepOriginalTimestamps {boolean} If true, keep the timestamps
  6915. * in the source; false to adjust the first segment to start at media timeline start.
  6916. */
  6917. CoalesceStream = function(options, metadataStream) {
  6918. // Number of Tracks per output segment
  6919. // If greater than 1, we combine multiple
  6920. // tracks into a single segment
  6921. this.numberOfTracks = 0;
  6922. this.metadataStream = metadataStream;
  6923.  
  6924. options = options || {};
  6925.  
  6926. if (typeof options.remux !== 'undefined') {
  6927. this.remuxTracks = !!options.remux;
  6928. } else {
  6929. this.remuxTracks = true;
  6930. }
  6931.  
  6932. if (typeof options.keepOriginalTimestamps === 'boolean') {
  6933. this.keepOriginalTimestamps = options.keepOriginalTimestamps;
  6934. } else {
  6935. this.keepOriginalTimestamps = false;
  6936. }
  6937.  
  6938. this.pendingTracks = [];
  6939. this.videoTrack = null;
  6940. this.pendingBoxes = [];
  6941. this.pendingCaptions = [];
  6942. this.pendingMetadata = [];
  6943. this.pendingBytes = 0;
  6944. this.emittedTracks = 0;
  6945.  
  6946. CoalesceStream.prototype.init.call(this);
  6947.  
  6948. // Take output from multiple
  6949. this.push = function(output) {
  6950. // buffer incoming captions until the associated video segment
  6951. // finishes
  6952. if (output.text) {
  6953. return this.pendingCaptions.push(output);
  6954. }
  6955. // buffer incoming id3 tags until the final flush
  6956. if (output.frames) {
  6957. return this.pendingMetadata.push(output);
  6958. }
  6959.  
  6960. // Add this track to the list of pending tracks and store
  6961. // important information required for the construction of
  6962. // the final segment
  6963. this.pendingTracks.push(output.track);
  6964. this.pendingBoxes.push(output.boxes);
  6965. this.pendingBytes += output.boxes.byteLength;
  6966.  
  6967. if (output.track.type === 'video') {
  6968. this.videoTrack = output.track;
  6969. }
  6970. if (output.track.type === 'audio') {
  6971. this.audioTrack = output.track;
  6972. }
  6973. };
  6974. };
  6975.  
  6976. CoalesceStream.prototype = new Stream();
  6977. CoalesceStream.prototype.flush = function(flushSource) {
  6978. var
  6979. offset = 0,
  6980. event = {
  6981. captions: [],
  6982. captionStreams: {},
  6983. metadata: [],
  6984. info: {}
  6985. },
  6986. caption,
  6987. id3,
  6988. initSegment,
  6989. timelineStartPts = 0,
  6990. i;
  6991.  
  6992. if (this.pendingTracks.length < this.numberOfTracks) {
  6993. if (flushSource !== 'VideoSegmentStream' &&
  6994. flushSource !== 'AudioSegmentStream') {
  6995. // Return because we haven't received a flush from a data-generating
  6996. // portion of the segment (meaning that we have only recieved meta-data
  6997. // or captions.)
  6998. return;
  6999. } else if (this.remuxTracks) {
  7000. // Return until we have enough tracks from the pipeline to remux (if we
  7001. // are remuxing audio and video into a single MP4)
  7002. return;
  7003. } else if (this.pendingTracks.length === 0) {
  7004. // In the case where we receive a flush without any data having been
  7005. // received we consider it an emitted track for the purposes of coalescing
  7006. // `done` events.
  7007. // We do this for the case where there is an audio and video track in the
  7008. // segment but no audio data. (seen in several playlists with alternate
  7009. // audio tracks and no audio present in the main TS segments.)
  7010. this.emittedTracks++;
  7011.  
  7012. if (this.emittedTracks >= this.numberOfTracks) {
  7013. this.trigger('done');
  7014. this.emittedTracks = 0;
  7015. }
  7016. return;
  7017. }
  7018. }
  7019.  
  7020. if (this.videoTrack) {
  7021. timelineStartPts = this.videoTrack.timelineStartInfo.pts;
  7022. VIDEO_PROPERTIES.forEach(function(prop) {
  7023. event.info[prop] = this.videoTrack[prop];
  7024. }, this);
  7025. } else if (this.audioTrack) {
  7026. timelineStartPts = this.audioTrack.timelineStartInfo.pts;
  7027. AUDIO_PROPERTIES.forEach(function(prop) {
  7028. event.info[prop] = this.audioTrack[prop];
  7029. }, this);
  7030. }
  7031.  
  7032. if (this.pendingTracks.length === 1) {
  7033. event.type = this.pendingTracks[0].type;
  7034. } else {
  7035. event.type = 'combined';
  7036. }
  7037.  
  7038. this.emittedTracks += this.pendingTracks.length;
  7039.  
  7040. initSegment = mp4.initSegment(this.pendingTracks);
  7041.  
  7042. // Create a new typed array to hold the init segment
  7043. event.initSegment = new Uint8Array(initSegment.byteLength);
  7044.  
  7045. // Create an init segment containing a moov
  7046. // and track definitions
  7047. event.initSegment.set(initSegment);
  7048.  
  7049. // Create a new typed array to hold the moof+mdats
  7050. event.data = new Uint8Array(this.pendingBytes);
  7051.  
  7052. // Append each moof+mdat (one per track) together
  7053. for (i = 0; i < this.pendingBoxes.length; i++) {
  7054. event.data.set(this.pendingBoxes[i], offset);
  7055. offset += this.pendingBoxes[i].byteLength;
  7056. }
  7057.  
  7058. // Translate caption PTS times into second offsets to match the
  7059. // video timeline for the segment, and add track info
  7060. for (i = 0; i < this.pendingCaptions.length; i++) {
  7061. caption = this.pendingCaptions[i];
  7062. caption.startTime = clock.metadataTsToSeconds(
  7063. caption.startPts, timelineStartPts, this.keepOriginalTimestamps);
  7064. caption.endTime = clock.metadataTsToSeconds(
  7065. caption.endPts, timelineStartPts, this.keepOriginalTimestamps);
  7066.  
  7067. event.captionStreams[caption.stream] = true;
  7068. event.captions.push(caption);
  7069. }
  7070.  
  7071. // Translate ID3 frame PTS times into second offsets to match the
  7072. // video timeline for the segment
  7073. for (i = 0; i < this.pendingMetadata.length; i++) {
  7074. id3 = this.pendingMetadata[i];
  7075. id3.cueTime = clock.videoTsToSeconds(
  7076. id3.pts, timelineStartPts, this.keepOriginalTimestamps);
  7077.  
  7078. event.metadata.push(id3);
  7079. }
  7080.  
  7081. // We add this to every single emitted segment even though we only need
  7082. // it for the first
  7083. event.metadata.dispatchType = this.metadataStream.dispatchType;
  7084.  
  7085. // Reset stream state
  7086. this.pendingTracks.length = 0;
  7087. this.videoTrack = null;
  7088. this.pendingBoxes.length = 0;
  7089. this.pendingCaptions.length = 0;
  7090. this.pendingBytes = 0;
  7091. this.pendingMetadata.length = 0;
  7092.  
  7093. // Emit the built segment
  7094. // We include captions and ID3 tags for backwards compatibility,
  7095. // ideally we should send only video and audio in the data event
  7096. this.trigger('data', event);
  7097. // Emit each caption to the outside world
  7098. // Ideally, this would happen immediately on parsing captions,
  7099. // but we need to ensure that video data is sent back first
  7100. // so that caption timing can be adjusted to match video timing
  7101. for (i = 0; i < event.captions.length; i++) {
  7102. caption = event.captions[i];
  7103.  
  7104. this.trigger('caption', caption);
  7105. }
  7106. // Emit each id3 tag to the outside world
  7107. // Ideally, this would happen immediately on parsing the tag,
  7108. // but we need to ensure that video data is sent back first
  7109. // so that ID3 frame timing can be adjusted to match video timing
  7110. for (i = 0; i < event.metadata.length; i++) {
  7111. id3 = event.metadata[i];
  7112.  
  7113. this.trigger('id3Frame', id3);
  7114. }
  7115.  
  7116. // Only emit `done` if all tracks have been flushed and emitted
  7117. if (this.emittedTracks >= this.numberOfTracks) {
  7118. this.trigger('done');
  7119. this.emittedTracks = 0;
  7120. }
  7121. };
  7122. /**
  7123. * A Stream that expects MP2T binary data as input and produces
  7124. * corresponding media segments, suitable for use with Media Source
  7125. * Extension (MSE) implementations that support the ISO BMFF byte
  7126. * stream format, like Chrome.
  7127. */
  7128. Transmuxer = function(options) {
  7129. var
  7130. self = this,
  7131. hasFlushed = true,
  7132. videoTrack,
  7133. audioTrack;
  7134.  
  7135. Transmuxer.prototype.init.call(this);
  7136.  
  7137. options = options || {};
  7138. this.baseMediaDecodeTime = options.baseMediaDecodeTime || 0;
  7139. this.transmuxPipeline_ = {};
  7140.  
  7141. this.setupAacPipeline = function() {
  7142. var pipeline = {};
  7143. this.transmuxPipeline_ = pipeline;
  7144.  
  7145. pipeline.type = 'aac';
  7146. pipeline.metadataStream = new m2ts.MetadataStream();
  7147.  
  7148. // set up the parsing pipeline
  7149. pipeline.aacStream = new AacStream();
  7150. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  7151. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  7152. pipeline.adtsStream = new AdtsStream();
  7153. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  7154. pipeline.headOfPipeline = pipeline.aacStream;
  7155.  
  7156. pipeline.aacStream
  7157. .pipe(pipeline.audioTimestampRolloverStream)
  7158. .pipe(pipeline.adtsStream);
  7159. pipeline.aacStream
  7160. .pipe(pipeline.timedMetadataTimestampRolloverStream)
  7161. .pipe(pipeline.metadataStream)
  7162. .pipe(pipeline.coalesceStream);
  7163.  
  7164. pipeline.metadataStream.on('timestamp', function(frame) {
  7165. pipeline.aacStream.setTimestamp(frame.timeStamp);
  7166. });
  7167.  
  7168. pipeline.aacStream.on('data', function(data) {
  7169. if (data.type === 'timed-metadata' && !pipeline.audioSegmentStream) {
  7170. audioTrack = audioTrack || {
  7171. timelineStartInfo: {
  7172. baseMediaDecodeTime: self.baseMediaDecodeTime
  7173. },
  7174. codec: 'adts',
  7175. type: 'audio'
  7176. };
  7177. // hook up the audio segment stream to the first track with aac data
  7178. pipeline.coalesceStream.numberOfTracks++;
  7179. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  7180.  
  7181. pipeline.audioSegmentStream.on('timingInfo',
  7182. self.trigger.bind(self, 'audioTimingInfo'));
  7183.  
  7184. // Set up the final part of the audio pipeline
  7185. pipeline.adtsStream
  7186. .pipe(pipeline.audioSegmentStream)
  7187. .pipe(pipeline.coalesceStream);
  7188. }
  7189. });
  7190.  
  7191. // Re-emit any data coming from the coalesce stream to the outside world
  7192. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  7193. // Let the consumer know we have finished flushing the entire pipeline
  7194. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  7195. };
  7196.  
  7197. this.setupTsPipeline = function() {
  7198. var pipeline = {};
  7199. this.transmuxPipeline_ = pipeline;
  7200.  
  7201. pipeline.type = 'ts';
  7202. pipeline.metadataStream = new m2ts.MetadataStream();
  7203.  
  7204. // set up the parsing pipeline
  7205. pipeline.packetStream = new m2ts.TransportPacketStream();
  7206. pipeline.parseStream = new m2ts.TransportParseStream();
  7207. pipeline.elementaryStream = new m2ts.ElementaryStream();
  7208. pipeline.videoTimestampRolloverStream = new m2ts.TimestampRolloverStream('video');
  7209. pipeline.audioTimestampRolloverStream = new m2ts.TimestampRolloverStream('audio');
  7210. pipeline.timedMetadataTimestampRolloverStream = new m2ts.TimestampRolloverStream('timed-metadata');
  7211. pipeline.adtsStream = new AdtsStream();
  7212. pipeline.h264Stream = new H264Stream();
  7213. pipeline.captionStream = new m2ts.CaptionStream();
  7214. pipeline.coalesceStream = new CoalesceStream(options, pipeline.metadataStream);
  7215. pipeline.headOfPipeline = pipeline.packetStream;
  7216.  
  7217. // disassemble MPEG2-TS packets into elementary streams
  7218. pipeline.packetStream
  7219. .pipe(pipeline.parseStream)
  7220. .pipe(pipeline.elementaryStream);
  7221.  
  7222. // !!THIS ORDER IS IMPORTANT!!
  7223. // demux the streams
  7224. pipeline.elementaryStream
  7225. .pipe(pipeline.videoTimestampRolloverStream)
  7226. .pipe(pipeline.h264Stream);
  7227. pipeline.elementaryStream
  7228. .pipe(pipeline.audioTimestampRolloverStream)
  7229. .pipe(pipeline.adtsStream);
  7230.  
  7231. pipeline.elementaryStream
  7232. .pipe(pipeline.timedMetadataTimestampRolloverStream)
  7233. .pipe(pipeline.metadataStream)
  7234. .pipe(pipeline.coalesceStream);
  7235.  
  7236. // Hook up CEA-608/708 caption stream
  7237. pipeline.h264Stream.pipe(pipeline.captionStream)
  7238. .pipe(pipeline.coalesceStream);
  7239.  
  7240. pipeline.elementaryStream.on('data', function(data) {
  7241. var i;
  7242.  
  7243. if (data.type === 'metadata') {
  7244. i = data.tracks.length;
  7245.  
  7246. // scan the tracks listed in the metadata
  7247. while (i--) {
  7248. if (!videoTrack && data.tracks[i].type === 'video') {
  7249. videoTrack = data.tracks[i];
  7250. videoTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  7251. } else if (!audioTrack && data.tracks[i].type === 'audio') {
  7252. audioTrack = data.tracks[i];
  7253. audioTrack.timelineStartInfo.baseMediaDecodeTime = self.baseMediaDecodeTime;
  7254. }
  7255. }
  7256.  
  7257. // hook up the video segment stream to the first track with h264 data
  7258. if (videoTrack && !pipeline.videoSegmentStream) {
  7259. pipeline.coalesceStream.numberOfTracks++;
  7260. pipeline.videoSegmentStream = new VideoSegmentStream(videoTrack, options);
  7261.  
  7262. pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo) {
  7263. // When video emits timelineStartInfo data after a flush, we forward that
  7264. // info to the AudioSegmentStream, if it exists, because video timeline
  7265. // data takes precedence.
  7266. if (audioTrack) {
  7267. audioTrack.timelineStartInfo = timelineStartInfo;
  7268. // On the first segment we trim AAC frames that exist before the
  7269. // very earliest DTS we have seen in video because Chrome will
  7270. // interpret any video track with a baseMediaDecodeTime that is
  7271. // non-zero as a gap.
  7272. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts);
  7273. }
  7274. });
  7275.  
  7276. pipeline.videoSegmentStream.on('processedGopsInfo',
  7277. self.trigger.bind(self, 'gopInfo'));
  7278. pipeline.videoSegmentStream.on('segmentTimingInfo',
  7279. self.trigger.bind(self, 'videoSegmentTimingInfo'));
  7280.  
  7281. pipeline.videoSegmentStream.on('baseMediaDecodeTime', function(baseMediaDecodeTime) {
  7282. if (audioTrack) {
  7283. pipeline.audioSegmentStream.setVideoBaseMediaDecodeTime(baseMediaDecodeTime);
  7284. }
  7285. });
  7286.  
  7287. pipeline.videoSegmentStream.on('timingInfo',
  7288. self.trigger.bind(self, 'videoTimingInfo'));
  7289.  
  7290. // Set up the final part of the video pipeline
  7291. pipeline.h264Stream
  7292. .pipe(pipeline.videoSegmentStream)
  7293. .pipe(pipeline.coalesceStream);
  7294. }
  7295.  
  7296. if (audioTrack && !pipeline.audioSegmentStream) {
  7297. // hook up the audio segment stream to the first track with aac data
  7298. pipeline.coalesceStream.numberOfTracks++;
  7299. pipeline.audioSegmentStream = new AudioSegmentStream(audioTrack, options);
  7300.  
  7301. pipeline.audioSegmentStream.on('timingInfo',
  7302. self.trigger.bind(self, 'audioTimingInfo'));
  7303.  
  7304. // Set up the final part of the audio pipeline
  7305. pipeline.adtsStream
  7306. .pipe(pipeline.audioSegmentStream)
  7307. .pipe(pipeline.coalesceStream);
  7308. }
  7309.  
  7310. // emit pmt info
  7311. self.trigger('trackinfo', {
  7312. hasAudio: !!audioTrack,
  7313. hasVideo: !!videoTrack
  7314. });
  7315. }
  7316. });
  7317.  
  7318. // Re-emit any data coming from the coalesce stream to the outside world
  7319. pipeline.coalesceStream.on('data', this.trigger.bind(this, 'data'));
  7320. pipeline.coalesceStream.on('id3Frame', function(id3Frame) {
  7321. id3Frame.dispatchType = pipeline.metadataStream.dispatchType;
  7322.  
  7323. self.trigger('id3Frame', id3Frame);
  7324. });
  7325. pipeline.coalesceStream.on('caption', this.trigger.bind(this, 'caption'));
  7326. // Let the consumer know we have finished flushing the entire pipeline
  7327. pipeline.coalesceStream.on('done', this.trigger.bind(this, 'done'));
  7328. };
  7329.  
  7330. // hook up the segment streams once track metadata is delivered
  7331. this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  7332. var pipeline = this.transmuxPipeline_;
  7333.  
  7334. if (!options.keepOriginalTimestamps) {
  7335. this.baseMediaDecodeTime = baseMediaDecodeTime;
  7336. }
  7337.  
  7338. if (audioTrack) {
  7339. audioTrack.timelineStartInfo.dts = undefined;
  7340. audioTrack.timelineStartInfo.pts = undefined;
  7341. trackDecodeInfo.clearDtsInfo(audioTrack);
  7342. if (!options.keepOriginalTimestamps) {
  7343. audioTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  7344. }
  7345. if (pipeline.audioTimestampRolloverStream) {
  7346. pipeline.audioTimestampRolloverStream.discontinuity();
  7347. }
  7348. }
  7349. if (videoTrack) {
  7350. if (pipeline.videoSegmentStream) {
  7351. pipeline.videoSegmentStream.gopCache_ = [];
  7352. pipeline.videoTimestampRolloverStream.discontinuity();
  7353. }
  7354. videoTrack.timelineStartInfo.dts = undefined;
  7355. videoTrack.timelineStartInfo.pts = undefined;
  7356. trackDecodeInfo.clearDtsInfo(videoTrack);
  7357. pipeline.captionStream.reset();
  7358. if (!options.keepOriginalTimestamps) {
  7359. videoTrack.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  7360. }
  7361. }
  7362.  
  7363. if (pipeline.timedMetadataTimestampRolloverStream) {
  7364. pipeline.timedMetadataTimestampRolloverStream.discontinuity();
  7365. }
  7366. };
  7367.  
  7368. this.setAudioAppendStart = function(timestamp) {
  7369. if (audioTrack) {
  7370. this.transmuxPipeline_.audioSegmentStream.setAudioAppendStart(timestamp);
  7371. }
  7372. };
  7373.  
  7374. this.alignGopsWith = function(gopsToAlignWith) {
  7375. if (videoTrack && this.transmuxPipeline_.videoSegmentStream) {
  7376. this.transmuxPipeline_.videoSegmentStream.alignGopsWith(gopsToAlignWith);
  7377. }
  7378. };
  7379.  
  7380. // feed incoming data to the front of the parsing pipeline
  7381. this.push = function(data) {
  7382. if (hasFlushed) {
  7383. var isAac = isLikelyAacData(data);
  7384.  
  7385. if (isAac && this.transmuxPipeline_.type !== 'aac') {
  7386. this.setupAacPipeline();
  7387. } else if (!isAac && this.transmuxPipeline_.type !== 'ts') {
  7388. this.setupTsPipeline();
  7389. }
  7390. hasFlushed = false;
  7391. }
  7392. this.transmuxPipeline_.headOfPipeline.push(data);
  7393. };
  7394.  
  7395. // flush any buffered data
  7396. this.flush = function() {
  7397. hasFlushed = true;
  7398. // Start at the top of the pipeline and flush all pending work
  7399. this.transmuxPipeline_.headOfPipeline.flush();
  7400. };
  7401.  
  7402. this.endTimeline = function() {
  7403. this.transmuxPipeline_.headOfPipeline.endTimeline();
  7404. };
  7405.  
  7406. this.reset = function() {
  7407. if (this.transmuxPipeline_.headOfPipeline) {
  7408. this.transmuxPipeline_.headOfPipeline.reset();
  7409. }
  7410. };
  7411.  
  7412. // Caption data has to be reset when seeking outside buffered range
  7413. this.resetCaptions = function() {
  7414. if (this.transmuxPipeline_.captionStream) {
  7415. this.transmuxPipeline_.captionStream.reset();
  7416. }
  7417. };
  7418.  
  7419. };
  7420. Transmuxer.prototype = new Stream();
  7421.  
  7422. module.exports = {
  7423. Transmuxer: Transmuxer,
  7424. VideoSegmentStream: VideoSegmentStream,
  7425. AudioSegmentStream: AudioSegmentStream,
  7426. AUDIO_PROPERTIES: AUDIO_PROPERTIES,
  7427. VIDEO_PROPERTIES: VIDEO_PROPERTIES,
  7428. // exported for testing
  7429. generateVideoSegmentTimingInfo: generateVideoSegmentTimingInfo
  7430. };
  7431.  
  7432. },{"1":1,"16":16,"2":2,"21":21,"23":23,"25":25,"27":27,"3":3,"38":38,"4":4,"40":40}],29:[function(require,module,exports){
  7433. 'use strict';
  7434.  
  7435. var Stream = require(40);
  7436. var mp4 = require(25);
  7437. var audioFrameUtils = require(21);
  7438. var trackInfo = require(27);
  7439.  
  7440. // constants
  7441. var AUDIO_PROPERTIES = [
  7442. 'audioobjecttype',
  7443. 'channelcount',
  7444. 'samplerate',
  7445. 'samplingfrequencyindex',
  7446. 'samplesize'
  7447. ];
  7448.  
  7449. var ONE_SECOND_IN_TS = 90000; // 90kHz clock
  7450.  
  7451. /**
  7452. * Constructs a single-track, ISO BMFF media segment from AAC data
  7453. * events. The output of this stream can be fed to a SourceBuffer
  7454. * configured with a suitable initialization segment.
  7455. */
  7456. var AudioSegmentStream = function(track, options) {
  7457. var
  7458. adtsFrames = [],
  7459. sequenceNumber = 0,
  7460. earliestAllowedDts = 0,
  7461. audioAppendStartTs = 0,
  7462. videoBaseMediaDecodeTime = Infinity,
  7463. segmentStartDts = null,
  7464. segmentEndDts = null;
  7465.  
  7466. options = options || {};
  7467.  
  7468. AudioSegmentStream.prototype.init.call(this);
  7469.  
  7470. this.push = function(data) {
  7471. trackInfo.collectDtsInfo(track, data);
  7472.  
  7473. if (track) {
  7474. AUDIO_PROPERTIES.forEach(function(prop) {
  7475. track[prop] = data[prop];
  7476. });
  7477. }
  7478.  
  7479. // buffer audio data until end() is called
  7480. adtsFrames.push(data);
  7481. };
  7482.  
  7483. this.setEarliestDts = function(earliestDts) {
  7484. earliestAllowedDts = earliestDts;
  7485. };
  7486.  
  7487. this.setVideoBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  7488. videoBaseMediaDecodeTime = baseMediaDecodeTime;
  7489. };
  7490.  
  7491. this.setAudioAppendStart = function(timestamp) {
  7492. audioAppendStartTs = timestamp;
  7493. };
  7494.  
  7495. this.processFrames_ = function() {
  7496. var
  7497. frames,
  7498. moof,
  7499. mdat,
  7500. boxes,
  7501. timingInfo;
  7502.  
  7503. // return early if no audio data has been observed
  7504. if (adtsFrames.length === 0) {
  7505. return;
  7506. }
  7507.  
  7508. frames = audioFrameUtils.trimAdtsFramesByEarliestDts(
  7509. adtsFrames, track, earliestAllowedDts);
  7510. if (frames.length === 0) {
  7511. // return early if the frames are all after the earliest allowed DTS
  7512. // TODO should we clear the adtsFrames?
  7513. return;
  7514. }
  7515.  
  7516. track.baseMediaDecodeTime = trackInfo.calculateTrackBaseMediaDecodeTime(
  7517. track, options.keepOriginalTimestamps);
  7518.  
  7519. audioFrameUtils.prefixWithSilence(
  7520. track, frames, audioAppendStartTs, videoBaseMediaDecodeTime);
  7521.  
  7522. // we have to build the index from byte locations to
  7523. // samples (that is, adts frames) in the audio data
  7524. track.samples = audioFrameUtils.generateSampleTable(frames);
  7525.  
  7526. // concatenate the audio data to constuct the mdat
  7527. mdat = mp4.mdat(audioFrameUtils.concatenateFrameData(frames));
  7528.  
  7529. adtsFrames = [];
  7530.  
  7531. moof = mp4.moof(sequenceNumber, [track]);
  7532.  
  7533. // bump the sequence number for next time
  7534. sequenceNumber++;
  7535.  
  7536. track.initSegment = mp4.initSegment([track]);
  7537.  
  7538. // it would be great to allocate this array up front instead of
  7539. // throwing away hundreds of media segment fragments
  7540. boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  7541.  
  7542. boxes.set(moof);
  7543. boxes.set(mdat, moof.byteLength);
  7544.  
  7545. trackInfo.clearDtsInfo(track);
  7546.  
  7547. if (segmentStartDts === null) {
  7548. segmentEndDts = segmentStartDts = frames[0].dts;
  7549. }
  7550.  
  7551. segmentEndDts += frames.length * (ONE_SECOND_IN_TS * 1024 / track.samplerate);
  7552.  
  7553. timingInfo = { start: segmentStartDts };
  7554.  
  7555. this.trigger('timingInfo', timingInfo);
  7556. this.trigger('data', {track: track, boxes: boxes});
  7557. };
  7558.  
  7559. this.flush = function() {
  7560. this.processFrames_();
  7561. // trigger final timing info
  7562. this.trigger('timingInfo', {
  7563. start: segmentStartDts,
  7564. end: segmentEndDts
  7565. });
  7566. this.resetTiming_();
  7567. this.trigger('done', 'AudioSegmentStream');
  7568. };
  7569.  
  7570. this.partialFlush = function() {
  7571. this.processFrames_();
  7572. this.trigger('partialdone', 'AudioSegmentStream');
  7573. };
  7574.  
  7575. this.endTimeline = function() {
  7576. this.flush();
  7577. this.trigger('endedtimeline', 'AudioSegmentStream');
  7578. };
  7579.  
  7580. this.resetTiming_ = function() {
  7581. trackInfo.clearDtsInfo(track);
  7582. segmentStartDts = null;
  7583. segmentEndDts = null;
  7584. };
  7585.  
  7586. this.reset = function() {
  7587. this.resetTiming_();
  7588. adtsFrames = [];
  7589. this.trigger('reset');
  7590. };
  7591. };
  7592.  
  7593. AudioSegmentStream.prototype = new Stream();
  7594.  
  7595. module.exports = AudioSegmentStream;
  7596.  
  7597. },{"21":21,"25":25,"27":27,"40":40}],30:[function(require,module,exports){
  7598. module.exports = {
  7599. Transmuxer: require(31)
  7600. };
  7601.  
  7602. },{"31":31}],31:[function(require,module,exports){
  7603. var Stream = require(40);
  7604. var m2ts = require(16);
  7605. var codecs = require(5);
  7606. var AudioSegmentStream = require(29);
  7607. var VideoSegmentStream = require(32);
  7608. var trackInfo = require(27);
  7609. var isLikelyAacData = require(2).isLikelyAacData;
  7610. var AdtsStream = require(3);
  7611. var AacStream = require(1);
  7612. var clock = require(38);
  7613.  
  7614. var createPipeline = function(object) {
  7615. object.prototype = new Stream();
  7616. object.prototype.init.call(object);
  7617.  
  7618. return object;
  7619. };
  7620.  
  7621. var tsPipeline = function(options) {
  7622. var
  7623. pipeline = {
  7624. type: 'ts',
  7625. tracks: {
  7626. audio: null,
  7627. video: null
  7628. },
  7629. packet: new m2ts.TransportPacketStream(),
  7630. parse: new m2ts.TransportParseStream(),
  7631. elementary: new m2ts.ElementaryStream(),
  7632. videoRollover: new m2ts.TimestampRolloverStream('video'),
  7633. audioRollover: new m2ts.TimestampRolloverStream('audio'),
  7634. adts: new codecs.Adts(),
  7635. h264: new codecs.h264.H264Stream(),
  7636. captionStream: new m2ts.CaptionStream(),
  7637. metadataStream: new m2ts.MetadataStream(),
  7638. timedMetadataRollover: new m2ts.TimestampRolloverStream('timed-metadata')
  7639. };
  7640.  
  7641. pipeline.headOfPipeline = pipeline.packet;
  7642.  
  7643. // Transport Stream
  7644. pipeline.packet
  7645. .pipe(pipeline.parse)
  7646. .pipe(pipeline.elementary);
  7647.  
  7648. // H264
  7649. pipeline.elementary
  7650. .pipe(pipeline.videoRollover)
  7651. .pipe(pipeline.h264);
  7652.  
  7653. // Hook up CEA-608/708 caption stream
  7654. pipeline.h264
  7655. .pipe(pipeline.captionStream);
  7656.  
  7657. pipeline.elementary
  7658. .pipe(pipeline.timedMetadataRollover)
  7659. .pipe(pipeline.metadataStream);
  7660.  
  7661. // ADTS
  7662. pipeline.elementary
  7663. .pipe(pipeline.audioRollover)
  7664. .pipe(pipeline.adts);
  7665.  
  7666. pipeline.elementary.on('data', function(data) {
  7667. if (data.type !== 'metadata') {
  7668. return;
  7669. }
  7670.  
  7671. for (var i = 0; i < data.tracks.length; i++) {
  7672. if (!pipeline.tracks[data.tracks[i].type]) {
  7673. pipeline.tracks[data.tracks[i].type] = data.tracks[i];
  7674. }
  7675. }
  7676.  
  7677. if (pipeline.tracks.video && !pipeline.videoSegmentStream) {
  7678. pipeline.videoSegmentStream = new VideoSegmentStream(pipeline.tracks.video, options);
  7679.  
  7680. pipeline.videoSegmentStream.on('timelineStartInfo', function(timelineStartInfo) {
  7681. if (pipeline.tracks.audio) {
  7682. pipeline.audioSegmentStream.setEarliestDts(timelineStartInfo.dts);
  7683. }
  7684. });
  7685.  
  7686. pipeline.videoSegmentStream.on('timingInfo',
  7687. pipeline.trigger.bind(pipeline, 'videoTimingInfo'));
  7688.  
  7689. pipeline.videoSegmentStream.on('data', function(data) {
  7690. pipeline.trigger('data', {
  7691. type: 'video',
  7692. data: data
  7693. });
  7694. });
  7695.  
  7696. pipeline.videoSegmentStream.on('done',
  7697. pipeline.trigger.bind(pipeline, 'done'));
  7698. pipeline.videoSegmentStream.on('partialdone',
  7699. pipeline.trigger.bind(pipeline, 'partialdone'));
  7700. pipeline.videoSegmentStream.on('endedtimeline',
  7701. pipeline.trigger.bind(pipeline, 'endedtimeline'));
  7702.  
  7703. pipeline.h264
  7704. .pipe(pipeline.videoSegmentStream);
  7705. }
  7706.  
  7707. if (pipeline.tracks.audio && !pipeline.audioSegmentStream) {
  7708. pipeline.audioSegmentStream = new AudioSegmentStream(pipeline.tracks.audio, options);
  7709.  
  7710. pipeline.audioSegmentStream.on('data', function(data) {
  7711. pipeline.trigger('data', {
  7712. type: 'audio',
  7713. data: data
  7714. });
  7715. });
  7716.  
  7717. pipeline.audioSegmentStream.on('done',
  7718. pipeline.trigger.bind(pipeline, 'done'));
  7719. pipeline.audioSegmentStream.on('partialdone',
  7720. pipeline.trigger.bind(pipeline, 'partialdone'));
  7721. pipeline.audioSegmentStream.on('endedtimeline',
  7722. pipeline.trigger.bind(pipeline, 'endedtimeline'));
  7723.  
  7724. pipeline.audioSegmentStream.on('timingInfo',
  7725. pipeline.trigger.bind(pipeline, 'audioTimingInfo'));
  7726.  
  7727. pipeline.adts
  7728. .pipe(pipeline.audioSegmentStream);
  7729. }
  7730.  
  7731. // emit pmt info
  7732. pipeline.trigger('trackinfo', {
  7733. hasAudio: !!pipeline.tracks.audio,
  7734. hasVideo: !!pipeline.tracks.video
  7735. });
  7736. });
  7737.  
  7738. pipeline.captionStream.on('data', function(caption) {
  7739. var timelineStartPts;
  7740.  
  7741. if (pipeline.tracks.video) {
  7742. timelineStartPts = pipeline.tracks.video.timelineStartInfo.pts || 0;
  7743. } else {
  7744. // This will only happen if we encounter caption packets before
  7745. // video data in a segment. This is an unusual/unlikely scenario,
  7746. // so we assume the timeline starts at zero for now.
  7747. timelineStartPts = 0;
  7748. }
  7749.  
  7750. // Translate caption PTS times into second offsets into the
  7751. // video timeline for the segment
  7752. caption.startTime = clock.metadataTsToSeconds(caption.startPts, timelineStartPts, options.keepOriginalTimestamps);
  7753. caption.endTime = clock.metadataTsToSeconds(caption.endPts, timelineStartPts, options.keepOriginalTimestamps);
  7754.  
  7755. pipeline.trigger('caption', caption);
  7756. });
  7757.  
  7758. pipeline = createPipeline(pipeline);
  7759.  
  7760. pipeline.metadataStream.on('data', pipeline.trigger.bind(pipeline, 'id3Frame'));
  7761.  
  7762. return pipeline;
  7763. };
  7764.  
  7765. var aacPipeline = function(options) {
  7766. var
  7767. pipeline = {
  7768. type: 'aac',
  7769. tracks: {
  7770. audio: {
  7771. timelineStartInfo: {
  7772. baseMediaDecodeTime: options.baseMediaDecodeTime
  7773. }
  7774. }
  7775. },
  7776. metadataStream: new m2ts.MetadataStream(),
  7777. aacStream: new AacStream(),
  7778. audioRollover: new m2ts.TimestampRolloverStream('audio'),
  7779. timedMetadataRollover: new m2ts.TimestampRolloverStream('timed-metadata'),
  7780. adtsStream: new AdtsStream(true)
  7781. };
  7782.  
  7783. // set up the parsing pipeline
  7784. pipeline.headOfPipeline = pipeline.aacStream;
  7785.  
  7786. pipeline.aacStream
  7787. .pipe(pipeline.audioRollover)
  7788. .pipe(pipeline.adtsStream);
  7789. pipeline.aacStream
  7790. .pipe(pipeline.timedMetadataRollover)
  7791. .pipe(pipeline.metadataStream);
  7792.  
  7793. pipeline.metadataStream.on('timestamp', function(frame) {
  7794. pipeline.aacStream.setTimestamp(frame.timeStamp);
  7795. });
  7796.  
  7797. pipeline.aacStream.on('data', function(data) {
  7798. if (data.type !== 'timed-metadata' || pipeline.audioSegmentStream) {
  7799. return;
  7800. }
  7801.  
  7802. pipeline.tracks.audio = {
  7803. timelineStartInfo: {
  7804. baseMediaDecodeTime: pipeline.tracks.audio.timelineStartInfo.baseMediaDecodeTime
  7805. },
  7806. codec: 'adts',
  7807. type: 'audio'
  7808. };
  7809.  
  7810. // hook up the audio segment stream to the first track with aac data
  7811. pipeline.audioSegmentStream = new AudioSegmentStream(pipeline.tracks.audio, options);
  7812.  
  7813. pipeline.audioSegmentStream.on('timingInfo',
  7814. pipeline.trigger.bind(pipeline, 'audioTimingInfo'));
  7815.  
  7816. // Set up the final part of the audio pipeline
  7817. pipeline.adtsStream
  7818. .pipe(pipeline.audioSegmentStream);
  7819.  
  7820. pipeline.audioSegmentStream.on('data', function(data) {
  7821. pipeline.trigger('data', {
  7822. type: 'audio',
  7823. data: data
  7824. });
  7825. });
  7826. pipeline.audioSegmentStream.on('partialdone',
  7827. pipeline.trigger.bind(pipeline, 'partialdone'));
  7828. pipeline.audioSegmentStream.on('done', pipeline.trigger.bind(pipeline, 'done'));
  7829. pipeline.audioSegmentStream.on('endedtimeline',
  7830. pipeline.trigger.bind(pipeline, 'endedtimeline'));
  7831. pipeline.audioSegmentStream.on('timingInfo',
  7832. pipeline.trigger.bind(pipeline, 'audioTimingInfo'));
  7833.  
  7834. });
  7835.  
  7836. // set the pipeline up as a stream before binding to get access to the trigger function
  7837. pipeline = createPipeline(pipeline);
  7838.  
  7839. pipeline.metadataStream.on('data', pipeline.trigger.bind(pipeline, 'id3Frame'));
  7840.  
  7841. return pipeline;
  7842. };
  7843.  
  7844. var setupPipelineListeners = function(pipeline, transmuxer) {
  7845. pipeline.on('data', transmuxer.trigger.bind(transmuxer, 'data'));
  7846. pipeline.on('done', transmuxer.trigger.bind(transmuxer, 'done'));
  7847. pipeline.on('partialdone', transmuxer.trigger.bind(transmuxer, 'partialdone'));
  7848. pipeline.on('endedtimeline', transmuxer.trigger.bind(transmuxer, 'endedtimeline'));
  7849. pipeline.on('audioTimingInfo', transmuxer.trigger.bind(transmuxer, 'audioTimingInfo'));
  7850. pipeline.on('videoTimingInfo', transmuxer.trigger.bind(transmuxer, 'videoTimingInfo'));
  7851. pipeline.on('trackinfo', transmuxer.trigger.bind(transmuxer, 'trackinfo'));
  7852. pipeline.on('id3Frame', function(event) {
  7853. // add this to every single emitted segment even though it's only needed for the first
  7854. event.dispatchType = pipeline.metadataStream.dispatchType;
  7855. // keep original time, can be adjusted if needed at a higher level
  7856. event.cueTime = clock.videoTsToSeconds(event.pts);
  7857.  
  7858. transmuxer.trigger('id3Frame', event);
  7859. });
  7860. pipeline.on('caption', function(event) {
  7861. transmuxer.trigger('caption', event);
  7862. });
  7863. };
  7864.  
  7865. var Transmuxer = function(options) {
  7866. var
  7867. pipeline = null,
  7868. hasFlushed = true;
  7869.  
  7870. Transmuxer.prototype.init.call(this);
  7871.  
  7872. this.push = function(bytes) {
  7873. if (hasFlushed) {
  7874. var isAac = isLikelyAacData(bytes);
  7875.  
  7876. if (isAac && (!pipeline || pipeline.type !== 'aac')) {
  7877. pipeline = aacPipeline(options);
  7878. setupPipelineListeners(pipeline, this);
  7879. } else if (!isAac && (!pipeline || pipeline.type !== 'ts')) {
  7880. pipeline = tsPipeline(options);
  7881. setupPipelineListeners(pipeline, this);
  7882. }
  7883. hasFlushed = false;
  7884. }
  7885.  
  7886. pipeline.headOfPipeline.push(bytes);
  7887. };
  7888.  
  7889. this.flush = function() {
  7890. if (!pipeline) {
  7891. return;
  7892. }
  7893.  
  7894. hasFlushed = true;
  7895. pipeline.headOfPipeline.flush();
  7896. };
  7897.  
  7898. this.partialFlush = function() {
  7899. if (!pipeline) {
  7900. return;
  7901. }
  7902.  
  7903. pipeline.headOfPipeline.partialFlush();
  7904. };
  7905.  
  7906. this.endTimeline = function() {
  7907. if (!pipeline) {
  7908. return;
  7909. }
  7910.  
  7911. pipeline.headOfPipeline.endTimeline();
  7912. };
  7913.  
  7914. this.reset = function() {
  7915. if (!pipeline) {
  7916. return;
  7917. }
  7918.  
  7919. pipeline.headOfPipeline.reset();
  7920. };
  7921.  
  7922. this.setBaseMediaDecodeTime = function(baseMediaDecodeTime) {
  7923. if (!options.keepOriginalTimestamps) {
  7924. options.baseMediaDecodeTime = baseMediaDecodeTime;
  7925. }
  7926.  
  7927. if (!pipeline) {
  7928. return;
  7929. }
  7930.  
  7931. if (pipeline.tracks.audio) {
  7932. pipeline.tracks.audio.timelineStartInfo.dts = undefined;
  7933. pipeline.tracks.audio.timelineStartInfo.pts = undefined;
  7934. trackInfo.clearDtsInfo(pipeline.tracks.audio);
  7935. if (!options.keepOriginalTimestamps) {
  7936. pipeline.tracks.audio.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  7937. }
  7938. if (pipeline.audioRollover) {
  7939. pipeline.audioRollover.discontinuity();
  7940. }
  7941. }
  7942. if (pipeline.tracks.video) {
  7943. if (pipeline.videoSegmentStream) {
  7944. pipeline.videoSegmentStream.gopCache_ = [];
  7945. pipeline.videoRollover.discontinuity();
  7946. }
  7947. pipeline.tracks.video.timelineStartInfo.dts = undefined;
  7948. pipeline.tracks.video.timelineStartInfo.pts = undefined;
  7949. trackInfo.clearDtsInfo(pipeline.tracks.video);
  7950. // pipeline.captionStream.reset();
  7951. if (!options.keepOriginalTimestamps) {
  7952. pipeline.tracks.video.timelineStartInfo.baseMediaDecodeTime = baseMediaDecodeTime;
  7953. }
  7954. }
  7955. };
  7956.  
  7957. this.setAudioAppendStart = function(audioAppendStart) {
  7958. if (!pipeline || !pipeline.tracks.audio || !pipeline.audioSegmentStream) {
  7959. return;
  7960. }
  7961.  
  7962. pipeline.audioSegmentStream.setAudioAppendStart(audioAppendStart);
  7963. };
  7964.  
  7965. // TODO GOP alignment support
  7966. // Support may be a bit trickier than with full segment appends, as GOPs may be split
  7967. // and processed in a more granular fashion
  7968. this.alignGopsWith = function(gopsToAlignWith) {
  7969. return;
  7970. };
  7971. };
  7972.  
  7973. Transmuxer.prototype = new Stream();
  7974.  
  7975. module.exports = Transmuxer;
  7976.  
  7977. },{"1":1,"16":16,"2":2,"27":27,"29":29,"3":3,"32":32,"38":38,"40":40,"5":5}],32:[function(require,module,exports){
  7978. /**
  7979. * Constructs a single-track, ISO BMFF media segment from H264 data
  7980. * events. The output of this stream can be fed to a SourceBuffer
  7981. * configured with a suitable initialization segment.
  7982. * @param track {object} track metadata configuration
  7983. * @param options {object} transmuxer options object
  7984. * @param options.alignGopsAtEnd {boolean} If true, start from the end of the
  7985. * gopsToAlignWith list when attempting to align gop pts
  7986. */
  7987. 'use strict';
  7988.  
  7989. var Stream = require(40);
  7990. var mp4 = require(25);
  7991. var trackInfo = require(27);
  7992. var frameUtils = require(23);
  7993.  
  7994. var VIDEO_PROPERTIES = [
  7995. 'width',
  7996. 'height',
  7997. 'profileIdc',
  7998. 'levelIdc',
  7999. 'profileCompatibility'
  8000. ];
  8001.  
  8002. var VideoSegmentStream = function(track, options) {
  8003. var
  8004. sequenceNumber = 0,
  8005. nalUnits = [],
  8006. frameCache = [],
  8007. // gopsToAlignWith = [],
  8008. config,
  8009. pps,
  8010. segmentStartDts = null,
  8011. segmentEndDts = null,
  8012. gops,
  8013. ensureNextFrameIsKeyFrame = true;
  8014.  
  8015. options = options || {};
  8016.  
  8017. VideoSegmentStream.prototype.init.call(this);
  8018.  
  8019. this.push = function(nalUnit) {
  8020. trackInfo.collectDtsInfo(track, nalUnit);
  8021. if (typeof track.timelineStartInfo.dts === 'undefined') {
  8022. track.timelineStartInfo.dts = nalUnit.dts;
  8023. }
  8024.  
  8025. // record the track config
  8026. if (nalUnit.nalUnitType === 'seq_parameter_set_rbsp' && !config) {
  8027. config = nalUnit.config;
  8028. track.sps = [nalUnit.data];
  8029.  
  8030. VIDEO_PROPERTIES.forEach(function(prop) {
  8031. track[prop] = config[prop];
  8032. }, this);
  8033. }
  8034.  
  8035. if (nalUnit.nalUnitType === 'pic_parameter_set_rbsp' &&
  8036. !pps) {
  8037. pps = nalUnit.data;
  8038. track.pps = [nalUnit.data];
  8039. }
  8040.  
  8041. // buffer video until flush() is called
  8042. nalUnits.push(nalUnit);
  8043. };
  8044.  
  8045. this.processNals_ = function(cacheLastFrame) {
  8046. var i;
  8047.  
  8048. nalUnits = frameCache.concat(nalUnits);
  8049.  
  8050. // Throw away nalUnits at the start of the byte stream until
  8051. // we find the first AUD
  8052. while (nalUnits.length) {
  8053. if (nalUnits[0].nalUnitType === 'access_unit_delimiter_rbsp') {
  8054. break;
  8055. }
  8056. nalUnits.shift();
  8057. }
  8058.  
  8059. // Return early if no video data has been observed
  8060. if (nalUnits.length === 0) {
  8061. return;
  8062. }
  8063.  
  8064. var frames = frameUtils.groupNalsIntoFrames(nalUnits);
  8065.  
  8066. if (!frames.length) {
  8067. return;
  8068. }
  8069.  
  8070. // note that the frame cache may also protect us from cases where we haven't
  8071. // pushed data for the entire first or last frame yet
  8072. frameCache = frames[frames.length - 1];
  8073.  
  8074. if (cacheLastFrame) {
  8075. frames.pop();
  8076. frames.duration -= frameCache.duration;
  8077. frames.nalCount -= frameCache.length;
  8078. frames.byteLength -= frameCache.byteLength;
  8079. }
  8080.  
  8081. if (!frames.length) {
  8082. nalUnits = [];
  8083. return;
  8084. }
  8085.  
  8086. this.trigger('timelineStartInfo', track.timelineStartInfo);
  8087.  
  8088. if (ensureNextFrameIsKeyFrame) {
  8089. gops = frameUtils.groupFramesIntoGops(frames);
  8090.  
  8091. if (!gops[0][0].keyFrame) {
  8092. gops = frameUtils.extendFirstKeyFrame(gops);
  8093.  
  8094. if (!gops[0][0].keyFrame) {
  8095. // we haven't yet gotten a key frame, so reset nal units to wait for more nal
  8096. // units
  8097. nalUnits = ([].concat.apply([], frames)).concat(frameCache);
  8098. frameCache = [];
  8099. return;
  8100. }
  8101.  
  8102. frames = [].concat.apply([], gops);
  8103. frames.duration = gops.duration;
  8104. }
  8105. ensureNextFrameIsKeyFrame = false;
  8106. }
  8107.  
  8108. if (segmentStartDts === null) {
  8109. segmentStartDts = frames[0].dts;
  8110. segmentEndDts = segmentStartDts;
  8111. }
  8112.  
  8113. segmentEndDts += frames.duration;
  8114.  
  8115. this.trigger('timingInfo', {
  8116. start: segmentStartDts,
  8117. end: segmentEndDts
  8118. });
  8119.  
  8120. for (i = 0; i < frames.length; i++) {
  8121. var frame = frames[i];
  8122.  
  8123. track.samples = frameUtils.generateSampleTableForFrame(frame);
  8124.  
  8125. var mdat = mp4.mdat(frameUtils.concatenateNalDataForFrame(frame));
  8126.  
  8127. trackInfo.clearDtsInfo(track);
  8128. trackInfo.collectDtsInfo(track, frame);
  8129.  
  8130. track.baseMediaDecodeTime = trackInfo.calculateTrackBaseMediaDecodeTime(
  8131. track, options.keepOriginalTimestamps);
  8132.  
  8133. var moof = mp4.moof(sequenceNumber, [track]);
  8134.  
  8135. sequenceNumber++;
  8136.  
  8137. track.initSegment = mp4.initSegment([track]);
  8138.  
  8139. var boxes = new Uint8Array(moof.byteLength + mdat.byteLength);
  8140.  
  8141. boxes.set(moof);
  8142. boxes.set(mdat, moof.byteLength);
  8143.  
  8144. this.trigger('data', {
  8145. track: track,
  8146. boxes: boxes,
  8147. sequence: sequenceNumber,
  8148. videoFrameDts: frame.dts
  8149. });
  8150. }
  8151.  
  8152. nalUnits = [];
  8153. };
  8154.  
  8155. this.resetTimingAndConfig_ = function() {
  8156. config = undefined;
  8157. pps = undefined;
  8158. segmentStartDts = null;
  8159. segmentEndDts = null;
  8160. };
  8161.  
  8162. this.partialFlush = function() {
  8163. this.processNals_(true);
  8164. this.trigger('partialdone', 'VideoSegmentStream');
  8165. };
  8166.  
  8167. this.flush = function() {
  8168. this.processNals_(false);
  8169. // reset config and pps because they may differ across segments
  8170. // for instance, when we are rendition switching
  8171. this.resetTimingAndConfig_();
  8172. this.trigger('done', 'VideoSegmentStream');
  8173. };
  8174.  
  8175. this.endTimeline = function() {
  8176. this.flush();
  8177. this.trigger('endedtimeline', 'VideoSegmentStream');
  8178. };
  8179.  
  8180. this.reset = function() {
  8181. this.resetTimingAndConfig_();
  8182. frameCache = [];
  8183. nalUnits = [];
  8184. ensureNextFrameIsKeyFrame = true;
  8185. this.trigger('reset');
  8186. };
  8187. };
  8188.  
  8189. VideoSegmentStream.prototype = new Stream();
  8190.  
  8191. module.exports = VideoSegmentStream;
  8192.  
  8193. },{"23":23,"25":25,"27":27,"40":40}],33:[function(require,module,exports){
  8194. /**
  8195. * mux.js
  8196. *
  8197. * Copyright (c) Brightcove
  8198. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8199. *
  8200. * Reads in-band caption information from a video elementary
  8201. * stream. Captions must follow the CEA-708 standard for injection
  8202. * into an MPEG-2 transport streams.
  8203. * @see https://en.wikipedia.org/wiki/CEA-708
  8204. * @see https://www.gpo.gov/fdsys/pkg/CFR-2007-title47-vol1/pdf/CFR-2007-title47-vol1-sec15-119.pdf
  8205. */
  8206.  
  8207. 'use strict';
  8208.  
  8209. // Supplemental enhancement information (SEI) NAL units have a
  8210. // payload type field to indicate how they are to be
  8211. // interpreted. CEAS-708 caption content is always transmitted with
  8212. // payload type 0x04.
  8213. var USER_DATA_REGISTERED_ITU_T_T35 = 4,
  8214. RBSP_TRAILING_BITS = 128;
  8215.  
  8216. /**
  8217. * Parse a supplemental enhancement information (SEI) NAL unit.
  8218. * Stops parsing once a message of type ITU T T35 has been found.
  8219. *
  8220. * @param bytes {Uint8Array} the bytes of a SEI NAL unit
  8221. * @return {object} the parsed SEI payload
  8222. * @see Rec. ITU-T H.264, 7.3.2.3.1
  8223. */
  8224. var parseSei = function(bytes) {
  8225. var
  8226. i = 0,
  8227. result = {
  8228. payloadType: -1,
  8229. payloadSize: 0
  8230. },
  8231. payloadType = 0,
  8232. payloadSize = 0;
  8233.  
  8234. // go through the sei_rbsp parsing each each individual sei_message
  8235. while (i < bytes.byteLength) {
  8236. // stop once we have hit the end of the sei_rbsp
  8237. if (bytes[i] === RBSP_TRAILING_BITS) {
  8238. break;
  8239. }
  8240.  
  8241. // Parse payload type
  8242. while (bytes[i] === 0xFF) {
  8243. payloadType += 255;
  8244. i++;
  8245. }
  8246. payloadType += bytes[i++];
  8247.  
  8248. // Parse payload size
  8249. while (bytes[i] === 0xFF) {
  8250. payloadSize += 255;
  8251. i++;
  8252. }
  8253. payloadSize += bytes[i++];
  8254.  
  8255. // this sei_message is a 608/708 caption so save it and break
  8256. // there can only ever be one caption message in a frame's sei
  8257. if (!result.payload && payloadType === USER_DATA_REGISTERED_ITU_T_T35) {
  8258. result.payloadType = payloadType;
  8259. result.payloadSize = payloadSize;
  8260. result.payload = bytes.subarray(i, i + payloadSize);
  8261. break;
  8262. }
  8263.  
  8264. // skip the payload and parse the next message
  8265. i += payloadSize;
  8266. payloadType = 0;
  8267. payloadSize = 0;
  8268. }
  8269.  
  8270. return result;
  8271. };
  8272.  
  8273. // see ANSI/SCTE 128-1 (2013), section 8.1
  8274. var parseUserData = function(sei) {
  8275. // itu_t_t35_contry_code must be 181 (United States) for
  8276. // captions
  8277. if (sei.payload[0] !== 181) {
  8278. return null;
  8279. }
  8280.  
  8281. // itu_t_t35_provider_code should be 49 (ATSC) for captions
  8282. if (((sei.payload[1] << 8) | sei.payload[2]) !== 49) {
  8283. return null;
  8284. }
  8285.  
  8286. // the user_identifier should be "GA94" to indicate ATSC1 data
  8287. if (String.fromCharCode(sei.payload[3],
  8288. sei.payload[4],
  8289. sei.payload[5],
  8290. sei.payload[6]) !== 'GA94') {
  8291. return null;
  8292. }
  8293.  
  8294. // finally, user_data_type_code should be 0x03 for caption data
  8295. if (sei.payload[7] !== 0x03) {
  8296. return null;
  8297. }
  8298.  
  8299. // return the user_data_type_structure and strip the trailing
  8300. // marker bits
  8301. return sei.payload.subarray(8, sei.payload.length - 1);
  8302. };
  8303.  
  8304. // see CEA-708-D, section 4.4
  8305. var parseCaptionPackets = function(pts, userData) {
  8306. var results = [], i, count, offset, data;
  8307.  
  8308. // if this is just filler, return immediately
  8309. if (!(userData[0] & 0x40)) {
  8310. return results;
  8311. }
  8312.  
  8313. // parse out the cc_data_1 and cc_data_2 fields
  8314. count = userData[0] & 0x1f;
  8315. for (i = 0; i < count; i++) {
  8316. offset = i * 3;
  8317. data = {
  8318. type: userData[offset + 2] & 0x03,
  8319. pts: pts
  8320. };
  8321.  
  8322. // capture cc data when cc_valid is 1
  8323. if (userData[offset + 2] & 0x04) {
  8324. data.ccData = (userData[offset + 3] << 8) | userData[offset + 4];
  8325. results.push(data);
  8326. }
  8327. }
  8328. return results;
  8329. };
  8330.  
  8331. var discardEmulationPreventionBytes = function(data) {
  8332. var
  8333. length = data.byteLength,
  8334. emulationPreventionBytesPositions = [],
  8335. i = 1,
  8336. newLength, newData;
  8337.  
  8338. // Find all `Emulation Prevention Bytes`
  8339. while (i < length - 2) {
  8340. if (data[i] === 0 && data[i + 1] === 0 && data[i + 2] === 0x03) {
  8341. emulationPreventionBytesPositions.push(i + 2);
  8342. i += 2;
  8343. } else {
  8344. i++;
  8345. }
  8346. }
  8347.  
  8348. // If no Emulation Prevention Bytes were found just return the original
  8349. // array
  8350. if (emulationPreventionBytesPositions.length === 0) {
  8351. return data;
  8352. }
  8353.  
  8354. // Create a new array to hold the NAL unit data
  8355. newLength = length - emulationPreventionBytesPositions.length;
  8356. newData = new Uint8Array(newLength);
  8357. var sourceIndex = 0;
  8358.  
  8359. for (i = 0; i < newLength; sourceIndex++, i++) {
  8360. if (sourceIndex === emulationPreventionBytesPositions[0]) {
  8361. // Skip this byte
  8362. sourceIndex++;
  8363. // Remove this position index
  8364. emulationPreventionBytesPositions.shift();
  8365. }
  8366. newData[i] = data[sourceIndex];
  8367. }
  8368.  
  8369. return newData;
  8370. };
  8371.  
  8372. // exports
  8373. module.exports = {
  8374. parseSei: parseSei,
  8375. parseUserData: parseUserData,
  8376. parseCaptionPackets: parseCaptionPackets,
  8377. discardEmulationPreventionBytes: discardEmulationPreventionBytes,
  8378. USER_DATA_REGISTERED_ITU_T_T35: USER_DATA_REGISTERED_ITU_T_T35
  8379. };
  8380.  
  8381. },{}],34:[function(require,module,exports){
  8382. /**
  8383. * mux.js
  8384. *
  8385. * Copyright (c) Brightcove
  8386. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8387. */
  8388. 'use strict';
  8389.  
  8390. var
  8391. tagTypes = {
  8392. 0x08: 'audio',
  8393. 0x09: 'video',
  8394. 0x12: 'metadata'
  8395. },
  8396. hex = function(val) {
  8397. return '0x' + ('00' + val.toString(16)).slice(-2).toUpperCase();
  8398. },
  8399. hexStringList = function(data) {
  8400. var arr = [], i;
  8401.  
  8402. while (data.byteLength > 0) {
  8403. i = 0;
  8404. arr.push(hex(data[i++]));
  8405. data = data.subarray(i);
  8406. }
  8407. return arr.join(' ');
  8408. },
  8409. parseAVCTag = function(tag, obj) {
  8410. var
  8411. avcPacketTypes = [
  8412. 'AVC Sequence Header',
  8413. 'AVC NALU',
  8414. 'AVC End-of-Sequence'
  8415. ],
  8416. compositionTime = (tag[1] & parseInt('01111111', 2) << 16) | (tag[2] << 8) | tag[3];
  8417.  
  8418. obj = obj || {};
  8419.  
  8420. obj.avcPacketType = avcPacketTypes[tag[0]];
  8421. obj.CompositionTime = (tag[1] & parseInt('10000000', 2)) ? -compositionTime : compositionTime;
  8422.  
  8423. if (tag[0] === 1) {
  8424. obj.nalUnitTypeRaw = hexStringList(tag.subarray(4, 100));
  8425. } else {
  8426. obj.data = hexStringList(tag.subarray(4));
  8427. }
  8428.  
  8429. return obj;
  8430. },
  8431. parseVideoTag = function(tag, obj) {
  8432. var
  8433. frameTypes = [
  8434. 'Unknown',
  8435. 'Keyframe (for AVC, a seekable frame)',
  8436. 'Inter frame (for AVC, a nonseekable frame)',
  8437. 'Disposable inter frame (H.263 only)',
  8438. 'Generated keyframe (reserved for server use only)',
  8439. 'Video info/command frame'
  8440. ],
  8441. codecID = tag[0] & parseInt('00001111', 2);
  8442.  
  8443. obj = obj || {};
  8444.  
  8445. obj.frameType = frameTypes[(tag[0] & parseInt('11110000', 2)) >>> 4];
  8446. obj.codecID = codecID;
  8447.  
  8448. if (codecID === 7) {
  8449. return parseAVCTag(tag.subarray(1), obj);
  8450. }
  8451. return obj;
  8452. },
  8453. parseAACTag = function(tag, obj) {
  8454. var packetTypes = [
  8455. 'AAC Sequence Header',
  8456. 'AAC Raw'
  8457. ];
  8458.  
  8459. obj = obj || {};
  8460.  
  8461. obj.aacPacketType = packetTypes[tag[0]];
  8462. obj.data = hexStringList(tag.subarray(1));
  8463.  
  8464. return obj;
  8465. },
  8466. parseAudioTag = function(tag, obj) {
  8467. var
  8468. formatTable = [
  8469. 'Linear PCM, platform endian',
  8470. 'ADPCM',
  8471. 'MP3',
  8472. 'Linear PCM, little endian',
  8473. 'Nellymoser 16-kHz mono',
  8474. 'Nellymoser 8-kHz mono',
  8475. 'Nellymoser',
  8476. 'G.711 A-law logarithmic PCM',
  8477. 'G.711 mu-law logarithmic PCM',
  8478. 'reserved',
  8479. 'AAC',
  8480. 'Speex',
  8481. 'MP3 8-Khz',
  8482. 'Device-specific sound'
  8483. ],
  8484. samplingRateTable = [
  8485. '5.5-kHz',
  8486. '11-kHz',
  8487. '22-kHz',
  8488. '44-kHz'
  8489. ],
  8490. soundFormat = (tag[0] & parseInt('11110000', 2)) >>> 4;
  8491.  
  8492. obj = obj || {};
  8493.  
  8494. obj.soundFormat = formatTable[soundFormat];
  8495. obj.soundRate = samplingRateTable[(tag[0] & parseInt('00001100', 2)) >>> 2];
  8496. obj.soundSize = ((tag[0] & parseInt('00000010', 2)) >>> 1) ? '16-bit' : '8-bit';
  8497. obj.soundType = (tag[0] & parseInt('00000001', 2)) ? 'Stereo' : 'Mono';
  8498.  
  8499. if (soundFormat === 10) {
  8500. return parseAACTag(tag.subarray(1), obj);
  8501. }
  8502. return obj;
  8503. },
  8504. parseGenericTag = function(tag) {
  8505. return {
  8506. tagType: tagTypes[tag[0]],
  8507. dataSize: (tag[1] << 16) | (tag[2] << 8) | tag[3],
  8508. timestamp: (tag[7] << 24) | (tag[4] << 16) | (tag[5] << 8) | tag[6],
  8509. streamID: (tag[8] << 16) | (tag[9] << 8) | tag[10]
  8510. };
  8511. },
  8512. inspectFlvTag = function(tag) {
  8513. var header = parseGenericTag(tag);
  8514. switch (tag[0]) {
  8515. case 0x08:
  8516. parseAudioTag(tag.subarray(11), header);
  8517. break;
  8518. case 0x09:
  8519. parseVideoTag(tag.subarray(11), header);
  8520. break;
  8521. case 0x12:
  8522. }
  8523. return header;
  8524. },
  8525. inspectFlv = function(bytes) {
  8526. var i = 9, // header
  8527. dataSize,
  8528. parsedResults = [],
  8529. tag;
  8530.  
  8531. // traverse the tags
  8532. i += 4; // skip previous tag size
  8533. while (i < bytes.byteLength) {
  8534. dataSize = bytes[i + 1] << 16;
  8535. dataSize |= bytes[i + 2] << 8;
  8536. dataSize |= bytes[i + 3];
  8537. dataSize += 11;
  8538.  
  8539. tag = bytes.subarray(i, i + dataSize);
  8540. parsedResults.push(inspectFlvTag(tag));
  8541. i += dataSize + 4;
  8542. }
  8543. return parsedResults;
  8544. },
  8545. textifyFlv = function(flvTagArray) {
  8546. return JSON.stringify(flvTagArray, null, 2);
  8547. };
  8548.  
  8549. module.exports = {
  8550. inspectTag: inspectFlvTag,
  8551. inspect: inspectFlv,
  8552. textify: textifyFlv
  8553. };
  8554.  
  8555. },{}],35:[function(require,module,exports){
  8556. /**
  8557. * mux.js
  8558. *
  8559. * Copyright (c) Brightcove
  8560. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  8561. *
  8562. * Parse the internal MP4 structure into an equivalent javascript
  8563. * object.
  8564. */
  8565. 'use strict';
  8566.  
  8567. var
  8568. inspectMp4,
  8569. textifyMp4,
  8570.  
  8571. parseType = require(26).parseType,
  8572. parseMp4Date = function(seconds) {
  8573. return new Date(seconds * 1000 - 2082844800000);
  8574. },
  8575. parseSampleFlags = function(flags) {
  8576. return {
  8577. isLeading: (flags[0] & 0x0c) >>> 2,
  8578. dependsOn: flags[0] & 0x03,
  8579. isDependedOn: (flags[1] & 0xc0) >>> 6,
  8580. hasRedundancy: (flags[1] & 0x30) >>> 4,
  8581. paddingValue: (flags[1] & 0x0e) >>> 1,
  8582. isNonSyncSample: flags[1] & 0x01,
  8583. degradationPriority: (flags[2] << 8) | flags[3]
  8584. };
  8585. },
  8586. nalParse = function(avcStream) {
  8587. var
  8588. avcView = new DataView(avcStream.buffer, avcStream.byteOffset, avcStream.byteLength),
  8589. result = [],
  8590. i,
  8591. length;
  8592. for (i = 0; i + 4 < avcStream.length; i += length) {
  8593. length = avcView.getUint32(i);
  8594. i += 4;
  8595.  
  8596. // bail if this doesn't appear to be an H264 stream
  8597. if (length <= 0) {
  8598. result.push('<span style=\'color:red;\'>MALFORMED DATA</span>');
  8599. continue;
  8600. }
  8601.  
  8602. switch (avcStream[i] & 0x1F) {
  8603. case 0x01:
  8604. result.push('slice_layer_without_partitioning_rbsp');
  8605. break;
  8606. case 0x05:
  8607. result.push('slice_layer_without_partitioning_rbsp_idr');
  8608. break;
  8609. case 0x06:
  8610. result.push('sei_rbsp');
  8611. break;
  8612. case 0x07:
  8613. result.push('seq_parameter_set_rbsp');
  8614. break;
  8615. case 0x08:
  8616. result.push('pic_parameter_set_rbsp');
  8617. break;
  8618. case 0x09:
  8619. result.push('access_unit_delimiter_rbsp');
  8620. break;
  8621. default:
  8622. result.push('UNKNOWN NAL - ' + avcStream[i] & 0x1F);
  8623. break;
  8624. }
  8625. }
  8626. return result;
  8627. },
  8628.  
  8629. // registry of handlers for individual mp4 box types
  8630. parse = {
  8631. // codingname, not a first-class box type. stsd entries share the
  8632. // same format as real boxes so the parsing infrastructure can be
  8633. // shared
  8634. avc1: function(data) {
  8635. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  8636. return {
  8637. dataReferenceIndex: view.getUint16(6),
  8638. width: view.getUint16(24),
  8639. height: view.getUint16(26),
  8640. horizresolution: view.getUint16(28) + (view.getUint16(30) / 16),
  8641. vertresolution: view.getUint16(32) + (view.getUint16(34) / 16),
  8642. frameCount: view.getUint16(40),
  8643. depth: view.getUint16(74),
  8644. config: inspectMp4(data.subarray(78, data.byteLength))
  8645. };
  8646. },
  8647. avcC: function(data) {
  8648. var
  8649. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8650. result = {
  8651. configurationVersion: data[0],
  8652. avcProfileIndication: data[1],
  8653. profileCompatibility: data[2],
  8654. avcLevelIndication: data[3],
  8655. lengthSizeMinusOne: data[4] & 0x03,
  8656. sps: [],
  8657. pps: []
  8658. },
  8659. numOfSequenceParameterSets = data[5] & 0x1f,
  8660. numOfPictureParameterSets,
  8661. nalSize,
  8662. offset,
  8663. i;
  8664.  
  8665. // iterate past any SPSs
  8666. offset = 6;
  8667. for (i = 0; i < numOfSequenceParameterSets; i++) {
  8668. nalSize = view.getUint16(offset);
  8669. offset += 2;
  8670. result.sps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
  8671. offset += nalSize;
  8672. }
  8673. // iterate past any PPSs
  8674. numOfPictureParameterSets = data[offset];
  8675. offset++;
  8676. for (i = 0; i < numOfPictureParameterSets; i++) {
  8677. nalSize = view.getUint16(offset);
  8678. offset += 2;
  8679. result.pps.push(new Uint8Array(data.subarray(offset, offset + nalSize)));
  8680. offset += nalSize;
  8681. }
  8682. return result;
  8683. },
  8684. btrt: function(data) {
  8685. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  8686. return {
  8687. bufferSizeDB: view.getUint32(0),
  8688. maxBitrate: view.getUint32(4),
  8689. avgBitrate: view.getUint32(8)
  8690. };
  8691. },
  8692. esds: function(data) {
  8693. return {
  8694. version: data[0],
  8695. flags: new Uint8Array(data.subarray(1, 4)),
  8696. esId: (data[6] << 8) | data[7],
  8697. streamPriority: data[8] & 0x1f,
  8698. decoderConfig: {
  8699. objectProfileIndication: data[11],
  8700. streamType: (data[12] >>> 2) & 0x3f,
  8701. bufferSize: (data[13] << 16) | (data[14] << 8) | data[15],
  8702. maxBitrate: (data[16] << 24) |
  8703. (data[17] << 16) |
  8704. (data[18] << 8) |
  8705. data[19],
  8706. avgBitrate: (data[20] << 24) |
  8707. (data[21] << 16) |
  8708. (data[22] << 8) |
  8709. data[23],
  8710. decoderConfigDescriptor: {
  8711. tag: data[24],
  8712. length: data[25],
  8713. audioObjectType: (data[26] >>> 3) & 0x1f,
  8714. samplingFrequencyIndex: ((data[26] & 0x07) << 1) |
  8715. ((data[27] >>> 7) & 0x01),
  8716. channelConfiguration: (data[27] >>> 3) & 0x0f
  8717. }
  8718. }
  8719. };
  8720. },
  8721. ftyp: function(data) {
  8722. var
  8723. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8724. result = {
  8725. majorBrand: parseType(data.subarray(0, 4)),
  8726. minorVersion: view.getUint32(4),
  8727. compatibleBrands: []
  8728. },
  8729. i = 8;
  8730. while (i < data.byteLength) {
  8731. result.compatibleBrands.push(parseType(data.subarray(i, i + 4)));
  8732. i += 4;
  8733. }
  8734. return result;
  8735. },
  8736. dinf: function(data) {
  8737. return {
  8738. boxes: inspectMp4(data)
  8739. };
  8740. },
  8741. dref: function(data) {
  8742. return {
  8743. version: data[0],
  8744. flags: new Uint8Array(data.subarray(1, 4)),
  8745. dataReferences: inspectMp4(data.subarray(8))
  8746. };
  8747. },
  8748. hdlr: function(data) {
  8749. var
  8750. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8751. result = {
  8752. version: view.getUint8(0),
  8753. flags: new Uint8Array(data.subarray(1, 4)),
  8754. handlerType: parseType(data.subarray(8, 12)),
  8755. name: ''
  8756. },
  8757. i = 8;
  8758.  
  8759. // parse out the name field
  8760. for (i = 24; i < data.byteLength; i++) {
  8761. if (data[i] === 0x00) {
  8762. // the name field is null-terminated
  8763. i++;
  8764. break;
  8765. }
  8766. result.name += String.fromCharCode(data[i]);
  8767. }
  8768. // decode UTF-8 to javascript's internal representation
  8769. // see http://ecmanaut.blogspot.com/2006/07/encoding-decoding-utf8-in-javascript.html
  8770. result.name = decodeURIComponent(escape(result.name));
  8771.  
  8772. return result;
  8773. },
  8774. mdat: function(data) {
  8775. return {
  8776. byteLength: data.byteLength,
  8777. nals: nalParse(data)
  8778. };
  8779. },
  8780. mdhd: function(data) {
  8781. var
  8782. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8783. i = 4,
  8784. language,
  8785. result = {
  8786. version: view.getUint8(0),
  8787. flags: new Uint8Array(data.subarray(1, 4)),
  8788. language: ''
  8789. };
  8790. if (result.version === 1) {
  8791. i += 4;
  8792. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  8793. i += 8;
  8794. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  8795. i += 4;
  8796. result.timescale = view.getUint32(i);
  8797. i += 8;
  8798. result.duration = view.getUint32(i); // truncating top 4 bytes
  8799. } else {
  8800. result.creationTime = parseMp4Date(view.getUint32(i));
  8801. i += 4;
  8802. result.modificationTime = parseMp4Date(view.getUint32(i));
  8803. i += 4;
  8804. result.timescale = view.getUint32(i);
  8805. i += 4;
  8806. result.duration = view.getUint32(i);
  8807. }
  8808. i += 4;
  8809. // language is stored as an ISO-639-2/T code in an array of three 5-bit fields
  8810. // each field is the packed difference between its ASCII value and 0x60
  8811. language = view.getUint16(i);
  8812. result.language += String.fromCharCode((language >> 10) + 0x60);
  8813. result.language += String.fromCharCode(((language & 0x03e0) >> 5) + 0x60);
  8814. result.language += String.fromCharCode((language & 0x1f) + 0x60);
  8815.  
  8816. return result;
  8817. },
  8818. mdia: function(data) {
  8819. return {
  8820. boxes: inspectMp4(data)
  8821. };
  8822. },
  8823. mfhd: function(data) {
  8824. return {
  8825. version: data[0],
  8826. flags: new Uint8Array(data.subarray(1, 4)),
  8827. sequenceNumber: (data[4] << 24) |
  8828. (data[5] << 16) |
  8829. (data[6] << 8) |
  8830. (data[7])
  8831. };
  8832. },
  8833. minf: function(data) {
  8834. return {
  8835. boxes: inspectMp4(data)
  8836. };
  8837. },
  8838. // codingname, not a first-class box type. stsd entries share the
  8839. // same format as real boxes so the parsing infrastructure can be
  8840. // shared
  8841. mp4a: function(data) {
  8842. var
  8843. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8844. result = {
  8845. // 6 bytes reserved
  8846. dataReferenceIndex: view.getUint16(6),
  8847. // 4 + 4 bytes reserved
  8848. channelcount: view.getUint16(16),
  8849. samplesize: view.getUint16(18),
  8850. // 2 bytes pre_defined
  8851. // 2 bytes reserved
  8852. samplerate: view.getUint16(24) + (view.getUint16(26) / 65536)
  8853. };
  8854.  
  8855. // if there are more bytes to process, assume this is an ISO/IEC
  8856. // 14496-14 MP4AudioSampleEntry and parse the ESDBox
  8857. if (data.byteLength > 28) {
  8858. result.streamDescriptor = inspectMp4(data.subarray(28))[0];
  8859. }
  8860. return result;
  8861. },
  8862. moof: function(data) {
  8863. return {
  8864. boxes: inspectMp4(data)
  8865. };
  8866. },
  8867. moov: function(data) {
  8868. return {
  8869. boxes: inspectMp4(data)
  8870. };
  8871. },
  8872. mvex: function(data) {
  8873. return {
  8874. boxes: inspectMp4(data)
  8875. };
  8876. },
  8877. mvhd: function(data) {
  8878. var
  8879. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8880. i = 4,
  8881. result = {
  8882. version: view.getUint8(0),
  8883. flags: new Uint8Array(data.subarray(1, 4))
  8884. };
  8885.  
  8886. if (result.version === 1) {
  8887. i += 4;
  8888. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  8889. i += 8;
  8890. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  8891. i += 4;
  8892. result.timescale = view.getUint32(i);
  8893. i += 8;
  8894. result.duration = view.getUint32(i); // truncating top 4 bytes
  8895. } else {
  8896. result.creationTime = parseMp4Date(view.getUint32(i));
  8897. i += 4;
  8898. result.modificationTime = parseMp4Date(view.getUint32(i));
  8899. i += 4;
  8900. result.timescale = view.getUint32(i);
  8901. i += 4;
  8902. result.duration = view.getUint32(i);
  8903. }
  8904. i += 4;
  8905.  
  8906. // convert fixed-point, base 16 back to a number
  8907. result.rate = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  8908. i += 4;
  8909. result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
  8910. i += 2;
  8911. i += 2;
  8912. i += 2 * 4;
  8913. result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
  8914. i += 9 * 4;
  8915. i += 6 * 4;
  8916. result.nextTrackId = view.getUint32(i);
  8917. return result;
  8918. },
  8919. pdin: function(data) {
  8920. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  8921. return {
  8922. version: view.getUint8(0),
  8923. flags: new Uint8Array(data.subarray(1, 4)),
  8924. rate: view.getUint32(4),
  8925. initialDelay: view.getUint32(8)
  8926. };
  8927. },
  8928. sdtp: function(data) {
  8929. var
  8930. result = {
  8931. version: data[0],
  8932. flags: new Uint8Array(data.subarray(1, 4)),
  8933. samples: []
  8934. }, i;
  8935.  
  8936. for (i = 4; i < data.byteLength; i++) {
  8937. result.samples.push({
  8938. dependsOn: (data[i] & 0x30) >> 4,
  8939. isDependedOn: (data[i] & 0x0c) >> 2,
  8940. hasRedundancy: data[i] & 0x03
  8941. });
  8942. }
  8943. return result;
  8944. },
  8945. sidx: function(data) {
  8946. var view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8947. result = {
  8948. version: data[0],
  8949. flags: new Uint8Array(data.subarray(1, 4)),
  8950. references: [],
  8951. referenceId: view.getUint32(4),
  8952. timescale: view.getUint32(8),
  8953. earliestPresentationTime: view.getUint32(12),
  8954. firstOffset: view.getUint32(16)
  8955. },
  8956. referenceCount = view.getUint16(22),
  8957. i;
  8958.  
  8959. for (i = 24; referenceCount; i += 12, referenceCount--) {
  8960. result.references.push({
  8961. referenceType: (data[i] & 0x80) >>> 7,
  8962. referencedSize: view.getUint32(i) & 0x7FFFFFFF,
  8963. subsegmentDuration: view.getUint32(i + 4),
  8964. startsWithSap: !!(data[i + 8] & 0x80),
  8965. sapType: (data[i + 8] & 0x70) >>> 4,
  8966. sapDeltaTime: view.getUint32(i + 8) & 0x0FFFFFFF
  8967. });
  8968. }
  8969.  
  8970. return result;
  8971. },
  8972. smhd: function(data) {
  8973. return {
  8974. version: data[0],
  8975. flags: new Uint8Array(data.subarray(1, 4)),
  8976. balance: data[4] + (data[5] / 256)
  8977. };
  8978. },
  8979. stbl: function(data) {
  8980. return {
  8981. boxes: inspectMp4(data)
  8982. };
  8983. },
  8984. stco: function(data) {
  8985. var
  8986. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  8987. result = {
  8988. version: data[0],
  8989. flags: new Uint8Array(data.subarray(1, 4)),
  8990. chunkOffsets: []
  8991. },
  8992. entryCount = view.getUint32(4),
  8993. i;
  8994. for (i = 8; entryCount; i += 4, entryCount--) {
  8995. result.chunkOffsets.push(view.getUint32(i));
  8996. }
  8997. return result;
  8998. },
  8999. stsc: function(data) {
  9000. var
  9001. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9002. entryCount = view.getUint32(4),
  9003. result = {
  9004. version: data[0],
  9005. flags: new Uint8Array(data.subarray(1, 4)),
  9006. sampleToChunks: []
  9007. },
  9008. i;
  9009. for (i = 8; entryCount; i += 12, entryCount--) {
  9010. result.sampleToChunks.push({
  9011. firstChunk: view.getUint32(i),
  9012. samplesPerChunk: view.getUint32(i + 4),
  9013. sampleDescriptionIndex: view.getUint32(i + 8)
  9014. });
  9015. }
  9016. return result;
  9017. },
  9018. stsd: function(data) {
  9019. return {
  9020. version: data[0],
  9021. flags: new Uint8Array(data.subarray(1, 4)),
  9022. sampleDescriptions: inspectMp4(data.subarray(8))
  9023. };
  9024. },
  9025. stsz: function(data) {
  9026. var
  9027. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9028. result = {
  9029. version: data[0],
  9030. flags: new Uint8Array(data.subarray(1, 4)),
  9031. sampleSize: view.getUint32(4),
  9032. entries: []
  9033. },
  9034. i;
  9035. for (i = 12; i < data.byteLength; i += 4) {
  9036. result.entries.push(view.getUint32(i));
  9037. }
  9038. return result;
  9039. },
  9040. stts: function(data) {
  9041. var
  9042. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9043. result = {
  9044. version: data[0],
  9045. flags: new Uint8Array(data.subarray(1, 4)),
  9046. timeToSamples: []
  9047. },
  9048. entryCount = view.getUint32(4),
  9049. i;
  9050.  
  9051. for (i = 8; entryCount; i += 8, entryCount--) {
  9052. result.timeToSamples.push({
  9053. sampleCount: view.getUint32(i),
  9054. sampleDelta: view.getUint32(i + 4)
  9055. });
  9056. }
  9057. return result;
  9058. },
  9059. styp: function(data) {
  9060. return parse.ftyp(data);
  9061. },
  9062. tfdt: function(data) {
  9063. var result = {
  9064. version: data[0],
  9065. flags: new Uint8Array(data.subarray(1, 4)),
  9066. baseMediaDecodeTime: data[4] << 24 | data[5] << 16 | data[6] << 8 | data[7]
  9067. };
  9068. if (result.version === 1) {
  9069. result.baseMediaDecodeTime *= Math.pow(2, 32);
  9070. result.baseMediaDecodeTime += data[8] << 24 | data[9] << 16 | data[10] << 8 | data[11];
  9071. }
  9072. return result;
  9073. },
  9074. tfhd: function(data) {
  9075. var
  9076. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9077. result = {
  9078. version: data[0],
  9079. flags: new Uint8Array(data.subarray(1, 4)),
  9080. trackId: view.getUint32(4)
  9081. },
  9082. baseDataOffsetPresent = result.flags[2] & 0x01,
  9083. sampleDescriptionIndexPresent = result.flags[2] & 0x02,
  9084. defaultSampleDurationPresent = result.flags[2] & 0x08,
  9085. defaultSampleSizePresent = result.flags[2] & 0x10,
  9086. defaultSampleFlagsPresent = result.flags[2] & 0x20,
  9087. durationIsEmpty = result.flags[0] & 0x010000,
  9088. defaultBaseIsMoof = result.flags[0] & 0x020000,
  9089. i;
  9090.  
  9091. i = 8;
  9092. if (baseDataOffsetPresent) {
  9093. i += 4; // truncate top 4 bytes
  9094. // FIXME: should we read the full 64 bits?
  9095. result.baseDataOffset = view.getUint32(12);
  9096. i += 4;
  9097. }
  9098. if (sampleDescriptionIndexPresent) {
  9099. result.sampleDescriptionIndex = view.getUint32(i);
  9100. i += 4;
  9101. }
  9102. if (defaultSampleDurationPresent) {
  9103. result.defaultSampleDuration = view.getUint32(i);
  9104. i += 4;
  9105. }
  9106. if (defaultSampleSizePresent) {
  9107. result.defaultSampleSize = view.getUint32(i);
  9108. i += 4;
  9109. }
  9110. if (defaultSampleFlagsPresent) {
  9111. result.defaultSampleFlags = view.getUint32(i);
  9112. }
  9113. if (durationIsEmpty) {
  9114. result.durationIsEmpty = true;
  9115. }
  9116. if (!baseDataOffsetPresent && defaultBaseIsMoof) {
  9117. result.baseDataOffsetIsMoof = true;
  9118. }
  9119. return result;
  9120. },
  9121. tkhd: function(data) {
  9122. var
  9123. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9124. i = 4,
  9125. result = {
  9126. version: view.getUint8(0),
  9127. flags: new Uint8Array(data.subarray(1, 4))
  9128. };
  9129. if (result.version === 1) {
  9130. i += 4;
  9131. result.creationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  9132. i += 8;
  9133. result.modificationTime = parseMp4Date(view.getUint32(i)); // truncating top 4 bytes
  9134. i += 4;
  9135. result.trackId = view.getUint32(i);
  9136. i += 4;
  9137. i += 8;
  9138. result.duration = view.getUint32(i); // truncating top 4 bytes
  9139. } else {
  9140. result.creationTime = parseMp4Date(view.getUint32(i));
  9141. i += 4;
  9142. result.modificationTime = parseMp4Date(view.getUint32(i));
  9143. i += 4;
  9144. result.trackId = view.getUint32(i);
  9145. i += 4;
  9146. i += 4;
  9147. result.duration = view.getUint32(i);
  9148. }
  9149. i += 4;
  9150. i += 2 * 4;
  9151. result.layer = view.getUint16(i);
  9152. i += 2;
  9153. result.alternateGroup = view.getUint16(i);
  9154. i += 2;
  9155. // convert fixed-point, base 16 back to a number
  9156. result.volume = view.getUint8(i) + (view.getUint8(i + 1) / 8);
  9157. i += 2;
  9158. i += 2;
  9159. result.matrix = new Uint32Array(data.subarray(i, i + (9 * 4)));
  9160. i += 9 * 4;
  9161. result.width = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  9162. i += 4;
  9163. result.height = view.getUint16(i) + (view.getUint16(i + 2) / 16);
  9164. return result;
  9165. },
  9166. traf: function(data) {
  9167. return {
  9168. boxes: inspectMp4(data)
  9169. };
  9170. },
  9171. trak: function(data) {
  9172. return {
  9173. boxes: inspectMp4(data)
  9174. };
  9175. },
  9176. trex: function(data) {
  9177. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  9178. return {
  9179. version: data[0],
  9180. flags: new Uint8Array(data.subarray(1, 4)),
  9181. trackId: view.getUint32(4),
  9182. defaultSampleDescriptionIndex: view.getUint32(8),
  9183. defaultSampleDuration: view.getUint32(12),
  9184. defaultSampleSize: view.getUint32(16),
  9185. sampleDependsOn: data[20] & 0x03,
  9186. sampleIsDependedOn: (data[21] & 0xc0) >> 6,
  9187. sampleHasRedundancy: (data[21] & 0x30) >> 4,
  9188. samplePaddingValue: (data[21] & 0x0e) >> 1,
  9189. sampleIsDifferenceSample: !!(data[21] & 0x01),
  9190. sampleDegradationPriority: view.getUint16(22)
  9191. };
  9192. },
  9193. trun: function(data) {
  9194. var
  9195. result = {
  9196. version: data[0],
  9197. flags: new Uint8Array(data.subarray(1, 4)),
  9198. samples: []
  9199. },
  9200. view = new DataView(data.buffer, data.byteOffset, data.byteLength),
  9201. // Flag interpretation
  9202. dataOffsetPresent = result.flags[2] & 0x01, // compare with 2nd byte of 0x1
  9203. firstSampleFlagsPresent = result.flags[2] & 0x04, // compare with 2nd byte of 0x4
  9204. sampleDurationPresent = result.flags[1] & 0x01, // compare with 2nd byte of 0x100
  9205. sampleSizePresent = result.flags[1] & 0x02, // compare with 2nd byte of 0x200
  9206. sampleFlagsPresent = result.flags[1] & 0x04, // compare with 2nd byte of 0x400
  9207. sampleCompositionTimeOffsetPresent = result.flags[1] & 0x08, // compare with 2nd byte of 0x800
  9208. sampleCount = view.getUint32(4),
  9209. offset = 8,
  9210. sample;
  9211.  
  9212. if (dataOffsetPresent) {
  9213. // 32 bit signed integer
  9214. result.dataOffset = view.getInt32(offset);
  9215. offset += 4;
  9216. }
  9217.  
  9218. // Overrides the flags for the first sample only. The order of
  9219. // optional values will be: duration, size, compositionTimeOffset
  9220. if (firstSampleFlagsPresent && sampleCount) {
  9221. sample = {
  9222. flags: parseSampleFlags(data.subarray(offset, offset + 4))
  9223. };
  9224. offset += 4;
  9225. if (sampleDurationPresent) {
  9226. sample.duration = view.getUint32(offset);
  9227. offset += 4;
  9228. }
  9229. if (sampleSizePresent) {
  9230. sample.size = view.getUint32(offset);
  9231. offset += 4;
  9232. }
  9233. if (sampleCompositionTimeOffsetPresent) {
  9234. // Note: this should be a signed int if version is 1
  9235. sample.compositionTimeOffset = view.getUint32(offset);
  9236. offset += 4;
  9237. }
  9238. result.samples.push(sample);
  9239. sampleCount--;
  9240. }
  9241.  
  9242. while (sampleCount--) {
  9243. sample = {};
  9244. if (sampleDurationPresent) {
  9245. sample.duration = view.getUint32(offset);
  9246. offset += 4;
  9247. }
  9248. if (sampleSizePresent) {
  9249. sample.size = view.getUint32(offset);
  9250. offset += 4;
  9251. }
  9252. if (sampleFlagsPresent) {
  9253. sample.flags = parseSampleFlags(data.subarray(offset, offset + 4));
  9254. offset += 4;
  9255. }
  9256. if (sampleCompositionTimeOffsetPresent) {
  9257. // Note: this should be a signed int if version is 1
  9258. sample.compositionTimeOffset = view.getUint32(offset);
  9259. offset += 4;
  9260. }
  9261. result.samples.push(sample);
  9262. }
  9263. return result;
  9264. },
  9265. 'url ': function(data) {
  9266. return {
  9267. version: data[0],
  9268. flags: new Uint8Array(data.subarray(1, 4))
  9269. };
  9270. },
  9271. vmhd: function(data) {
  9272. var view = new DataView(data.buffer, data.byteOffset, data.byteLength);
  9273. return {
  9274. version: data[0],
  9275. flags: new Uint8Array(data.subarray(1, 4)),
  9276. graphicsmode: view.getUint16(4),
  9277. opcolor: new Uint16Array([view.getUint16(6),
  9278. view.getUint16(8),
  9279. view.getUint16(10)])
  9280. };
  9281. }
  9282. };
  9283.  
  9284.  
  9285. /**
  9286. * Return a javascript array of box objects parsed from an ISO base
  9287. * media file.
  9288. * @param data {Uint8Array} the binary data of the media to be inspected
  9289. * @return {array} a javascript array of potentially nested box objects
  9290. */
  9291. inspectMp4 = function(data) {
  9292. var
  9293. i = 0,
  9294. result = [],
  9295. view,
  9296. size,
  9297. type,
  9298. end,
  9299. box;
  9300.  
  9301. // Convert data from Uint8Array to ArrayBuffer, to follow Dataview API
  9302. var ab = new ArrayBuffer(data.length);
  9303. var v = new Uint8Array(ab);
  9304. for (var z = 0; z < data.length; ++z) {
  9305. v[z] = data[z];
  9306. }
  9307. view = new DataView(ab);
  9308.  
  9309. while (i < data.byteLength) {
  9310. // parse box data
  9311. size = view.getUint32(i);
  9312. type = parseType(data.subarray(i + 4, i + 8));
  9313. end = size > 1 ? i + size : data.byteLength;
  9314.  
  9315. // parse type-specific data
  9316. box = (parse[type] || function(data) {
  9317. return {
  9318. data: data
  9319. };
  9320. })(data.subarray(i + 8, end));
  9321. box.size = size;
  9322. box.type = type;
  9323.  
  9324. // store this box and move to the next
  9325. result.push(box);
  9326. i = end;
  9327. }
  9328. return result;
  9329. };
  9330.  
  9331. /**
  9332. * Returns a textual representation of the javascript represtentation
  9333. * of an MP4 file. You can use it as an alternative to
  9334. * JSON.stringify() to compare inspected MP4s.
  9335. * @param inspectedMp4 {array} the parsed array of boxes in an MP4
  9336. * file
  9337. * @param depth {number} (optional) the number of ancestor boxes of
  9338. * the elements of inspectedMp4. Assumed to be zero if unspecified.
  9339. * @return {string} a text representation of the parsed MP4
  9340. */
  9341. textifyMp4 = function(inspectedMp4, depth) {
  9342. var indent;
  9343. depth = depth || 0;
  9344. indent = new Array(depth * 2 + 1).join(' ');
  9345.  
  9346. // iterate over all the boxes
  9347. return inspectedMp4.map(function(box, index) {
  9348.  
  9349. // list the box type first at the current indentation level
  9350. return indent + box.type + '\n' +
  9351.  
  9352. // the type is already included and handle child boxes separately
  9353. Object.keys(box).filter(function(key) {
  9354. return key !== 'type' && key !== 'boxes';
  9355.  
  9356. // output all the box properties
  9357. }).map(function(key) {
  9358. var prefix = indent + ' ' + key + ': ',
  9359. value = box[key];
  9360.  
  9361. // print out raw bytes as hexademical
  9362. if (value instanceof Uint8Array || value instanceof Uint32Array) {
  9363. var bytes = Array.prototype.slice.call(new Uint8Array(value.buffer, value.byteOffset, value.byteLength))
  9364. .map(function(byte) {
  9365. return ' ' + ('00' + byte.toString(16)).slice(-2);
  9366. }).join('').match(/.{1,24}/g);
  9367. if (!bytes) {
  9368. return prefix + '<>';
  9369. }
  9370. if (bytes.length === 1) {
  9371. return prefix + '<' + bytes.join('').slice(1) + '>';
  9372. }
  9373. return prefix + '<\n' + bytes.map(function(line) {
  9374. return indent + ' ' + line;
  9375. }).join('\n') + '\n' + indent + ' >';
  9376. }
  9377.  
  9378. // stringify generic objects
  9379. return prefix +
  9380. JSON.stringify(value, null, 2)
  9381. .split('\n').map(function(line, index) {
  9382. if (index === 0) {
  9383. return line;
  9384. }
  9385. return indent + ' ' + line;
  9386. }).join('\n');
  9387. }).join('\n') +
  9388.  
  9389. // recursively textify the child boxes
  9390. (box.boxes ? '\n' + textifyMp4(box.boxes, depth + 1) : '');
  9391. }).join('\n');
  9392. };
  9393.  
  9394. module.exports = {
  9395. inspect: inspectMp4,
  9396. textify: textifyMp4,
  9397. parseTfdt: parse.tfdt,
  9398. parseHdlr: parse.hdlr,
  9399. parseTfhd: parse.tfhd,
  9400. parseTrun: parse.trun,
  9401. parseSidx: parse.sidx
  9402. };
  9403.  
  9404. },{"26":26}],36:[function(require,module,exports){
  9405. /**
  9406. * mux.js
  9407. *
  9408. * Copyright (c) Brightcove
  9409. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9410. *
  9411. * Parse mpeg2 transport stream packets to extract basic timing information
  9412. */
  9413. 'use strict';
  9414.  
  9415. var StreamTypes = require(19);
  9416. var handleRollover = require(20).handleRollover;
  9417. var probe = {};
  9418. probe.ts = require(18);
  9419. probe.aac = require(2);
  9420. var ONE_SECOND_IN_TS = require(38).ONE_SECOND_IN_TS;
  9421.  
  9422. var
  9423. MP2T_PACKET_LENGTH = 188, // bytes
  9424. SYNC_BYTE = 0x47;
  9425.  
  9426. /**
  9427. * walks through segment data looking for pat and pmt packets to parse out
  9428. * program map table information
  9429. */
  9430. var parsePsi_ = function(bytes, pmt) {
  9431. var
  9432. startIndex = 0,
  9433. endIndex = MP2T_PACKET_LENGTH,
  9434. packet, type;
  9435.  
  9436. while (endIndex < bytes.byteLength) {
  9437. // Look for a pair of start and end sync bytes in the data..
  9438. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  9439. // We found a packet
  9440. packet = bytes.subarray(startIndex, endIndex);
  9441. type = probe.ts.parseType(packet, pmt.pid);
  9442.  
  9443. switch (type) {
  9444. case 'pat':
  9445. if (!pmt.pid) {
  9446. pmt.pid = probe.ts.parsePat(packet);
  9447. }
  9448. break;
  9449. case 'pmt':
  9450. if (!pmt.table) {
  9451. pmt.table = probe.ts.parsePmt(packet);
  9452. }
  9453. break;
  9454. default:
  9455. break;
  9456. }
  9457.  
  9458. // Found the pat and pmt, we can stop walking the segment
  9459. if (pmt.pid && pmt.table) {
  9460. return;
  9461. }
  9462.  
  9463. startIndex += MP2T_PACKET_LENGTH;
  9464. endIndex += MP2T_PACKET_LENGTH;
  9465. continue;
  9466. }
  9467.  
  9468. // If we get here, we have somehow become de-synchronized and we need to step
  9469. // forward one byte at a time until we find a pair of sync bytes that denote
  9470. // a packet
  9471. startIndex++;
  9472. endIndex++;
  9473. }
  9474. };
  9475.  
  9476. /**
  9477. * walks through the segment data from the start and end to get timing information
  9478. * for the first and last audio pes packets
  9479. */
  9480. var parseAudioPes_ = function(bytes, pmt, result) {
  9481. var
  9482. startIndex = 0,
  9483. endIndex = MP2T_PACKET_LENGTH,
  9484. packet, type, pesType, pusi, parsed;
  9485.  
  9486. var endLoop = false;
  9487.  
  9488. // Start walking from start of segment to get first audio packet
  9489. while (endIndex <= bytes.byteLength) {
  9490. // Look for a pair of start and end sync bytes in the data..
  9491. if (bytes[startIndex] === SYNC_BYTE &&
  9492. (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  9493. // We found a packet
  9494. packet = bytes.subarray(startIndex, endIndex);
  9495. type = probe.ts.parseType(packet, pmt.pid);
  9496.  
  9497. switch (type) {
  9498. case 'pes':
  9499. pesType = probe.ts.parsePesType(packet, pmt.table);
  9500. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  9501. if (pesType === 'audio' && pusi) {
  9502. parsed = probe.ts.parsePesTime(packet);
  9503. if (parsed) {
  9504. parsed.type = 'audio';
  9505. result.audio.push(parsed);
  9506. endLoop = true;
  9507. }
  9508. }
  9509. break;
  9510. default:
  9511. break;
  9512. }
  9513.  
  9514. if (endLoop) {
  9515. break;
  9516. }
  9517.  
  9518. startIndex += MP2T_PACKET_LENGTH;
  9519. endIndex += MP2T_PACKET_LENGTH;
  9520. continue;
  9521. }
  9522.  
  9523. // If we get here, we have somehow become de-synchronized and we need to step
  9524. // forward one byte at a time until we find a pair of sync bytes that denote
  9525. // a packet
  9526. startIndex++;
  9527. endIndex++;
  9528. }
  9529.  
  9530. // Start walking from end of segment to get last audio packet
  9531. endIndex = bytes.byteLength;
  9532. startIndex = endIndex - MP2T_PACKET_LENGTH;
  9533. endLoop = false;
  9534. while (startIndex >= 0) {
  9535. // Look for a pair of start and end sync bytes in the data..
  9536. if (bytes[startIndex] === SYNC_BYTE &&
  9537. (bytes[endIndex] === SYNC_BYTE || endIndex === bytes.byteLength)) {
  9538. // We found a packet
  9539. packet = bytes.subarray(startIndex, endIndex);
  9540. type = probe.ts.parseType(packet, pmt.pid);
  9541.  
  9542. switch (type) {
  9543. case 'pes':
  9544. pesType = probe.ts.parsePesType(packet, pmt.table);
  9545. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  9546. if (pesType === 'audio' && pusi) {
  9547. parsed = probe.ts.parsePesTime(packet);
  9548. if (parsed) {
  9549. parsed.type = 'audio';
  9550. result.audio.push(parsed);
  9551. endLoop = true;
  9552. }
  9553. }
  9554. break;
  9555. default:
  9556. break;
  9557. }
  9558.  
  9559. if (endLoop) {
  9560. break;
  9561. }
  9562.  
  9563. startIndex -= MP2T_PACKET_LENGTH;
  9564. endIndex -= MP2T_PACKET_LENGTH;
  9565. continue;
  9566. }
  9567.  
  9568. // If we get here, we have somehow become de-synchronized and we need to step
  9569. // forward one byte at a time until we find a pair of sync bytes that denote
  9570. // a packet
  9571. startIndex--;
  9572. endIndex--;
  9573. }
  9574. };
  9575.  
  9576. /**
  9577. * walks through the segment data from the start and end to get timing information
  9578. * for the first and last video pes packets as well as timing information for the first
  9579. * key frame.
  9580. */
  9581. var parseVideoPes_ = function(bytes, pmt, result) {
  9582. var
  9583. startIndex = 0,
  9584. endIndex = MP2T_PACKET_LENGTH,
  9585. packet, type, pesType, pusi, parsed, frame, i, pes;
  9586.  
  9587. var endLoop = false;
  9588.  
  9589. var currentFrame = {
  9590. data: [],
  9591. size: 0
  9592. };
  9593.  
  9594. // Start walking from start of segment to get first video packet
  9595. while (endIndex < bytes.byteLength) {
  9596. // Look for a pair of start and end sync bytes in the data..
  9597. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  9598. // We found a packet
  9599. packet = bytes.subarray(startIndex, endIndex);
  9600. type = probe.ts.parseType(packet, pmt.pid);
  9601.  
  9602. switch (type) {
  9603. case 'pes':
  9604. pesType = probe.ts.parsePesType(packet, pmt.table);
  9605. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  9606. if (pesType === 'video') {
  9607. if (pusi && !endLoop) {
  9608. parsed = probe.ts.parsePesTime(packet);
  9609. if (parsed) {
  9610. parsed.type = 'video';
  9611. result.video.push(parsed);
  9612. endLoop = true;
  9613. }
  9614. }
  9615. if (!result.firstKeyFrame) {
  9616. if (pusi) {
  9617. if (currentFrame.size !== 0) {
  9618. frame = new Uint8Array(currentFrame.size);
  9619. i = 0;
  9620. while (currentFrame.data.length) {
  9621. pes = currentFrame.data.shift();
  9622. frame.set(pes, i);
  9623. i += pes.byteLength;
  9624. }
  9625. if (probe.ts.videoPacketContainsKeyFrame(frame)) {
  9626. var firstKeyFrame = probe.ts.parsePesTime(frame);
  9627.  
  9628. // PTS/DTS may not be available. Simply *not* setting
  9629. // the keyframe seems to work fine with HLS playback
  9630. // and definitely preferable to a crash with TypeError...
  9631. if (firstKeyFrame) {
  9632. result.firstKeyFrame = firstKeyFrame;
  9633. result.firstKeyFrame.type = 'video';
  9634. } else {
  9635. // eslint-disable-next-line
  9636. console.warn(
  9637. 'Failed to extract PTS/DTS from PES at first keyframe. ' +
  9638. 'This could be an unusual TS segment, or else mux.js did not ' +
  9639. 'parse your TS segment correctly. If you know your TS ' +
  9640. 'segments do contain PTS/DTS on keyframes please file a bug ' +
  9641. 'report! You can try ffprobe to double check for yourself.'
  9642. );
  9643. }
  9644. }
  9645. currentFrame.size = 0;
  9646. }
  9647. }
  9648. currentFrame.data.push(packet);
  9649. currentFrame.size += packet.byteLength;
  9650. }
  9651. }
  9652. break;
  9653. default:
  9654. break;
  9655. }
  9656.  
  9657. if (endLoop && result.firstKeyFrame) {
  9658. break;
  9659. }
  9660.  
  9661. startIndex += MP2T_PACKET_LENGTH;
  9662. endIndex += MP2T_PACKET_LENGTH;
  9663. continue;
  9664. }
  9665.  
  9666. // If we get here, we have somehow become de-synchronized and we need to step
  9667. // forward one byte at a time until we find a pair of sync bytes that denote
  9668. // a packet
  9669. startIndex++;
  9670. endIndex++;
  9671. }
  9672.  
  9673. // Start walking from end of segment to get last video packet
  9674. endIndex = bytes.byteLength;
  9675. startIndex = endIndex - MP2T_PACKET_LENGTH;
  9676. endLoop = false;
  9677. while (startIndex >= 0) {
  9678. // Look for a pair of start and end sync bytes in the data..
  9679. if (bytes[startIndex] === SYNC_BYTE && bytes[endIndex] === SYNC_BYTE) {
  9680. // We found a packet
  9681. packet = bytes.subarray(startIndex, endIndex);
  9682. type = probe.ts.parseType(packet, pmt.pid);
  9683.  
  9684. switch (type) {
  9685. case 'pes':
  9686. pesType = probe.ts.parsePesType(packet, pmt.table);
  9687. pusi = probe.ts.parsePayloadUnitStartIndicator(packet);
  9688. if (pesType === 'video' && pusi) {
  9689. parsed = probe.ts.parsePesTime(packet);
  9690. if (parsed) {
  9691. parsed.type = 'video';
  9692. result.video.push(parsed);
  9693. endLoop = true;
  9694. }
  9695. }
  9696. break;
  9697. default:
  9698. break;
  9699. }
  9700.  
  9701. if (endLoop) {
  9702. break;
  9703. }
  9704.  
  9705. startIndex -= MP2T_PACKET_LENGTH;
  9706. endIndex -= MP2T_PACKET_LENGTH;
  9707. continue;
  9708. }
  9709.  
  9710. // If we get here, we have somehow become de-synchronized and we need to step
  9711. // forward one byte at a time until we find a pair of sync bytes that denote
  9712. // a packet
  9713. startIndex--;
  9714. endIndex--;
  9715. }
  9716. };
  9717.  
  9718. /**
  9719. * Adjusts the timestamp information for the segment to account for
  9720. * rollover and convert to seconds based on pes packet timescale (90khz clock)
  9721. */
  9722. var adjustTimestamp_ = function(segmentInfo, baseTimestamp) {
  9723. if (segmentInfo.audio && segmentInfo.audio.length) {
  9724. var audioBaseTimestamp = baseTimestamp;
  9725. if (typeof audioBaseTimestamp === 'undefined') {
  9726. audioBaseTimestamp = segmentInfo.audio[0].dts;
  9727. }
  9728. segmentInfo.audio.forEach(function(info) {
  9729. info.dts = handleRollover(info.dts, audioBaseTimestamp);
  9730. info.pts = handleRollover(info.pts, audioBaseTimestamp);
  9731. // time in seconds
  9732. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  9733. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  9734. });
  9735. }
  9736.  
  9737. if (segmentInfo.video && segmentInfo.video.length) {
  9738. var videoBaseTimestamp = baseTimestamp;
  9739. if (typeof videoBaseTimestamp === 'undefined') {
  9740. videoBaseTimestamp = segmentInfo.video[0].dts;
  9741. }
  9742. segmentInfo.video.forEach(function(info) {
  9743. info.dts = handleRollover(info.dts, videoBaseTimestamp);
  9744. info.pts = handleRollover(info.pts, videoBaseTimestamp);
  9745. // time in seconds
  9746. info.dtsTime = info.dts / ONE_SECOND_IN_TS;
  9747. info.ptsTime = info.pts / ONE_SECOND_IN_TS;
  9748. });
  9749. if (segmentInfo.firstKeyFrame) {
  9750. var frame = segmentInfo.firstKeyFrame;
  9751. frame.dts = handleRollover(frame.dts, videoBaseTimestamp);
  9752. frame.pts = handleRollover(frame.pts, videoBaseTimestamp);
  9753. // time in seconds
  9754. frame.dtsTime = frame.dts / ONE_SECOND_IN_TS;
  9755. frame.ptsTime = frame.dts / ONE_SECOND_IN_TS;
  9756. }
  9757. }
  9758. };
  9759.  
  9760. /**
  9761. * inspects the aac data stream for start and end time information
  9762. */
  9763. var inspectAac_ = function(bytes) {
  9764. var
  9765. endLoop = false,
  9766. audioCount = 0,
  9767. sampleRate = null,
  9768. timestamp = null,
  9769. frameSize = 0,
  9770. byteIndex = 0,
  9771. packet;
  9772.  
  9773. while (bytes.length - byteIndex >= 3) {
  9774. var type = probe.aac.parseType(bytes, byteIndex);
  9775. switch (type) {
  9776. case 'timed-metadata':
  9777. // Exit early because we don't have enough to parse
  9778. // the ID3 tag header
  9779. if (bytes.length - byteIndex < 10) {
  9780. endLoop = true;
  9781. break;
  9782. }
  9783.  
  9784. frameSize = probe.aac.parseId3TagSize(bytes, byteIndex);
  9785.  
  9786. // Exit early if we don't have enough in the buffer
  9787. // to emit a full packet
  9788. if (frameSize > bytes.length) {
  9789. endLoop = true;
  9790. break;
  9791. }
  9792. if (timestamp === null) {
  9793. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  9794. timestamp = probe.aac.parseAacTimestamp(packet);
  9795. }
  9796. byteIndex += frameSize;
  9797. break;
  9798. case 'audio':
  9799. // Exit early because we don't have enough to parse
  9800. // the ADTS frame header
  9801. if (bytes.length - byteIndex < 7) {
  9802. endLoop = true;
  9803. break;
  9804. }
  9805.  
  9806. frameSize = probe.aac.parseAdtsSize(bytes, byteIndex);
  9807.  
  9808. // Exit early if we don't have enough in the buffer
  9809. // to emit a full packet
  9810. if (frameSize > bytes.length) {
  9811. endLoop = true;
  9812. break;
  9813. }
  9814. if (sampleRate === null) {
  9815. packet = bytes.subarray(byteIndex, byteIndex + frameSize);
  9816. sampleRate = probe.aac.parseSampleRate(packet);
  9817. }
  9818. audioCount++;
  9819. byteIndex += frameSize;
  9820. break;
  9821. default:
  9822. byteIndex++;
  9823. break;
  9824. }
  9825. if (endLoop) {
  9826. return null;
  9827. }
  9828. }
  9829. if (sampleRate === null || timestamp === null) {
  9830. return null;
  9831. }
  9832.  
  9833. var audioTimescale = ONE_SECOND_IN_TS / sampleRate;
  9834.  
  9835. var result = {
  9836. audio: [
  9837. {
  9838. type: 'audio',
  9839. dts: timestamp,
  9840. pts: timestamp
  9841. },
  9842. {
  9843. type: 'audio',
  9844. dts: timestamp + (audioCount * 1024 * audioTimescale),
  9845. pts: timestamp + (audioCount * 1024 * audioTimescale)
  9846. }
  9847. ]
  9848. };
  9849.  
  9850. return result;
  9851. };
  9852.  
  9853. /**
  9854. * inspects the transport stream segment data for start and end time information
  9855. * of the audio and video tracks (when present) as well as the first key frame's
  9856. * start time.
  9857. */
  9858. var inspectTs_ = function(bytes) {
  9859. var pmt = {
  9860. pid: null,
  9861. table: null
  9862. };
  9863.  
  9864. var result = {};
  9865.  
  9866. parsePsi_(bytes, pmt);
  9867.  
  9868. for (var pid in pmt.table) {
  9869. if (pmt.table.hasOwnProperty(pid)) {
  9870. var type = pmt.table[pid];
  9871. switch (type) {
  9872. case StreamTypes.H264_STREAM_TYPE:
  9873. result.video = [];
  9874. parseVideoPes_(bytes, pmt, result);
  9875. if (result.video.length === 0) {
  9876. delete result.video;
  9877. }
  9878. break;
  9879. case StreamTypes.ADTS_STREAM_TYPE:
  9880. result.audio = [];
  9881. parseAudioPes_(bytes, pmt, result);
  9882. if (result.audio.length === 0) {
  9883. delete result.audio;
  9884. }
  9885. break;
  9886. default:
  9887. break;
  9888. }
  9889. }
  9890. }
  9891. return result;
  9892. };
  9893.  
  9894. /**
  9895. * Inspects segment byte data and returns an object with start and end timing information
  9896. *
  9897. * @param {Uint8Array} bytes The segment byte data
  9898. * @param {Number} baseTimestamp Relative reference timestamp used when adjusting frame
  9899. * timestamps for rollover. This value must be in 90khz clock.
  9900. * @return {Object} Object containing start and end frame timing info of segment.
  9901. */
  9902. var inspect = function(bytes, baseTimestamp) {
  9903. var isAacData = probe.aac.isLikelyAacData(bytes);
  9904.  
  9905. var result;
  9906.  
  9907. if (isAacData) {
  9908. result = inspectAac_(bytes);
  9909. } else {
  9910. result = inspectTs_(bytes);
  9911. }
  9912.  
  9913. if (!result || (!result.audio && !result.video)) {
  9914. return null;
  9915. }
  9916.  
  9917. adjustTimestamp_(result, baseTimestamp);
  9918.  
  9919. return result;
  9920. };
  9921.  
  9922. module.exports = {
  9923. inspect: inspect,
  9924. parseAudioPes_: parseAudioPes_
  9925. };
  9926.  
  9927. },{"18":18,"19":19,"2":2,"20":20,"38":38}],37:[function(require,module,exports){
  9928. /**
  9929. * mux.js
  9930. *
  9931. * Copyright (c) Brightcove
  9932. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9933. */
  9934. var toUnsigned = function(value) {
  9935. return value >>> 0;
  9936. };
  9937.  
  9938. module.exports = {
  9939. toUnsigned: toUnsigned
  9940. };
  9941.  
  9942. },{}],38:[function(require,module,exports){
  9943. /**
  9944. * mux.js
  9945. *
  9946. * Copyright (c) Brightcove
  9947. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  9948. */
  9949. var
  9950. ONE_SECOND_IN_TS = 90000, // 90kHz clock
  9951. secondsToVideoTs,
  9952. secondsToAudioTs,
  9953. videoTsToSeconds,
  9954. audioTsToSeconds,
  9955. audioTsToVideoTs,
  9956. videoTsToAudioTs,
  9957. metadataTsToSeconds;
  9958.  
  9959. secondsToVideoTs = function(seconds) {
  9960. return seconds * ONE_SECOND_IN_TS;
  9961. };
  9962.  
  9963. secondsToAudioTs = function(seconds, sampleRate) {
  9964. return seconds * sampleRate;
  9965. };
  9966.  
  9967. videoTsToSeconds = function(timestamp) {
  9968. return timestamp / ONE_SECOND_IN_TS;
  9969. };
  9970.  
  9971. audioTsToSeconds = function(timestamp, sampleRate) {
  9972. return timestamp / sampleRate;
  9973. };
  9974.  
  9975. audioTsToVideoTs = function(timestamp, sampleRate) {
  9976. return secondsToVideoTs(audioTsToSeconds(timestamp, sampleRate));
  9977. };
  9978.  
  9979. videoTsToAudioTs = function(timestamp, sampleRate) {
  9980. return secondsToAudioTs(videoTsToSeconds(timestamp), sampleRate);
  9981. };
  9982.  
  9983. /**
  9984. * Adjust ID3 tag or caption timing information by the timeline pts values
  9985. * (if keepOriginalTimestamps is false) and convert to seconds
  9986. */
  9987. metadataTsToSeconds = function(timestamp, timelineStartPts, keepOriginalTimestamps) {
  9988. return videoTsToSeconds(keepOriginalTimestamps ? timestamp : timestamp - timelineStartPts);
  9989. };
  9990.  
  9991. module.exports = {
  9992. ONE_SECOND_IN_TS: ONE_SECOND_IN_TS,
  9993. secondsToVideoTs: secondsToVideoTs,
  9994. secondsToAudioTs: secondsToAudioTs,
  9995. videoTsToSeconds: videoTsToSeconds,
  9996. audioTsToSeconds: audioTsToSeconds,
  9997. audioTsToVideoTs: audioTsToVideoTs,
  9998. videoTsToAudioTs: videoTsToAudioTs,
  9999. metadataTsToSeconds: metadataTsToSeconds
  10000. };
  10001.  
  10002. },{}],39:[function(require,module,exports){
  10003. /**
  10004. * mux.js
  10005. *
  10006. * Copyright (c) Brightcove
  10007. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10008. */
  10009. 'use strict';
  10010.  
  10011. var ExpGolomb;
  10012.  
  10013. /**
  10014. * Parser for exponential Golomb codes, a variable-bitwidth number encoding
  10015. * scheme used by h264.
  10016. */
  10017. ExpGolomb = function(workingData) {
  10018. var
  10019. // the number of bytes left to examine in workingData
  10020. workingBytesAvailable = workingData.byteLength,
  10021.  
  10022. // the current word being examined
  10023. workingWord = 0, // :uint
  10024.  
  10025. // the number of bits left to examine in the current word
  10026. workingBitsAvailable = 0; // :uint;
  10027.  
  10028. // ():uint
  10029. this.length = function() {
  10030. return (8 * workingBytesAvailable);
  10031. };
  10032.  
  10033. // ():uint
  10034. this.bitsAvailable = function() {
  10035. return (8 * workingBytesAvailable) + workingBitsAvailable;
  10036. };
  10037.  
  10038. // ():void
  10039. this.loadWord = function() {
  10040. var
  10041. position = workingData.byteLength - workingBytesAvailable,
  10042. workingBytes = new Uint8Array(4),
  10043. availableBytes = Math.min(4, workingBytesAvailable);
  10044.  
  10045. if (availableBytes === 0) {
  10046. throw new Error('no bytes available');
  10047. }
  10048.  
  10049. workingBytes.set(workingData.subarray(position,
  10050. position + availableBytes));
  10051. workingWord = new DataView(workingBytes.buffer).getUint32(0);
  10052.  
  10053. // track the amount of workingData that has been processed
  10054. workingBitsAvailable = availableBytes * 8;
  10055. workingBytesAvailable -= availableBytes;
  10056. };
  10057.  
  10058. // (count:int):void
  10059. this.skipBits = function(count) {
  10060. var skipBytes; // :int
  10061. if (workingBitsAvailable > count) {
  10062. workingWord <<= count;
  10063. workingBitsAvailable -= count;
  10064. } else {
  10065. count -= workingBitsAvailable;
  10066. skipBytes = Math.floor(count / 8);
  10067.  
  10068. count -= (skipBytes * 8);
  10069. workingBytesAvailable -= skipBytes;
  10070.  
  10071. this.loadWord();
  10072.  
  10073. workingWord <<= count;
  10074. workingBitsAvailable -= count;
  10075. }
  10076. };
  10077.  
  10078. // (size:int):uint
  10079. this.readBits = function(size) {
  10080. var
  10081. bits = Math.min(workingBitsAvailable, size), // :uint
  10082. valu = workingWord >>> (32 - bits); // :uint
  10083. // if size > 31, handle error
  10084. workingBitsAvailable -= bits;
  10085. if (workingBitsAvailable > 0) {
  10086. workingWord <<= bits;
  10087. } else if (workingBytesAvailable > 0) {
  10088. this.loadWord();
  10089. }
  10090.  
  10091. bits = size - bits;
  10092. if (bits > 0) {
  10093. return valu << bits | this.readBits(bits);
  10094. }
  10095. return valu;
  10096. };
  10097.  
  10098. // ():uint
  10099. this.skipLeadingZeros = function() {
  10100. var leadingZeroCount; // :uint
  10101. for (leadingZeroCount = 0; leadingZeroCount < workingBitsAvailable; ++leadingZeroCount) {
  10102. if ((workingWord & (0x80000000 >>> leadingZeroCount)) !== 0) {
  10103. // the first bit of working word is 1
  10104. workingWord <<= leadingZeroCount;
  10105. workingBitsAvailable -= leadingZeroCount;
  10106. return leadingZeroCount;
  10107. }
  10108. }
  10109.  
  10110. // we exhausted workingWord and still have not found a 1
  10111. this.loadWord();
  10112. return leadingZeroCount + this.skipLeadingZeros();
  10113. };
  10114.  
  10115. // ():void
  10116. this.skipUnsignedExpGolomb = function() {
  10117. this.skipBits(1 + this.skipLeadingZeros());
  10118. };
  10119.  
  10120. // ():void
  10121. this.skipExpGolomb = function() {
  10122. this.skipBits(1 + this.skipLeadingZeros());
  10123. };
  10124.  
  10125. // ():uint
  10126. this.readUnsignedExpGolomb = function() {
  10127. var clz = this.skipLeadingZeros(); // :uint
  10128. return this.readBits(clz + 1) - 1;
  10129. };
  10130.  
  10131. // ():int
  10132. this.readExpGolomb = function() {
  10133. var valu = this.readUnsignedExpGolomb(); // :int
  10134. if (0x01 & valu) {
  10135. // the number is odd if the low order bit is set
  10136. return (1 + valu) >>> 1; // add 1 to make it even, and divide by 2
  10137. }
  10138. return -1 * (valu >>> 1); // divide by two then make it negative
  10139. };
  10140.  
  10141. // Some convenience functions
  10142. // :Boolean
  10143. this.readBoolean = function() {
  10144. return this.readBits(1) === 1;
  10145. };
  10146.  
  10147. // ():int
  10148. this.readUnsignedByte = function() {
  10149. return this.readBits(8);
  10150. };
  10151.  
  10152. this.loadWord();
  10153. };
  10154.  
  10155. module.exports = ExpGolomb;
  10156.  
  10157. },{}],40:[function(require,module,exports){
  10158. /**
  10159. * mux.js
  10160. *
  10161. * Copyright (c) Brightcove
  10162. * Licensed Apache-2.0 https://github.com/videojs/mux.js/blob/master/LICENSE
  10163. *
  10164. * A lightweight readable stream implemention that handles event dispatching.
  10165. * Objects that inherit from streams should call init in their constructors.
  10166. */
  10167. 'use strict';
  10168.  
  10169. var Stream = function() {
  10170. this.init = function() {
  10171. var listeners = {};
  10172. /**
  10173. * Add a listener for a specified event type.
  10174. * @param type {string} the event name
  10175. * @param listener {function} the callback to be invoked when an event of
  10176. * the specified type occurs
  10177. */
  10178. this.on = function(type, listener) {
  10179. if (!listeners[type]) {
  10180. listeners[type] = [];
  10181. }
  10182. listeners[type] = listeners[type].concat(listener);
  10183. };
  10184. /**
  10185. * Remove a listener for a specified event type.
  10186. * @param type {string} the event name
  10187. * @param listener {function} a function previously registered for this
  10188. * type of event through `on`
  10189. */
  10190. this.off = function(type, listener) {
  10191. var index;
  10192. if (!listeners[type]) {
  10193. return false;
  10194. }
  10195. index = listeners[type].indexOf(listener);
  10196. listeners[type] = listeners[type].slice();
  10197. listeners[type].splice(index, 1);
  10198. return index > -1;
  10199. };
  10200. /**
  10201. * Trigger an event of the specified type on this stream. Any additional
  10202. * arguments to this function are passed as parameters to event listeners.
  10203. * @param type {string} the event name
  10204. */
  10205. this.trigger = function(type) {
  10206. var callbacks, i, length, args;
  10207. callbacks = listeners[type];
  10208. if (!callbacks) {
  10209. return;
  10210. }
  10211. // Slicing the arguments on every invocation of this method
  10212. // can add a significant amount of overhead. Avoid the
  10213. // intermediate object creation for the common case of a
  10214. // single callback argument
  10215. if (arguments.length === 2) {
  10216. length = callbacks.length;
  10217. for (i = 0; i < length; ++i) {
  10218. callbacks[i].call(this, arguments[1]);
  10219. }
  10220. } else {
  10221. args = [];
  10222. i = arguments.length;
  10223. for (i = 1; i < arguments.length; ++i) {
  10224. args.push(arguments[i]);
  10225. }
  10226. length = callbacks.length;
  10227. for (i = 0; i < length; ++i) {
  10228. callbacks[i].apply(this, args);
  10229. }
  10230. }
  10231. };
  10232. /**
  10233. * Destroys the stream and cleans up.
  10234. */
  10235. this.dispose = function() {
  10236. listeners = {};
  10237. };
  10238. };
  10239. };
  10240.  
  10241. /**
  10242. * Forwards all `data` events on this stream to the destination stream. The
  10243. * destination stream should provide a method `push` to receive the data
  10244. * events as they arrive.
  10245. * @param destination {stream} the stream that will receive all `data` events
  10246. * @param autoFlush {boolean} if false, we will not call `flush` on the destination
  10247. * when the current stream emits a 'done' event
  10248. * @see http://nodejs.org/api/stream.html#stream_readable_pipe_destination_options
  10249. */
  10250. Stream.prototype.pipe = function(destination) {
  10251. this.on('data', function(data) {
  10252. destination.push(data);
  10253. });
  10254.  
  10255. this.on('done', function(flushSource) {
  10256. destination.flush(flushSource);
  10257. });
  10258.  
  10259. this.on('partialdone', function(flushSource) {
  10260. destination.partialFlush(flushSource);
  10261. });
  10262.  
  10263. this.on('endedtimeline', function(flushSource) {
  10264. destination.endTimeline(flushSource);
  10265. });
  10266.  
  10267. this.on('reset', function(flushSource) {
  10268. destination.reset(flushSource);
  10269. });
  10270.  
  10271. return destination;
  10272. };
  10273.  
  10274. // Default stream functions that are expected to be overridden to perform
  10275. // actual work. These are provided by the prototype as a sort of no-op
  10276. // implementation so that we don't have to check for their existence in the
  10277. // `pipe` function above.
  10278. Stream.prototype.push = function(data) {
  10279. this.trigger('data', data);
  10280. };
  10281.  
  10282. Stream.prototype.flush = function(flushSource) {
  10283. this.trigger('done', flushSource);
  10284. };
  10285.  
  10286. Stream.prototype.partialFlush = function(flushSource) {
  10287. this.trigger('partialdone', flushSource);
  10288. };
  10289.  
  10290. Stream.prototype.endTimeline = function(flushSource) {
  10291. this.trigger('endedtimeline', flushSource);
  10292. };
  10293.  
  10294. Stream.prototype.reset = function(flushSource) {
  10295. this.trigger('reset', flushSource);
  10296. };
  10297.  
  10298. module.exports = Stream;
  10299.  
  10300. },{}]},{},[13])(13)
  10301. });