( id: string, filePath: string, time: number, fps: number, )
| 13 | } |
| 14 | |
| 15 | export async function getFrame( |
| 16 | id: string, |
| 17 | filePath: string, |
| 18 | time: number, |
| 19 | fps: number, |
| 20 | ) { |
| 21 | // Check if we already have a VideoFrameExtractor for this video |
| 22 | const extractorId = filePath + '-' + id; |
| 23 | let extractor = videoFrameExtractors.get(extractorId); |
| 24 | |
| 25 | const frameDuration = 1 / fps; |
| 26 | |
| 27 | /** |
| 28 | * Sometimes, HTMLVideoElement.duration is not accurate, which can lead to the |
| 29 | * requested time being greater than the duration. |
| 30 | * To prevent this, we clamp the time to the duration reported by the extractor. |
| 31 | */ |
| 32 | const duration = extractor?.getDuration(); |
| 33 | if (duration && time > duration) { |
| 34 | time = duration; |
| 35 | } |
| 36 | |
| 37 | const isOldFrame = |
| 38 | extractor && Math.abs(time - extractor.getLastTime()) < frameDuration / 2; |
| 39 | |
| 40 | // If time has not changed, return the last frame |
| 41 | if (extractor && isOldFrame) { |
| 42 | const lastFrame = extractor.getLastFrame(); |
| 43 | if (!lastFrame) { |
| 44 | throw new Error('No last frame'); |
| 45 | } |
| 46 | |
| 47 | return lastFrame; |
| 48 | } |
| 49 | |
| 50 | // If the video has skipped back we need to create a new extractor |
| 51 | if (extractor && time + frameDuration < extractor.getTime()) { |
| 52 | extractor.close(); |
| 53 | videoFrameExtractors.delete(extractorId); |
| 54 | extractor = undefined; |
| 55 | } |
| 56 | |
| 57 | // If the video has skipped forward we need to create a new extractor |
| 58 | if (extractor && time > extractor.getTime() + frameDuration * 1.5) { |
| 59 | extractor.close(); |
| 60 | videoFrameExtractors.delete(extractorId); |
| 61 | extractor = undefined; |
| 62 | } |
| 63 | |
| 64 | if (!extractor) { |
| 65 | extractor = new Mp4Parser(filePath, fps, time); |
| 66 | await extractor.start(); |
| 67 | videoFrameExtractors.set(extractorId, extractor); |
| 68 | } |
| 69 | |
| 70 | // Go to the frame that is closest to the requested time |
| 71 | return extractor.getNextFrame(); |
| 72 | } |
no test coverage detected