tssmooth.js 5.5 KB

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