tssmooth.js 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  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. if (newPCR === -1) return -1;
  64. var pcrtime = self.pcr2time(newPCR);
  65. if (self.pcrtime === -1) {
  66. self.pcrtime = pcrtime;
  67. return -1;
  68. }
  69. var delta = pcrtime - self.pcrtime;
  70. if (delta > 100E3 || delta < 0) {
  71. console.error('PCR_error: '+(delta/1E6).toFixed(2)+'s missing');
  72. }
  73. var now = utime();
  74. var error = now - pcrtime;
  75. if (Math.abs(error) > 20*1E6) {
  76. self.emit('error', new RateError('PCR sync offset '+(error/1E6).toFixed(2)+'s error'));
  77. self.pcr = -1;
  78. pcrtime = self.pcr2time(newPCR);
  79. }
  80. self.pcrtime = pcrtime;
  81. return pcrtime;
  82. }
  83. Transform.call(this, {highWaterMark:this.packetSize});
  84. }
  85. util.inherits(TsSmooth, Transform);
  86. function utime() {
  87. var t = process.hrtime(); // based on CLOCK_MONOTONIC, and thus accommodates local drift (but apparently not suspend)
  88. // console.error(t);
  89. return t[0] * 1E6 + t[1] / 1E3;
  90. }
  91. // smoothly outputs given buffer before endTime
  92. function outputBefore(stream, buffer, endTime, packetSize, cb) {
  93. var index = 0;
  94. function outputPacket() {
  95. var now = utime();
  96. var packetTime = (endTime - now) * (packetSize / (buffer.length - index));
  97. stream.push(buffer.slice(index, Math.min(buffer.length, index+packetSize)));
  98. index += packetSize;
  99. var done = (index < buffer.length) ? outputPacket: cb;
  100. var delay = Math.min(Math.max((0.8*packetTime/1000)-1, 1), 50);
  101. if (delay === 1)
  102. process.nextTick(done);
  103. else
  104. setTimeout(done, delay);
  105. }
  106. outputPacket();
  107. }
  108. TsSmooth.prototype._transform = function(chunk, encoding, cb) {
  109. var self = this;
  110. var index = Math.floor(this.buffer.length/188)*188;
  111. this.buffer = Buffer.concat([this.buffer, chunk]);
  112. var buf = self.buffer;
  113. var end = buf.length-188;
  114. var startIndex = 0;
  115. function processNext() {
  116. while (index < end) {
  117. // check sync
  118. if (buf.readUInt8(index+188, true) !== 0x47) {
  119. // find next potential sync point
  120. debug('ts sync lost');
  121. var sync = index+1;
  122. for (; sync < end; sync++) {
  123. if (buf.readUInt8(sync, true) === 0x47)
  124. break;
  125. }
  126. // remove bad data
  127. debug('slice', sync, end);
  128. buf = Buffer.concat([buf.slice(0, index), buf.slice(sync)]);
  129. end -= sync-index;
  130. continue;
  131. }
  132. var pcr = parsePCR(buf, index);
  133. var outtime = self.output_time(pcr);
  134. if (outtime !== -1 && index !== startIndex) {
  135. var slice = buf.slice(startIndex, index);
  136. startIndex = index;
  137. return outputBefore(self, slice, outtime, self.packetSize, processNext);
  138. }
  139. index += 188;
  140. }
  141. if (startIndex !== 0) self.buffer = buf.slice(startIndex);
  142. cb();
  143. }
  144. processNext();
  145. };
  146. TsSmooth.prototype._flush = function(cb) {
  147. if (this.buffer.length) this.push(this.buffer); // TODO: use outputBefore() based on current stream speed?
  148. cb();
  149. };
  150. function tssmooth(options) {
  151. return new TsSmooth(options);
  152. }