tssmooth.js 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. 'use strict';
  2. const util = require('util');
  3. const debug = require('debug')('hls:tssmooth');
  4. const Transform = require('readable-stream/transform');
  5. const internals = {};
  6. // In Transport Streams the intended rate is determined by the values of the PCR fields and the number of Transport Stream bytes between them. (ISO-13818-1 D.0.9)
  7. function RateError(msg) {
  8. Error.call(this);
  9. this.message = msg;
  10. }
  11. util.inherits(RateError, Error);
  12. RateError.prototype.name = 'Rate Error';
  13. internals.parsePCR = function(buffer, index, pcr_pid) {
  14. let head = buffer.readUInt32BE(index, true);
  15. let pid = (head >> 8) & 0x1fff;
  16. if (((head >> 5) & 1) !== 1) return -1;
  17. if (pcr_pid && pcr_pid != pid) return -1;
  18. let s = buffer.readUInt8(index + 4, true);
  19. if (s < 7) return -1;
  20. let f = buffer.readUInt8(index + 5, true);
  21. if (((f >> 4) & 1) !== 1) return -1;
  22. let base = buffer.readUInt32BE(index + 6, true) * 2;
  23. let ext = buffer.readUInt32BE(index + 10, true);
  24. base += (ext >> 31);
  25. ext = ext & 0x1ff;
  26. return base / 0.09 + ext / 27; // return usecs
  27. };
  28. internals.utime = function() {
  29. let t = process.hrtime(); // based on CLOCK_MONOTONIC, and thus accommodates local drift (but apparently not suspend)
  30. // console.error(t);
  31. return t[0] * 1E6 + t[1] / 1E3;
  32. };
  33. internals.wait = function(waitMs, fn) {
  34. if (waitMs > 0)
  35. setTimeout(fn, Math.round(waitMs));
  36. else
  37. fn();
  38. }
  39. function TsSmooth(options) {
  40. options = options || {};
  41. this.packetSize = options.packetSize || 7 * 188; // size of output packets
  42. this.buffer = new Buffer(0);
  43. this.pcr = -1;
  44. this.last = null;
  45. this.errorLimit = 80000; /* 80 ms */
  46. this.bitrate = 10E06;
  47. this.pcrTime = -1;
  48. this.pcrDelta = (pcr, lastPcr) => {
  49. let pcrDelta = pcr - lastPcr;
  50. if (pcrDelta < 0) pcrDelta += (0x200000000 * 300) / 27;
  51. return pcrDelta;
  52. };
  53. this.pcr2time = (pcr) => {
  54. if (this.pcr === -1) {
  55. this.pcr = pcr;
  56. this.last = internals.utime();
  57. }
  58. let pcrDelta = this.pcrDelta(pcr, this.pcr);
  59. let ret = this.last + pcrDelta;
  60. if (pcrDelta > 3600E6) {
  61. // update pcr reference every hour to handle wrap-around
  62. this.pcr = pcr;
  63. this.last = ret;
  64. }
  65. return ret;
  66. };
  67. this.outputTime = (newPCR) => {
  68. // when this is called normally, now ~= this.pcrtime
  69. if (newPCR === -1) return undefined;
  70. let pcrtime = this.pcr2time(newPCR);
  71. if (this.pcrTime === -1) {
  72. this.pcrTime = pcrtime;
  73. return undefined;
  74. }
  75. let delta = pcrtime - this.pcrTime;
  76. this.pcrTime = pcrtime;
  77. return { time:pcrtime, delta: delta };
  78. };
  79. Transform.call(this, {highWaterMark:this.packetSize});
  80. }
  81. util.inherits(TsSmooth, Transform);
  82. TsSmooth.prototype.reset = function(currentPCR) {
  83. this.pcr = -1;
  84. if (typeof currentPCR !== 'undefined')
  85. this.pcrTime = this.pcr2time(currentPCR);
  86. };
  87. // smoothly outputs given buffer before endTime
  88. function outputBefore(stream, buffer, endTime, packetSize, cb) {
  89. let index = 0;
  90. const outputPacket = () => {
  91. let now = internals.utime();
  92. let packetTime = (endTime - now) * (packetSize / (buffer.length - index));
  93. stream.push(buffer.slice(index, Math.min(buffer.length, index + packetSize)));
  94. index += packetSize;
  95. let done = (index < buffer.length) ? outputPacket : cb;
  96. let delay = Math.round(Math.min(Math.max((0.8 * packetTime / 1000) - 1, 1), 50));
  97. if (delay === 1)
  98. process.nextTick(done);
  99. else
  100. setTimeout(done, delay);
  101. }
  102. outputPacket();
  103. }
  104. TsSmooth.prototype._transform = function(chunk, encoding, cb) {
  105. let index = Math.floor(this.buffer.length / 188) * 188;
  106. this.buffer = Buffer.concat([this.buffer, chunk]);
  107. let buf = this.buffer;
  108. let end = buf.length - 188;
  109. let startIndex = 0;
  110. const processNext = () => {
  111. while (index < end) {
  112. // check sync
  113. if (buf.readUInt8(index + 188, true) !== 0x47) {
  114. // find next potential sync point
  115. debug('ts sync lost');
  116. let sync = index + 1;
  117. for (; sync < end; sync++) {
  118. if (buf.readUInt8(sync, true) === 0x47)
  119. break;
  120. }
  121. // remove bad data
  122. debug('slice', sync, end);
  123. buf = Buffer.concat([buf.slice(0, index), buf.slice(sync)]);
  124. end -= sync - index;
  125. continue;
  126. }
  127. let pcr = internals.parsePCR(buf, index);
  128. let out = this.outputTime(pcr);
  129. if (out !== undefined && index !== startIndex) {
  130. if (out.delta > 100E3 || out.delta < 0)
  131. this.emit('warning', new Error('PCR_error: ' + (out.delta / 1E6).toFixed(2) + 's missing'));
  132. let now = internals.utime();
  133. let error = (out.time - now) - out.delta;
  134. let waittime = (error > this.errorLimit) ? (error / 1000 - 5) : 0;
  135. if (error < -2 * 1E6 || error > 300 * 1E6) {
  136. // negative == buffer too late
  137. // positive == buffer too early
  138. this.emit('warning', new RateError('PCR sync offset ' + (error / 1E6).toFixed(2) + 's error'));
  139. this.reset(pcr);
  140. waittime = 0;
  141. } else if (error < -this.errorLimit) {
  142. // ignore the data since it is too late
  143. return setImmediate(processNext);
  144. }
  145. let slice = buf.slice(startIndex, index);
  146. startIndex = index;
  147. /* eslint-disable no-loop-func */
  148. return internals.wait(waittime, () => {
  149. return outputBefore(this, slice, out.time, this.packetSize, processNext);
  150. });
  151. /* eslint-enable */
  152. }
  153. index += 188;
  154. }
  155. if (startIndex !== 0) this.buffer = buf.slice(startIndex);
  156. cb();
  157. }
  158. processNext();
  159. };
  160. TsSmooth.prototype._flush = function(cb) {
  161. if (this.buffer.length) this.push(this.buffer); // TODO: use outputBefore() based on current stream speed?
  162. cb();
  163. };
  164. const tssmooth = module.exports = function tssmooth(options) {
  165. return new TsSmooth(options);
  166. };
  167. tssmooth.TsSmooth = TsSmooth;