π₯ Make videos programmatically with React
lru map
Jonny Burgere43191eaea26
diff --git a/packages/astro-example/src/components/Counter.tsx b/packages/astro-example/src/components/Counter.tsxindex 27fee06259..6840832fc0 100644--- a/packages/astro-example/src/components/Counter.tsx+++ b/packages/astro-example/src/components/Counter.tsx@@ -1,37 +1,33 @@-import React, { useState } from "react";import "./Counter.css";import { Player } from "@remotion/player";+import { Gif } from "@remotion/gif";+import { Pumpkin } from "./LottieExample";const Comp: React.FC = () => {- return <div>Hello World</div>;+ return (+ <div>+ <Gif+ src="https://media.giphy.com/media/xT0GqH01ZyKwd3aT3G/giphy.gif"+ fit="cover"+ height={200}+ width={200}+ />+ <Pumpkin></Pumpkin>+ </div>+ );};-export default function Counter({- children,- count: initialCount,-}: {- children: JSX.Element;- count: number;-}) {- const [count, setCount] = useState(initialCount);- const add = () => setCount((i) => i + 1);- const subtract = () => setCount((i) => i - 1);-+export default function Counter() {return (<><Playercomponent={Comp}durationInFrames={100}- compositionWidth={100}- compositionHeight={100}+ compositionWidth={1000}+ compositionHeight={1000}fps={30}+ controls></Player>- <div className="counter">- <button onClick={subtract}>-</button>- <pre>{count}</pre>- <button onClick={add}>+</button>- </div>- <div className="counter-message">{children}</div></>);}diff --git a/packages/astro-example/src/components/LottieExample.tsx b/packages/astro-example/src/components/LottieExample.tsxnew file mode 100644index 0000000000..5d78f22ffb--- /dev/null+++ b/packages/astro-example/src/components/LottieExample.tsx@@ -0,0 +1,46 @@+import { Lottie } from "@remotion/lottie";+import { useEffect, useState } from "react";+import {+ AbsoluteFill,+ continueRender,+ delayRender,+ interpolate,+ useCurrentFrame,+ useVideoConfig,+} from "remotion";++export const Pumpkin = () => {+ const frame = useCurrentFrame();+ const { durationInFrames } = useVideoConfig();++ const animationDelay = 1;+ const animationInput = frame - animationDelay;+ const animationOpacity = interpolate(+ animationInput,+ [0, 5, durationInFrames - 20, durationInFrames],+ [0, 1, 1, 0]+ );++ const [animationData, setAnimationData] = useState(null);+ const [handle] = useState(() => delayRender());++ useEffect(() => {+ // Credits: https://lottiefiles.com/37789-scary-halloween-pumpkin+ fetch("https://assets2.lottiefiles.com/packages/lf20_c5izbrx1.json")+ .then((res) => res.json())+ .then((data) => {+ setAnimationData(data);+ continueRender(handle);+ });+ }, [handle]);++ if (!animationData) {+ return null;+ }++ return (+ <AbsoluteFill style={{ opacity: animationOpacity }}>+ <Lottie animationData={animationData} />+ </AbsoluteFill>+ );+};diff --git a/packages/gif/package.json b/packages/gif/package.jsonindex 7751884437..12fec28ba8 100644--- a/packages/gif/package.json+++ b/packages/gif/package.json@@ -32,7 +32,6 @@}},"dependencies": {- "lru_map": "0.4.1","remotion": "3.3.62"},"devDependencies": {diff --git a/packages/gif/rollup.config.js b/packages/gif/rollup.config.jsindex 10527602fd..145571d05a 100644--- a/packages/gif/rollup.config.js+++ b/packages/gif/rollup.config.js@@ -11,7 +11,7 @@ export default [sourcemap: false,},],- external: ['react', 'remotion', 'react/jsx-runtime', 'lru_map'],+ external: ['react', 'remotion', 'react/jsx-runtime'],plugins: [typescript({tsconfig: 'tsconfig-esm.json',diff --git a/packages/gif/src/gif-cache.ts b/packages/gif/src/gif-cache.tsindex 9ecfbd8a0e..88ff02ef31 100644--- a/packages/gif/src/gif-cache.ts+++ b/packages/gif/src/gif-cache.ts@@ -1,5 +1,5 @@-import {LRUMap} from 'lru_map';+import {QuickLRU} from './lru/index';import type {GifState} from './props';-export const volatileGifCache = new LRUMap<string, GifState>(30);+export const volatileGifCache = new QuickLRU<string, GifState>({maxSize: 30});export const manuallyManagedGifCache = new Map<string, GifState>();diff --git a/packages/gif/src/lru/index.ts b/packages/gif/src/lru/index.tsnew file mode 100644index 0000000000..f8e493cb19--- /dev/null+++ b/packages/gif/src/lru/index.ts@@ -0,0 +1,363 @@+export interface Options<KeyType, ValueType> {+ /**+ The maximum number of milliseconds an item should remain in the cache.++ @default Infinity++ By default, `maxAge` will be `Infinity`, which means that items will never expire.+ Lazy expiration upon the next write or read call.++ Individual expiration of an item can be specified by the `set(key, value, maxAge)` method.+ */+ readonly maxAge?: number;++ /**+ The maximum number of items before evicting the least recently used items.+ */+ readonly maxSize: number;++ /**+ Called right before an item is evicted from the cache.++ Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`).+ */+ onEviction?: (key: KeyType, value: ValueType) => void;+}++type MapValue<ValueType> = {+ value: ValueType;+ expiry?: number;+};++export class QuickLRU<KeyType, ValueType>+ implements Iterable<[KeyType, ValueType]>+{+ /**+ The maximum number of milliseconds an item should remain in the cache.++ @default Infinity++ By default, `maxAge` will be `Infinity`, which means that items will never expire.+ Lazy expiration upon the next write or read call.++ Individual expiration of an item can be specified by the `set(key, value, maxAge)` method.+ */+ maxAge: number;++ /**+ The maximum number of items before evicting the least recently used items.+ */+ maxSize: number;++ /**+ Called right before an item is evicted from the cache.++ Useful for side effects or for items like object URLs that need explicit cleanup (`revokeObjectURL`).+ */+ onEviction?: (key: KeyType, value: ValueType) => void;++ private _size: number;+ private cache: Map<KeyType, MapValue<ValueType>>;+ private oldCache: Map<KeyType, MapValue<ValueType>>;++ /**+ Simple ["Least Recently Used" (LRU) cache](https://en.m.wikipedia.org/wiki/Cache_replacement_policies#Least_Recently_Used_.28LRU.29).++ The instance is an [`Iterable`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Iteration_protocols) of `[key, value]` pairs so you can use it directly in a [`forβ¦of`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for...of) loop.++ @example+ ```+ import { QuickLRU } from 'quick-lru-ts';++ const lru = new QuickLRU({maxSize: 1000});++ lru.set('π¦', 'π');++ lru.has('π¦');+ //=> true++ lru.get('π¦');+ //=> 'π'+ ```+ */+ constructor(options: Options<KeyType, ValueType>) {+ if (!(options.maxSize && options.maxSize > 0)) {+ throw new TypeError('`maxSize` must be a number greater than 0');+ }++ if (typeof options.maxAge === 'number' && options.maxAge === 0) {+ throw new TypeError('`maxAge` must be a number greater than 0');+ }++ this.maxSize = options.maxSize;+ this.maxAge = options.maxAge || Number.POSITIVE_INFINITY;+ this.onEviction = options.onEviction;+ this.cache = new Map();+ this.oldCache = new Map();+ this._size = 0;+ }++ private _emitEvictions(+ cache: Map<KeyType, MapValue<ValueType>> | [KeyType, MapValue<ValueType>][]+ ) {+ if (typeof this.onEviction !== 'function') {+ return;+ }++ for (const [key, item] of cache) {+ this.onEviction(key, item.value);+ }+ }++ private _deleteIfExpired(+ key: KeyType,+ item: MapValue<ValueType> | undefined+ ) {+ if (item === undefined) return true;+ if (typeof item.expiry === 'number' && item.expiry <= Date.now()) {+ if (typeof this.onEviction === 'function') {+ this.onEviction(key, item.value);+ }++ return this.delete(key);+ }++ return false;+ }++ private _getOrDeleteIfExpired(key: KeyType, item: MapValue<ValueType>) {+ const deleted = this._deleteIfExpired(key, item);+ if (deleted === false) {+ return item.value;+ }+ }++ private _getItemValue(key: KeyType, item: MapValue<ValueType> | undefined) {+ if (item === undefined) return undefined;+ return item.expiry ? this._getOrDeleteIfExpired(key, item) : item.value;+ }++ private _peek(key: KeyType, cache: Map<KeyType, MapValue<ValueType>>) {+ const item = cache.get(key);++ return this._getItemValue(key, item);+ }++ private _set(key: KeyType, value: MapValue<ValueType>) {+ this.cache.set(key, value);+ this._size++;++ if (this._size >= this.maxSize) {+ this._size = 0;+ this._emitEvictions(this.oldCache);+ this.oldCache = this.cache;+ this.cache = new Map();+ }+ }++ private _moveToRecent(key: KeyType, item: MapValue<ValueType>) {+ this.oldCache.delete(key);+ this._set(key, item);+ }++ private *_entriesAscending() {+ for (const item of this.oldCache) {+ const [key, value] = item;+ if (!this.cache.has(key)) {+ const deleted = this._deleteIfExpired(key, value);+ if (deleted === false) {+ yield item;+ }+ }+ }++ for (const item of this.cache) {+ const [key, value] = item;+ const deleted = this._deleteIfExpired(key, value);+ if (deleted === false) {+ yield item;+ }+ }+ }++ /**+ Get an item.++ @returns The stored item or `undefined`.+ */+ get(key: KeyType): ValueType | undefined {+ if (this.cache.has(key)) {+ const item = this.cache.get(key);++ return this._getItemValue(key, item);+ }++ if (this.oldCache.has(key)) {+ const item = this.oldCache.get(key);+ if (this._deleteIfExpired(key, item) === false) {+ this._moveToRecent(key, item as MapValue<ValueType>);+ return (item as MapValue<ValueType>).value;+ }+ }+ }++ set(+ key: KeyType,+ value: ValueType,+ {maxAge = this.maxAge}: {maxAge?: number} = {}+ ) {+ const expiry =+ typeof maxAge === 'number' && maxAge !== Number.POSITIVE_INFINITY+ ? Date.now() + maxAge+ : undefined;+ if (this.cache.has(key)) {+ this.cache.set(key, {+ value,+ expiry,+ });+ } else {+ this._set(key, {value, expiry});+ }+ }++ has(key: KeyType) {+ if (this.cache.has(key)) {+ return !this._deleteIfExpired(key, this.cache.get(key));+ }++ if (this.oldCache.has(key)) {+ return !this._deleteIfExpired(key, this.oldCache.get(key));+ }++ return false;+ }++ peek(key: KeyType) {+ if (this.cache.has(key)) {+ return this._peek(key, this.cache);+ }++ if (this.oldCache.has(key)) {+ return this._peek(key, this.oldCache);+ }+ }++ delete(key: KeyType) {+ const deleted = this.cache.delete(key);+ if (deleted) {+ this._size--;+ }++ return this.oldCache.delete(key) || deleted;+ }++ clear() {+ this.cache.clear();+ this.oldCache.clear();+ this._size = 0;+ }++ resize(maxSize: number) {+ if (!(maxSize && maxSize > 0)) {+ throw new TypeError('`maxSize` must be a number greater than 0');+ }++ const items = [...this._entriesAscending()];+ const removeCount = items.length - maxSize;+ if (removeCount < 0) {+ this.cache = new Map(items);+ this.oldCache = new Map();+ this._size = items.length;+ } else {+ if (removeCount > 0) {+ this._emitEvictions(items.slice(0, removeCount));+ }++ this.oldCache = new Map(items.slice(removeCount));+ this.cache = new Map();+ this._size = 0;+ }++ this.maxSize = maxSize;+ }++ *keys() {+ for (const [key] of this) {+ yield key;+ }+ }++ *values() {+ for (const [, value] of this) {+ yield value;+ }+ }++ *[Symbol.iterator](): IterableIterator<[KeyType, ValueType]> {+ for (const item of this.cache) {+ const [key, value] = item;+ const deleted = this._deleteIfExpired(key, value);+ if (deleted === false) {+ yield [key, value.value];+ }+ }++ for (const item of this.oldCache) {+ const [key, value] = item;+ if (!this.cache.has(key)) {+ const deleted = this._deleteIfExpired(key, value);+ if (deleted === false) {+ yield [key, value.value];+ }+ }+ }+ }++ /**+ Iterable for all entries, starting with the newest (descending in recency).+ */+ *entriesDescending(): IterableIterator<[KeyType, ValueType]> {+ let items = [...this.cache];+ for (let i = items.length - 1; i >= 0; --i) {+ const item = items[i];+ const [key, value] = item;+ const deleted = this._deleteIfExpired(key, value);+ if (deleted === false) {+ yield [key, value.value];+ }+ }++ items = [...this.oldCache];+ for (let i = items.length - 1; i >= 0; --i) {+ const item = items[i];+ const [key, value] = item;+ if (!this.cache.has(key)) {+ const deleted = this._deleteIfExpired(key, value);+ if (deleted === false) {+ yield [key, value.value];+ }+ }+ }+ }++ *entriesAscending() {+ for (const [key, value] of this._entriesAscending()) {+ yield [key, value.value];+ }+ }++ get size(): number {+ if (!this._size) {+ return this.oldCache.size;+ }++ let oldCacheSize = 0;+ for (const key of this.oldCache.keys()) {+ if (!this.cache.has(key)) {+ oldCacheSize++;+ }+ }++ return Math.min(this._size + oldCacheSize, this.maxSize);+ }+}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex fcc9df73da..5d138606e9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -573,7 +573,6 @@ importers:'@types/react-dom': 18.0.10esbuild: 0.16.12eslint: 8.25.0- lru_map: 0.4.1prettier: 2.6.2prettier-plugin-organize-imports: ^2.3.4react: 18.0.0@@ -583,7 +582,6 @@ importers:typescript: ^4.7.0webpack: 5.74.0dependencies:- lru_map: 0.4.1remotion: link:../coredevDependencies:'@jonny/eslint-config': 3.0.266_t54va6jeo5lf3vtqih5uiyrm5e@@ -17271,10 +17269,6 @@ packages:dependencies:yallist: 4.0.0- /lru_map/0.4.1:- resolution: {integrity: sha512-I+lBvqMMFfqaV8CJCISjI3wbjmwVu/VyOoU7+qtu9d7ioW5klMgsTTiUOUp+DJvfTTzKXoPbyC6YfgkNcyPSOg==}- dev: false-/lz-string/1.4.4:resolution: {integrity: sha512-0ckx7ZHRPqb0oUm8zNr+90mtf9DQB60H1wMCjBtfi62Kl3a7JbHob6gA2bC+xRvZoOL+1hzUK8jeuEIQE8svEQ==}hasBin: true