tssmooth.js 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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.error_limit = 80000; /* 80 ms */
  42. this.bitrate = 10E06;
  43. this.pcrtime = -1;
  44. this.pcrdelta = function(pcr, pcr_old) {
  45. var pcr_delta = pcr - pcr_old;
  46. if (pcr_delta < 0) pcr_delta += (0x200000000 * 300) / 27;
  47. return pcr_delta;
  48. }
  49. this.pcr2time = function(pcr) {
  50. if (self.pcr === -1) {
  51. self.pcr = pcr;
  52. self.last = utime();
  53. }
  54. var pcr_delta = self.pcrdelta(pcr, self.pcr);
  55. var ret = self.last + pcr_delta;
  56. if (pcr_delta > 3600E6) {
  57. // update pcr reference every hour to handle wrap-around
  58. self.pcr = pcr;
  59. self.last = ret;
  60. }
  61. return ret;
  62. }
  63. this.output_time = function(newPCR) {
  64. // when this is called normally, now ~= self.pcrtime
  65. if (newPCR === -1) return;
  66. var pcrtime = self.pcr2time(newPCR);
  67. if (self.pcrtime === -1) {
  68. self.pcrtime = pcrtime;
  69. return;
  70. }
  71. var delta = pcrtime - self.pcrtime;
  72. self.pcrtime = pcrtime;
  73. return { time:pcrtime, delta: delta };
  74. }
  75. Transform.call(this, {highWaterMark:this.packetSize});
  76. }
  77. util.inherits(TsSmooth, Transform);
  78. TsSmooth.prototype.reset = function(currentPCR) {
  79. this.pcr = -1;
  80. if (typeof currentPCR !== 'undefined')
  81. this.pcrtime = this.pcr2time(currentPCR);
  82. };
  83. function utime() {
  84. var t = process.hrtime(); // based on CLOCK_MONOTONIC, and thus accommodates local drift (but apparently not suspend)
  85. // console.error(t);
  86. return t[0] * 1E6 + t[1] / 1E3;
  87. }
  88. function wait(waitMs, fn) {
  89. if (waitMs > 0)
  90. setTimeout(fn, waitMs);
  91. else
  92. fn();
  93. }
  94. // smoothly outputs given buffer before endTime
  95. function outputBefore(stream, buffer, endTime, packetSize, cb) {
  96. var index = 0;
  97. function outputPacket() {
  98. var now = utime();
  99. var packetTime = (endTime - now) * (packetSize / (buffer.length - index));
  100. stream.push(buffer.slice(index, Math.min(buffer.length, index+packetSize)));
  101. index += packetSize;
  102. var done = (index < buffer.length) ? outputPacket: cb;
  103. var delay = Math.min(Math.max((0.8*packetTime/1000)-1, 1), 50);
  104. if (delay === 1)
  105. process.nextTick(done);
  106. else
  107. setTimeout(done, delay);
  108. }
  109. outputPacket();
  110. }
  111. TsSmooth.prototype._transform = function(chunk, encoding, cb) {
  112. var self = this;
  113. var index = Math.floor(this.buffer.length/188)*188;
  114. this.buffer = Buffer.concat([this.buffer, chunk]);
  115. var buf = self.buffer;
  116. var end = buf.length-188;
  117. var startIndex = 0;
  118. function processNext() {
  119. while (index < end) {
  120. // check sync
  121. if (buf.readUInt8(index+188, true) !== 0x47) {
  122. // find next potential sync point
  123. debug('ts sync lost');
  124. var sync = index+1;
  125. for (; sync < end; sync++) {
  126. if (buf.readUInt8(sync, true) === 0x47)
  127. break;
  128. }
  129. // remove bad data
  130. debug('slice', sync, end);
  131. buf = Buffer.concat([buf.slice(0, index), buf.slice(sync)]);
  132. end -= sync-index;
  133. continue;
  134. }
  135. var pcr = parsePCR(buf, index);
  136. var out = self.output_time(pcr);
  137. if (out !== undefined && index !== startIndex) {
  138. if (out.delta > 100E3 || out.delta < 0)
  139. self.emit('warning', new Error('PCR_error: '+(out.delta/1E6).toFixed(2)+'s missing'));
  140. var now = utime();
  141. var error = (out.time - now) - out.delta;
  142. var waittime = (error > self.error_limit) ? (error/1000 - 5) : 0;
  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. } else if (error < -self.error_limit) {
  150. // ignore the data since it is too late
  151. return processNext();
  152. }
  153. return wait(waittime, function output() {
  154. var slice = buf.slice(startIndex, index);
  155. startIndex = index;
  156. return outputBefore(self, slice, out.time, self.packetSize, processNext);
  157. });
  158. }
  159. index += 188;
  160. }
  161. if (startIndex !== 0) self.buffer = buf.slice(startIndex);
  162. cb();
  163. }
  164. processNext();
  165. };
  166. TsSmooth.prototype._flush = function(cb) {
  167. if (this.buffer.length) this.push(this.buffer); // TODO: use outputBefore() based on current stream speed?
  168. cb();
  169. };
  170. function tssmooth(options) {
  171. return new TsSmooth(options);
  172. }