decoder.js 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. JSMpeg.Decoder.Base = (function(){ "use strict";
  2. var BaseDecoder = function(options) {
  3. this.destination = null;
  4. this.canPlay = false;
  5. this.collectTimestamps = !options.streaming;
  6. this.timestamps = [];
  7. this.timestampIndex = 0;
  8. this.startTime = 0;
  9. this.decodedTime = 0;
  10. Object.defineProperty(this, 'currentTime', {get: this.getCurrentTime});
  11. };
  12. BaseDecoder.prototype.connect = function(destination) {
  13. this.destination = destination;
  14. };
  15. BaseDecoder.prototype.write = function(pts, buffers) {
  16. if (this.collectTimestamps) {
  17. if (this.timestamps.length === 0) {
  18. this.startTime = pts;
  19. this.decodedTime = pts;
  20. }
  21. this.timestamps.push({index: this.bits.byteLength << 3, time: pts});
  22. }
  23. this.bits.write(buffers);
  24. this.canPlay = true;
  25. };
  26. BaseDecoder.prototype.seek = function(time) {
  27. if (!this.collectTimestamps) {
  28. return;
  29. }
  30. this.timestampIndex = 0;
  31. for (var i = 0; i < this.timestamps.length; i++) {
  32. if (this.timestamps[i].time > time) {
  33. break;
  34. }
  35. this.timestampIndex = i;
  36. }
  37. var ts = this.timestamps[this.timestampIndex];
  38. if (ts) {
  39. this.bits.index = ts.index;
  40. this.decodedTime = ts.time;
  41. }
  42. else {
  43. this.bits.index = 0;
  44. this.decodedTime = this.startTime;
  45. }
  46. };
  47. BaseDecoder.prototype.decode = function() {
  48. this.advanceDecodedTime(0);
  49. };
  50. BaseDecoder.prototype.advanceDecodedTime = function(seconds) {
  51. if (this.collectTimestamps) {
  52. var newTimestampIndex = -1;
  53. for (var i = this.timestampIndex; i < this.timestamps.length; i++) {
  54. if (this.timestamps[i].index > this.bits.index) {
  55. break;
  56. }
  57. newTimestampIndex = i;
  58. }
  59. // Did we find a new PTS, different from the last? If so, we don't have
  60. // to advance the decoded time manually and can instead sync it exactly
  61. // to the PTS.
  62. if (
  63. newTimestampIndex !== -1 &&
  64. newTimestampIndex !== this.timestampIndex
  65. ) {
  66. this.timestampIndex = newTimestampIndex;
  67. this.decodedTime = this.timestamps[this.timestampIndex].time;
  68. return;
  69. }
  70. }
  71. this.decodedTime += seconds;
  72. };
  73. BaseDecoder.prototype.getCurrentTime = function() {
  74. return this.decodedTime;
  75. };
  76. return BaseDecoder;
  77. })();