Skip to content

Commit

Permalink
Added calculateFrameCount() and calculateDuration(); close phoboslab#22
Browse files Browse the repository at this point in the history
  • Loading branch information
phoboslab committed Sep 3, 2014
1 parent 295bdb6 commit 2cf6a81
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 1 deletion.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,16 @@ player.stop();
// An 'onload' callback can be specified in the 'options' argument
var mpegLoaded = function( player ) {
console.log('Loaded', player);
}

// calculateFrameCount() and calculateDuration() can only be called
// after the mpeg has been fully loaded. So this callback is the ideal
// place to fetch this info
var frames = player.calculateFrameCount(),
duration = player.calculateDuration();

console.log('Duration: '+duration+' seconds ('+frames+' frames)');
};

var player = new jsmpeg('file.mpeg', {onload:mpegLoaded});

// If you don't use 'autoplay' and don't explicitly call .play(), you can get individual
Expand Down
25 changes: 25 additions & 0 deletions jsmpg.js
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,31 @@ jsmpeg.prototype.fillArray = function(a, value) {
}
};

jsmpeg.prototype.cachedFrameCount = 0;
jsmpeg.prototype.calculateFrameCount = function() {
if( !this.buffer || this.cachedFrameCount ) {
return this.cachedFrameCount;
}

// Remember the buffer position, so we can rewind to the beginning and
// reset to the current position afterwards
var currentPlaybackIndex = this.buffer.index,
frames = 0;

this.buffer.index = 0;
while( this.findStartCode(START_PICTURE) !== BitReader.NOT_FOUND ) {
frames++;
}
this.buffer.index = currentPlaybackIndex;

this.cachedFrameCount = frames;
return frames;
};

jsmpeg.prototype.calculateDuration = function() {
return this.calculateFrameCount() * (1/this.pictureRate);
};



// ----------------------------------------------------------------------------
Expand Down

0 comments on commit 2cf6a81

Please sign in to comment.