generated from napi-rs/package-template
-
-
Notifications
You must be signed in to change notification settings - Fork 92
feat: support Lottie API #1177
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
feat: support Lottie API #1177
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -177,3 +177,5 @@ llvm-project-llvmorg-* | |
| .claude | ||
|
|
||
| *.code-workspace | ||
| /example/output.mp4 | ||
| /example/lottie_extracted | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| import { readFileSync, writeFileSync } from 'node:fs' | ||
| import { join } from 'node:path' | ||
|
|
||
|
|
||
| import { createCanvas, LottieAnimation } from '../index.js' | ||
| import { | ||
| VideoEncoder, | ||
| VideoFrame, | ||
| Mp4Muxer, | ||
| type EncodedVideoChunk, | ||
| type EncodedVideoChunkMetadata, | ||
| } from '@napi-rs/webcodecs' | ||
|
|
||
| const __dirname = new URL('.', import.meta.url).pathname | ||
|
|
||
| async function main() { | ||
| // Load the Lottie animation from extracted data | ||
| const animation = LottieAnimation.loadFromData(readFileSync(join(__dirname, 'LoopingCircless.json'), 'utf-8')) | ||
|
|
||
| console.log('Animation loaded:') | ||
| console.log(` Duration: ${animation.duration.toFixed(2)}s`) | ||
| console.log(` FPS: ${animation.fps}`) | ||
| console.log(` Frames: ${animation.frames}`) | ||
| console.log(` Size: ${animation.width}x${animation.height}`) | ||
| console.log(` Version: ${animation.version}`) | ||
|
|
||
| // Use original animation size (ensure dimensions are even for video codecs) | ||
| const encodedWidth = Math.round(animation.width) % 2 === 0 ? Math.round(animation.width) : Math.round(animation.width) + 1 | ||
| const encodedHeight = Math.round(animation.height) % 2 === 0 ? Math.round(animation.height) : Math.round(animation.height) + 1 | ||
|
|
||
| console.log(`\nOutput size: ${encodedWidth}x${encodedHeight}`) | ||
|
|
||
| // Create the canvas for rendering | ||
| const canvas = createCanvas(encodedWidth, encodedHeight) | ||
| const ctx = canvas.getContext('2d') | ||
|
|
||
| // Calculate frame duration in microseconds | ||
| const fps = animation.fps | ||
| const frameDurationUs = Math.round(1_000_000 / fps) | ||
| const totalFrames = Math.round(animation.frames) | ||
|
|
||
| // Collect all encoded chunks and metadata first (following webcodecs test pattern) | ||
| const videoChunks: EncodedVideoChunk[] = [] | ||
| const videoMetadatas: (EncodedVideoChunkMetadata | undefined)[] = [] | ||
|
|
||
| // Create video encoder | ||
| const encoder = new VideoEncoder({ | ||
| output: (chunk: EncodedVideoChunk, meta?: EncodedVideoChunkMetadata) => { | ||
| videoChunks.push(chunk) | ||
| videoMetadatas.push(meta) | ||
|
|
||
| const count = videoChunks.length | ||
| if (count % 30 === 0 || count === totalFrames) { | ||
| console.log(` Encoded ${count}/${totalFrames} frames`) | ||
| } | ||
| }, | ||
| error: (e: Error) => { | ||
| console.error('Encoder error:', e) | ||
| }, | ||
| }) | ||
|
|
||
| // Configure encoder for H.264 Baseline (no B-frames for smoother playback) | ||
| encoder.configure({ | ||
| codec: 'avc1.42001f', // H.264 Baseline Profile Level 3.1 | ||
| width: encodedWidth, | ||
| height: encodedHeight, | ||
| bitrate: 5_000_000, // 5 Mbps | ||
| framerate: fps, | ||
| latencyMode: 'realtime', // Disable B-frames for smoother sequential playback | ||
| }) | ||
|
|
||
| console.log('\nEncoding frames...') | ||
|
|
||
| // Render and encode each frame | ||
| for (let frameIndex = 0; frameIndex < totalFrames; frameIndex++) { | ||
| // Seek to exact frame for precise animation timing | ||
| animation.seekFrame(frameIndex) | ||
|
|
||
| // Clear the canvas with white background | ||
| ctx.fillStyle = '#ffffff' | ||
| ctx.fillRect(0, 0, encodedWidth, encodedHeight) | ||
|
|
||
| // Render the animation with destination rect for proper scaling | ||
| // Note: ctx.scale() doesn't affect Skottie rendering - must use dst rect | ||
| animation.render(ctx, { x: 0, y: 0, width: encodedWidth, height: encodedHeight }) | ||
|
|
||
| // Create a VideoFrame from the canvas | ||
| const timestamp = frameIndex * frameDurationUs | ||
| const frame = new VideoFrame(canvas, { | ||
| timestamp, | ||
| duration: frameDurationUs, | ||
| }) | ||
|
|
||
| // Encode the frame (request keyframe every 2 seconds) | ||
| const isKeyFrame = frameIndex % Math.round(fps * 2) === 0 | ||
| encoder.encode(frame, { keyFrame: isKeyFrame }) | ||
|
|
||
| // Close the frame to release resources | ||
| frame.close() | ||
| } | ||
|
|
||
| // Flush the encoder to ensure all frames are processed | ||
| console.log('\nFlushing encoder...') | ||
| await encoder.flush() | ||
| encoder.close() | ||
|
|
||
| console.log(`\nCollected ${videoChunks.length} chunks`) | ||
|
|
||
| // Now create the muxer and add all chunks | ||
| // Note: fastStart is not compatible with in-memory muxing | ||
| const muxer = new Mp4Muxer() | ||
|
|
||
| // Get codec description from the first keyframe's metadata | ||
| const description = videoMetadatas[0]?.decoderConfig?.description | ||
|
|
||
| // Add video track with the codec description (avcC box for H.264) | ||
| muxer.addVideoTrack({ | ||
| codec: 'avc1.42001f', | ||
| width: encodedWidth, | ||
| height: encodedHeight, | ||
| description, | ||
| }) | ||
|
|
||
| console.log('Muxing chunks...') | ||
|
|
||
| // Add all chunks to the muxer | ||
| for (let i = 0; i < videoChunks.length; i++) { | ||
| muxer.addVideoChunk(videoChunks[i], videoMetadatas[i]) | ||
| } | ||
|
|
||
| // Flush and finalize the muxer | ||
| console.log('Finalizing MP4...') | ||
| await muxer.flush() | ||
| const mp4Data = muxer.finalize() | ||
| muxer.close() | ||
|
|
||
| // Write to file | ||
| const outputPath = join(__dirname, 'output.mp4') | ||
| writeFileSync(outputPath, mp4Data) | ||
|
|
||
| console.log(`\nVideo saved to: ${outputPath}`) | ||
| console.log(`File size: ${(mp4Data.byteLength / 1024 / 1024).toFixed(2)} MB`) | ||
| } | ||
|
|
||
| main().catch(console.error) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is an extra empty line after the imports. Remove this blank line for consistency with the codebase formatting.