### Install Dependencies and Start Development Server Source: https://github.com/augani/openreel-video/blob/main/CONTRIBUTING.md Follow these steps to set up the development environment. Ensure Node.js 18+ and pnpm are installed. ```bash git clone https://github.com/Augani/openreel-video.git cd openreel-video pnpm install pnpm dev # Open browser to http://localhost:5173 ``` -------------------------------- ### Playback Controller Initialization and Usage Example Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Demonstrates the complete lifecycle of using the Playback Controller, from initialization and event listener setup to starting, controlling playback rate, seeking, and pausing. ```typescript // Initialize const videoEngine = new VideoEngine(); const audioEngine = new AudioEngine(); const controller = new PlaybackController({ frameRate: 30 }); await videoEngine.initialize(); await audioEngine.initialize(); await controller.initialize(videoEngine, audioEngine); // Setup display const canvas = document.getElementById('video') as HTMLCanvasElement; controller.setDisplayCanvas(canvas); // Add listeners controller.addEventListener('timeupdate', (event) => { updateTimecode(event.time); }); controller.addEventListener('ended', () => { showMessage('Video finished'); }); // Start playback await controller.play(project, 0); // Later: change speed controller.setPlaybackRate(0.5); // Later: seek to different time await controller.seek(project, 10); // Later: pause controller.pause(); ``` -------------------------------- ### Clone and Run OpenReel Video Locally Source: https://github.com/augani/openreel-video/blob/main/README.md Follow these steps to clone the repository, install dependencies, and start the development server. Requires Node.js 18+. ```bash # Clone the repository git clone https://github.com/Augani/openreel-video.git cd openreel-video # Install dependencies (requires Node.js 18+) pnpm install # Start development server pnpm dev # Open http://localhost:5173 ``` -------------------------------- ### Audio Engine Initialization Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Demonstrates how to get an instance of the Audio Engine and initialize it for use. ```APIDOC ## Singleton Access ```typescript import { getAudioEngine, initializeAudioEngine } from '@openreel/core'; const engine = getAudioEngine(); await engine.initialize(); ``` ``` -------------------------------- ### Build and Preview OpenReel Video for Production Source: https://github.com/augani/openreel-video/blob/main/README.md Commands to build the project for production and start a preview server. ```bash pnpm build pnpm preview ``` -------------------------------- ### Start Playback Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Start playback of a project from a specified time. If startTime is not provided, playback begins from the current time. ```typescript await controller.play(project, 0); // Start from beginning ``` -------------------------------- ### Video Engine Initialization and Access Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md This snippet shows how to import, get an instance of, and initialize the Video Engine. ```APIDOC ## Singleton Access ```typescript import { getVideoEngine, initializeVideoEngine } from '@openreel/core'; const engine = getVideoEngine(); await engine.initialize(); ``` ``` -------------------------------- ### Initialize and Access Audio Engine Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Demonstrates how to import, initialize, and get an instance of the Audio Engine. Ensure the engine is awaited after initialization. ```typescript import { getAudioEngine, initializeAudioEngine } from '@openreel/core'; const engine = getAudioEngine(); await engine.initialize(); ``` -------------------------------- ### Text Animation Preset Example Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/animation-engine.md Example of applying a 'typewriter' text animation preset to a TextClip. Requires specifying animation type, preset, duration, and delay. ```typescript const textClip: TextClip = { ...clip, animation: { type: 'entrance', preset: 'typewriter', duration: 3, delay: 0.5, }, }; ``` -------------------------------- ### InverseActionGenerator.generateInverse Example Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/action-executor.md Example demonstrating the generation of an inverse action. This specific example shows how an 'add clip' action's inverse would be a 'delete clip' action. ```typescript // Original action added a clip const addAction: Action = { type: 'clip/add', params: { clipId: 'clip-1', trackId: 'track-1' }, }; // Generated inverse removes it const deleteAction = InverseActionGenerator.generateInverse( addAction, stateBefore, stateAfter, ); // deleteAction.type === 'clip/delete' ``` -------------------------------- ### Get and Initialize Export Engine Instance Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Demonstrates how to import and obtain the singleton instance of the Export Engine and initialize it before use. ```typescript import { getExportEngine } from '@openreel/core'; const engine = getExportEngine(); await engine.initialize(); ``` -------------------------------- ### play Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Starts playback of a project from a specified time, defaulting to the current playback time. ```APIDOC ## play ### Description Starts playback from the specified time (default: current time). ### Signature ```typescript async play(project: Project, startTime?: number): Promise ``` ### Parameters #### project (Project) - Required Project to play. #### startTime (number) - Optional Start time in seconds. Defaults to the current playback time. ### Example ```typescript await controller.play(project, 0); // Start from beginning ``` ``` -------------------------------- ### Export Engine Initialization and Usage Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Demonstrates how to get the singleton instance of the Export Engine and initialize it. This is the entry point for using export functionalities. ```APIDOC ## Singleton Instance Use `getExportEngine()` to get the singleton instance: ```typescript import { getExportEngine } from '@openreel/core'; const engine = getExportEngine(); await engine.initialize(); ``` ``` -------------------------------- ### Media Import Example Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Demonstrates how to import a media file using the MediaBunnyEngine, including options for thumbnail and waveform generation. Logs the media ID and duration upon successful import. ```typescript const file = new File([...], 'video.mp4', { type: 'video/mp4' }); const result = await engine.importMedia(file, { generateThumbnail: true, generateWaveform: true, thumbnailSize: { width: 200, height: 112 }, }); if (result.success) { console.log(`Media imported: ${result.mediaId}`); console.log(`Duration: ${result.media?.duration}s`); } ``` -------------------------------- ### ActionSerializer.serialize Example Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/action-executor.md Example of serializing an action and storing it in local storage. Ensure the action object is defined elsewhere. ```typescript const json = ActionSerializer.serialize(action); localStorage.setItem('action', json); ``` -------------------------------- ### getCodecRecommendations() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Gets codec recommendations based on the provided device profile. ```APIDOC ## getCodecRecommendations() ### Description Gets codec recommendations based on device capabilities. ### Parameters #### Request Body - **profile** (DeviceProfile) - Required - Device profile from getDeviceProfile() ### Returns `CodecRecommendation[]` - Prioritized codec recommendations ### CodecRecommendation ```typescript interface CodecRecommendation { codec: 'h264' | 'h265' | 'vp9' | 'av1'; label: string; recommended: boolean; // True for top choice reason: string; speedRating: 'fast' | 'medium' | 'slow' | 'very-slow'; qualityRating: 'good' | 'better' | 'best'; } ``` ### Example ```typescript const recommendations = getCodecRecommendations(profile); // Top recommendation for this device const topChoice = recommendations.find(r => r.recommended); console.log(`Recommended: ${topChoice.codec} (${topChoice.speedRating})`); // All recommendations with reasons recommendations.forEach(r => { console.log(`${r.codec}: ${r.reason}`); }); ``` ``` -------------------------------- ### Get Codec Recommendations Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Gets prioritized codec recommendations based on a provided device profile. Use this to determine the best codec for a given device's capabilities. ```typescript const recommendations = getCodecRecommendations(profile); // Top recommendation for this device const topChoice = recommendations.find(r => r.recommended); console.log(`Recommended: ${topChoice.codec} (${topChoice.speedRating})`); // All recommendations with reasons recommendations.forEach(r => { console.log(`${r.codec}: ${r.reason}`); }); ``` -------------------------------- ### Project Manager Usage Example Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/storage-engine.md Demonstrates how to use the ProjectSerializer with an IStorageEngine to save, load, export, and import projects. Includes error handling and validation. ```typescript import { ProjectSerializer, } from '@openreel/core'; class ProjectManager { private serializer: ProjectSerializer; constructor(storage: IStorageEngine) { this.serializer = new ProjectSerializer(storage); } async saveProject(project: Project): Promise { try { await this.serializer.saveProject(project); console.log(`Saved: ${project.name}`); } catch (error) { console.error('Save failed:', error); throw error; } } async loadProject(id: string): Promise { try { const project = await this.serializer.loadProject(id); if (!project) { console.warn(`Project not found: ${id}`); return null; } console.log(`Loaded: ${project.name}`); return project; } catch (error) { console.error('Load failed:', error); return null; } } exportProject(project: Project, format: 'json' | 'json-meta' = 'json'): string { if (format === 'json-meta') { return this.serializer.exportToJsonWithMetadata( project, `Project export from ${new Date().toISOString()}` ); } return this.serializer.exportToJson(project); } async importProject(json: string): Promise { try { const validation = this.serializer.validateProjectJson(json); if (!validation.valid) { console.error('Invalid project file:', validation.errors); return null; } if (validation.warnings.length > 0) { console.warn('Import warnings:', validation.warnings); } const project = this.serializer.importFromJson(json); console.log(`Imported: ${project.name}`); return project; } catch (error) { console.error('Import failed:', error); return null; } } async deleteProject(id: string): Promise { // Implementation depends on storage backend return true; } } ``` -------------------------------- ### Conventional Commits Examples Source: https://github.com/augani/openreel-video/blob/main/CONTRIBUTING.md Examples of commit messages adhering to the conventional commits specification for clarity and automation. ```git feat: add crossfade transition effect fix: resolve timeline scrubbing lag docs: update API documentation refactor: simplify video processing pipeline test: add tests for audio mixer perf: optimize waveform rendering ``` -------------------------------- ### Create Git Feature Branches Source: https://github.com/augani/openreel-video/blob/main/CONTRIBUTING.md Examples for creating Git branches for different types of work, following a consistent naming convention. ```bash # Feature branch git checkout -b feat/add-transition-effects # Bug fix branch git checkout -b fix/timeline-scroll-bug # Documentation git checkout -b docs/update-contributing-guide ``` -------------------------------- ### Get Singleton Engine Instances Source: https://github.com/augani/openreel-video/blob/main/_autodocs/README.md Import and retrieve singleton instances for video, audio, and export engines. These instances should be created once and reused throughout the application. ```typescript import { getVideoEngine, getAudioEngine, getExportEngine, getMediaEngine, getGSAPEngine, getDeviceProfile, } from '@openreel/core'; // All singletons - create once, reuse const videoEngine = getVideoEngine(); const audioEngine = getAudioEngine(); const exportEngine = getExportEngine(); ``` -------------------------------- ### Handle UNSUPPORTED_CODEC Source: https://github.com/augani/openreel-video/blob/main/_autodocs/errors.md Example of checking device capabilities for supported codecs and falling back to 'h264' if a desired codec like 'av1' is not available. ```typescript import { getExportEngine } from '@openreel/core'; const engine = getExportEngine(); const caps = engine.getDeviceCapabilities(); if (!caps.supportedCodecs.includes('av1')) { settings.codec = 'h264'; } ``` -------------------------------- ### Detect Device Capabilities and Codec Recommendations Source: https://github.com/augani/openreel-video/blob/main/_autodocs/README.md Retrieves the device's profile and gets recommended video codecs based on its capabilities. Useful for optimizing exports. ```typescript import { getDeviceProfile, getCodecRecommendations } from '@openreel/core'; const profile = await getDeviceProfile(); console.log(`Device Tier: ${profile.overallTier}`); const recommendations = getCodecRecommendations(profile); const bestCodec = recommendations[0].codec; // Top choice for device ``` -------------------------------- ### TypeScript Interface and Function Example Source: https://github.com/augani/openreel-video/blob/main/CONTRIBUTING.md Demonstrates correct TypeScript practices, including using interfaces for object shapes and avoiding 'any'. ```typescript interface VideoClip { id: string; duration: number; startTime: number; } function processClip(clip: VideoClip): ProcessedClip { if (!clip.id) { throw new Error('Clip ID is required'); } return { ...clip, processed: true, }; } ``` ```typescript // ❌ Avoid function processClip(clip: any) { console.log('Processing...'); // Remove debug logs const result = clip; // Unclear what's happening return result; } ``` -------------------------------- ### GSAP Animation Engine Constructor Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/animation-engine.md Initializes the GSAP Animation Engine. No specific setup is required beyond instantiating the class. ```typescript constructor() ``` -------------------------------- ### Get Quality Preset for Device Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Recommends an export quality preset that matches the device's capabilities. Use this to ensure optimal export settings for the user's hardware. ```typescript const preset = getQualityPresetForDevice(profile); // { id: '1080p-web', width: 1920, height: 1080, bitrate: 5000, frameRate: 30 } ``` -------------------------------- ### initialize() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Initializes the video engine, loading MediaBunny and setting up rendering infrastructure. ```APIDOC ## initialize() ### Description Initializes the video engine, loading MediaBunny and setting up rendering infrastructure. ### Method `async initialize(): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Throws - **Error**: When required libraries fail to load ``` -------------------------------- ### Get Sample Rate Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Gets the current sample rate of the audio engine in Hz. ```typescript getSampleRate(): number ``` -------------------------------- ### Initialize and Access Media Engine Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Demonstrates how to import, initialize, and access the Media Engine singleton. Ensure the engine is initialized before use. ```typescript import { getMediaEngine, initializeMediaEngine } from '@openreel/core'; const engine = getMediaEngine(); await engine.initialize(); ``` -------------------------------- ### initialize Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Initializes the playback controller with the provided video and audio render engines. ```APIDOC ## initialize ### Description Initializes the playback controller with render engines. ### Signature ```typescript async initialize(videoEngine: VideoEngine, audioEngine: AudioEngine): Promise ``` ### Parameters #### videoEngine (VideoEngine) - Required Video rendering engine. #### audioEngine (AudioEngine) - Required Audio rendering engine. ### Example ```typescript const videoEngine = new VideoEngine(); const audioEngine = new AudioEngine(); await videoEngine.initialize(); await audioEngine.initialize(); const controller = new PlaybackController(); await controller.initialize(videoEngine, audioEngine); ``` ``` -------------------------------- ### ActionSerializer.deserialize Example Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/action-executor.md Example of deserializing a JSON string into an action object. The 'json' variable should contain a valid action JSON string. ```typescript const action = ActionSerializer.deserialize(json); ``` -------------------------------- ### initialize() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Initializes the audio engine and creates the audio context. This method should be called before any other audio operations. ```APIDOC ## initialize() ### Description Initializes the audio engine and creates the audio context. ### Method async initialize(): Promise ### Throws - **Error**: When AudioContext creation fails ### Example ```typescript const engine = new AudioEngine(); await engine.initialize(); ``` ``` -------------------------------- ### Constructor Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Creates a new PlaybackController instance with optional configuration for frame rate and real-time audio. ```APIDOC ## Constructor ### Description Creates a new PlaybackController instance. ### Signature ```typescript constructor(config?: Partial) ``` ### Parameters #### config (PlaybackConfig) Optional configuration object. **PlaybackConfig:** ```typescript interface PlaybackConfig { frameRate: number; // default: 30 useRealtimeAudio: boolean; // default: true targetFrameTime: number; // ms, calculated from frameRate } ``` ### Example ```typescript const controller = new PlaybackController({ frameRate: 60, useRealtimeAudio: true, }); ``` ``` -------------------------------- ### getCurrentTime() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Gets the current playback time in seconds. ```APIDOC ## getCurrentTime() ### Description Returns the current playback time in seconds. ### Method Signature ```typescript getCurrentTime(): number ``` ### Return Value - **number** - The current playback time in seconds. ``` -------------------------------- ### getSampleRate Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Gets the current sample rate of the audio engine. ```APIDOC ## getSampleRate() ### Description Gets the current sample rate. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```typescript getSampleRate(): number ``` ### Response #### Success Response (number) - Sample rate in Hz ``` -------------------------------- ### Instantiate AudioEngine with Configuration Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Create a new AudioEngine instance with custom configuration options like sample rate, channels, and FFT size. ```typescript const engine = new AudioEngine({ sampleRate: 48000, channels: 2, fftSize: 2048, }); ``` -------------------------------- ### initializeGPUCompositor() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Initializes GPU compositing for hardware-accelerated rendering. ```APIDOC ## initializeGPUCompositor(width: number, height: number) ### Description Initializes GPU compositing for hardware-accelerated rendering. ### Method `async initializeGPUCompositor(width: number, height: number): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **width** (number) - Required - Compositor output width - **height** (number) - Required - Compositor output height ``` -------------------------------- ### Get Full History Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/action-executor.md Retrieves the complete array of all history entries. ```typescript getHistory(): HistoryEntry[] ``` -------------------------------- ### getClipEndTime Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Calculates the end time of a clip based on its start time and duration. ```APIDOC ## getClipEndTime() ### Description Calculates the end time of a clip. ### Signature ```typescript function getClipEndTime(clip: Clip): number ``` ``` -------------------------------- ### initialize() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Initializes the media engine and loads the MediaBunny library. This method should be called before using other engine functionalities. ```APIDOC ## initialize() ### Description Initializes the media engine and loads MediaBunny library. ### Method `async initialize(): Promise` ### Parameters None ### Throws - **Error**: When MediaBunny fails to load. ``` -------------------------------- ### Get Gap Between Clips Function Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Calculates the gap in seconds between two sequential clips. ```typescript function getGapBetweenClips(clip1: Clip, clip2: Clip): number ``` -------------------------------- ### getQualityPresetForDevice() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Recommends an export quality preset that matches the device's capabilities. ```APIDOC ## getQualityPresetForDevice() ### Description Recommends quality preset matching device capabilities. ### Returns `ExportPreset` - Preset optimized for device ### Example ```typescript const preset = getQualityPresetForDevice(profile); // { id: '1080p-web', width: 1920, height: 1080, bitrate: 5000, frameRate: 30 } ``` ``` -------------------------------- ### Initialize PlaybackController Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Initialize the playback controller with video and audio rendering engines. Ensure engines are initialized before passing them to the controller. ```typescript const videoEngine = new VideoEngine(); const audioEngine = new AudioEngine(); await videoEngine.initialize(); await audioEngine.initialize(); const controller = new PlaybackController(); await controller.initialize(videoEngine, audioEngine); ``` -------------------------------- ### Get Clip End Time Function Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Calculates and returns the end time of a given clip. ```typescript function getClipEndTime(clip: Clip): number ``` -------------------------------- ### Instantiate PlaybackController Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Create a new PlaybackController instance with optional configuration. The frameRate defaults to 30 and useRealtimeAudio defaults to true. ```typescript const controller = new PlaybackController({ frameRate: 60, useRealtimeAudio: true, }); ``` -------------------------------- ### Handle ENCODER_INIT_FAILED Error Source: https://github.com/augani/openreel-video/blob/main/_autodocs/errors.md Example of how to catch and handle an 'ENCODER_INIT_FAILED' error during video export, with a fallback to the H.264 codec. ```typescript const result = await engine.exportVideo(project, settings); if (result.error?.code === 'ENCODER_INIT_FAILED') { console.error('Encoder initialization failed'); // Fall back to H.264 settings.codec = 'h264'; } ``` -------------------------------- ### Get Audio Context Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Retrieves the Web Audio API AudioContext instance. Returns null if the context is not available. ```typescript getAudioContext(): AudioContext | null ``` -------------------------------- ### initializeGPUForExport() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Initializes GPU resources for hardware-accelerated video export. Returns true if successful, false otherwise. ```APIDOC ## initializeGPUForExport(width: number, height: number) ### Description Initializes GPU resources for hardware-accelerated export. ### Method `async initializeGPUForExport(width: number, height: number): Promise` ### Parameters #### Path Parameters - **width** (number) - Required - Output video width in pixels - **height** (number) - Required - Output video height in pixels ### Throws - **Error**: When GPU initialization fails. ### Returns - **boolean**: True if GPU initialization succeeded, false otherwise ### Example ```typescript const gpuReady = await engine.initializeGPUForExport(1920, 1080); if (gpuReady) { console.log("GPU acceleration available"); } ``` ``` -------------------------------- ### AudioEngine Constructor Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Creates a new AudioEngine instance with optional configuration for sample rate, channels, and FFT size. ```APIDOC ## Constructor AudioEngine ### Description Creates a new AudioEngine instance with optional configuration. ### Parameters #### Path Parameters - **config** (Partial) - Optional - Audio engine configuration ### Request Example ```typescript const engine = new AudioEngine({ sampleRate: 48000, channels: 2, fftSize: 2048, }); ``` ``` -------------------------------- ### React Component with TypeScript Props Source: https://github.com/augani/openreel-video/blob/main/CONTRIBUTING.md Example of a well-structured React component using TypeScript for props and `useCallback` for event handlers. ```typescript interface TimelineProps { tracks: Track[]; onClipSelect: (clipId: string) => void; } export const Timeline: React.FC = ({ tracks, onClipSelect }) => { const handleClick = useCallback((id: string) => { onClipSelect(id); }, [onClipSelect]); return (
{tracks.map(track => ( ))}
); }; ``` -------------------------------- ### isInitialized() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Checks if the audio engine has been successfully initialized. ```APIDOC ## isInitialized() ### Description Checks if the audio engine is initialized. ### Method isInitialized(): boolean ### Returns - **boolean**: True if the engine is initialized, false otherwise. ``` -------------------------------- ### initialize() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Initializes the export engine and loads necessary dependencies. This method must be called before other operations. ```APIDOC ## initialize() ### Description Initializes the export engine and loads required dependencies (MediaBunny, video and audio engines). ### Method `async initialize(): Promise` ### Throws - **Error**: When initialization fails due to missing dependencies. ### Example ```typescript const engine = new ExportEngine(); await engine.initialize(); ``` ``` -------------------------------- ### Get Playback Statistics Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Retrieves performance statistics for the current playback. Use this to monitor frame rates and dropped frames. ```typescript const stats = controller.getPlaybackStats(); console.log(`Average frame time: ${stats.averageFrameTime.toFixed(2)}ms`); console.log(`Dropped frames: ${stats.droppedFrames}`); ``` -------------------------------- ### moveClip() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Moves an existing clip to a new start time or a different track on the timeline, considering the zoom level for snapping. ```APIDOC ## moveClip() Moves a clip to a new position or track. ### Method Signature ```typescript async moveClip( timeline: Timeline, params: MoveClipParams, pixelsPerSecond?: number, ): Promise ``` **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | timeline | Timeline | Yes | Timeline containing the clip | | params | MoveClipParams | Yes | Move parameters | | pixelsPerSecond | number | No | Zoom level for snapping | **MoveClipParams:** ```typescript interface MoveClipParams { clipId: string; // Clip to move startTime: number; // New start time trackId?: string; // New track (optional) } ``` **Returns:** `Promise` - Result with adjusted position **Example:** ```typescript const result = await clipManager.moveClip(timeline, { clipId: 'clip-123', startTime: 5.0, trackId: 'track-video-2', // Move to different track }); ``` ``` -------------------------------- ### MediaBunnyEngine Constructor Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Creates a new MediaBunnyEngine instance. Optionally configure the number of worker threads. ```APIDOC ## Constructor MediaBunnyEngine ### Description Creates a new MediaBunnyEngine instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **options** (object) - Optional - Configuration options for the engine. - **workerCount** (number) - Optional - The number of worker threads to use. ``` -------------------------------- ### Run Project Tests and Linting Source: https://github.com/augani/openreel-video/blob/main/CONTRIBUTING.md Commands to execute the test suite, perform type checking, and run the linter. ```bash # Run all tests (watch mode) pnpm test # Run tests once (CI mode) pnpm test:run # Type checking pnpm typecheck # Linting pnpm lint ``` -------------------------------- ### VideoEngine Constructor Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Creates a new VideoEngine instance with optional cache configuration. ```APIDOC ## Constructor VideoEngine ### Description Creates a new VideoEngine instance with optional cache configuration. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **cacheConfig** (Partial) - Optional - Frame cache configuration overrides ### Request Example ```typescript const engine = new VideoEngine({ maxFrames: 200, maxSizeBytes: 1000 * 1024 * 1024, preloadAhead: 30, }); ``` ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Trim a Clip Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Utilize trimClip to adjust the in and out points of a clip, effectively changing its start and end duration within the media timeline. ```typescript // Trim to use middle 3 seconds of 5-second clip const result = await clipManager.trimClip(timeline, 'clip-123', 1, 4); ``` -------------------------------- ### isInitialized() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Checks if the media engine has been successfully initialized. ```APIDOC ## isInitialized() ### Description Checks if the engine is initialized. ### Method `isInitialized(): boolean` ### Parameters None ### Returns - **boolean**: `true` if the engine is initialized, `false` otherwise. ``` -------------------------------- ### ExportEngine Constructor Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Creates a new instance of the ExportEngine. ```APIDOC ## ExportEngine() ### Description Creates a new ExportEngine instance. ### Constructor `constructor()` ``` -------------------------------- ### Initialize MediaBunnyEngine Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Creates a new MediaBunnyEngine instance. Optionally configure the number of worker threads. ```typescript constructor(options?: { workerCount?: number }) ``` -------------------------------- ### supportsGPURendering() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Checks if GPU rendering is available on the device. ```APIDOC ## supportsGPURendering() ### Description Checks if GPU rendering is available on the device. ### Method `supportsGPURendering(): boolean` ### Returns `boolean` - True if WebGPU is supported and initialized ``` -------------------------------- ### Get History Snapshots Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/action-executor.md Retrieves all history snapshots, which are suitable for UI display. Each snapshot includes an ID, the action, timestamp, and a human-readable label. ```typescript getSnapshots(): HistorySnapshot[] ``` -------------------------------- ### Get Device Capabilities Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Retrieves information about the device's video processing capabilities, including hardware acceleration support and supported codecs. ```typescript getDeviceCapabilities(): { supportsHardwareDecoding: boolean; supportsHardwareEncoding: boolean; supportedCodecs: string[]; maxResolution: { width: number; height: number }; } ``` -------------------------------- ### Initialize AudioEngine Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/audio-engine.md Initialize the audio engine to create the necessary audio context. This method should be called before performing any audio operations. It may throw an error if AudioContext creation fails. ```typescript const engine = new AudioEngine(); await engine.initialize(); ``` -------------------------------- ### Reorder a Track Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Move an existing track to a new position within the timeline. This is useful for organizing tracks, for example, moving an audio track to the top. ```typescript // Move audio track to position 0 (top) await trackManager.reorderTrack(timeline, 'track-audio-1', 0); ``` -------------------------------- ### Initialize Export Engine Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Creates a new ExportEngine instance and initializes it. This step is required before using other engine methods. Ensure all dependencies are available. ```typescript const engine = new ExportEngine(); await engine.initialize(); ``` -------------------------------- ### Get Export Presets Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Retrieve an array of predefined export quality presets. These can be used to quickly configure export settings for common use cases. ```typescript const presets = ExportEngine.getExportPresets(); const hd = presets.find(p => p.id === '1080p-web'); console.log(hd.settings); ``` -------------------------------- ### Instantiate VideoEngine with Cache Configuration Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Create a new VideoEngine instance. You can override default frame cache settings like maximum frames, size, and preloading behavior. ```typescript const engine = new VideoEngine({ maxFrames: 200, maxSizeBytes: 1000 * 1024 * 1024, preloadAhead: 30, }); ``` -------------------------------- ### Get CPU Information Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Retrieves information about the device's CPU, including the number of cores and performance tier. This is useful for understanding processing power. ```typescript function getCpuInfo(): CpuInfo // Example usage would involve calling this function and inspecting the returned CpuInfo object. ``` -------------------------------- ### Initialize Media Engine Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Initializes the media engine and loads the MediaBunny library. This asynchronous operation may throw an error if MediaBunny fails to load. ```typescript async initialize(): Promise ``` -------------------------------- ### Get Cache Statistics Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/storage-engine.md Retrieves statistics about the current cache usage, including size, number of entries, and hit rate. Useful for monitoring cache performance. ```typescript const stats = cacheManager.getCacheStats(); console.log(`Cache: ${(stats.size / 1024 / 1024).toFixed(1)}MB`); console.log(`Hit Rate: ${(stats.hitRate * 100).toFixed(1)}%`); ``` -------------------------------- ### Get Memory Information Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Retrieves information about the device's RAM, including the total GB and performance tier. This helps in assessing memory capacity and performance. ```typescript function getMemoryInfo(): MemoryInfo // Example usage would involve calling this function and inspecting the returned MemoryInfo object. ``` -------------------------------- ### Import Project from JSON Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/storage-engine.md Imports a project from a JSON string. Media items will be placeholders if blobs are not included in the JSON. ```typescript const json = await file.text(); const project = serializer.importFromJson(json); console.log(`Imported: ${project.name}`); ``` -------------------------------- ### Initialize GPU for Hardware-Accelerated Export Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Initializes GPU resources for hardware-accelerated video export. Returns true if successful, false otherwise. Specify the desired output video dimensions. ```typescript const gpuReady = await engine.initializeGPUForExport(1920, 1080); if (gpuReady) { console.log("GPU acceleration available"); } ``` -------------------------------- ### Create Rectangle Shape Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/graphics-engine.md Creates a rectangle shape with specified dimensions and optional styling. The rectangle is added to a specific track and has a defined start time and duration. ```typescript const rect = graphics.createRectangle( 'track-graphics-1', 0, 2, 200, 150, { fill: { color: '#FF0000' }, stroke: { width: 2, color: '#000000' } } ); ``` -------------------------------- ### Decode a Single Video Frame Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/media-engine.md Use decodeFrame to get a specific video frame at a given time. Options for width and height can be provided to resize the output frame. ```typescript async decodeFrame( file: File | Blob, time: number, options?: { width?: number; height?: number }, ): Promise ``` ```typescript const result = await engine.decodeFrame(videoFile, 1.5, { width: 320, height: 180, }); const bitmap = await result.frame.convertToImageBitmap(); ``` -------------------------------- ### Initialize ClipManager with Snap-to-Grid Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Instantiate ClipManager with options to enable snap-to-grid functionality and configure grid size and threshold. ```typescript const clipManager = new ClipManager({ snapToGridEnabled: true, gridSize: 0.5, // 500ms grid snapThreshold: 10, // pixels }); ``` -------------------------------- ### Get Realtime Audio Graph Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/playback-controller.md Retrieves the real-time audio graph for direct manipulation of audio nodes. Use this to schedule audio clips or manage gain nodes. ```typescript getRealtimeAudioGraph(): RealtimeAudioGraph ``` ```typescript const audioGraph = controller.getRealtimeAudioGraph(); // Can schedule audio clips, manage gain nodes, etc. ``` -------------------------------- ### Default Image Export Settings Source: https://github.com/augani/openreel-video/blob/main/_autodocs/configuration.md Provides the default configuration for image exports, including format, quality, width, and height. This can be used as a starting point for custom configurations. ```typescript const DEFAULT_IMAGE_SETTINGS: ImageExportSettings = { format: 'jpg', quality: 90, width: 1920, height: 1080, }; ``` -------------------------------- ### Initialize Video Engine Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Accesses the singleton Video Engine instance and initializes it. Ensure this is called before using other engine functionalities. ```typescript import { getVideoEngine, initializeVideoEngine } from '@openreel/core'; const engine = getVideoEngine(); await engine.initialize(); ``` -------------------------------- ### Default Playback Configuration Source: https://github.com/augani/openreel-video/blob/main/_autodocs/configuration.md Provides default playback settings, including a frame rate of 30fps and real-time audio enabled. ```typescript const DEFAULT_PLAYBACK_CONFIG: PlaybackConfig = { frameRate: 30, useRealtimeAudio: true, targetFrameTime: 1000 / 30, // ~33ms for 30fps }; ``` -------------------------------- ### Move a Clip on the Timeline Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Employ moveClip to reposition an existing clip to a new start time, optionally moving it to a different track. The pixelsPerSecond parameter affects snapping. ```typescript const result = await clipManager.moveClip(timeline, { clipId: 'clip-123', startTime: 5.0, trackId: 'track-video-2', // Move to different track }); ``` -------------------------------- ### benchmarkDevice() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Runs an encoding performance benchmark for a given device profile and optional codec. ```APIDOC ## benchmarkDevice() ### Description Runs encoding performance benchmark. ### Parameters #### Request Body - **profile** (DeviceProfile) - Required - Device profile - **codec** (string) - Optional - Specific codec to benchmark ### Returns `Promise` ### BenchmarkResult ```typescript interface BenchmarkResult { framesPerSecond: number; codec: string; resolution: { width: number; height: number }; testedAt: number; } ``` ### Example ```typescript const benchmark = await benchmarkDevice(profile, 'h264'); console.log(`${benchmark.framesPerSecond.toFixed(1)} fps at 1080p`); if (benchmark.framesPerSecond < 30) { console.warn('Encoding is slow, consider lower bitrate'); } ``` ``` -------------------------------- ### isInitialized() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/video-engine.md Checks if the video engine has completed its initialization process. ```APIDOC ## isInitialized() ### Description Checks if the engine is initialized. ### Method (Not specified, likely an SDK method) ### Response #### Success Response - **boolean** - True if initialization completed ``` -------------------------------- ### Get Device Profile Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Automatically detects and profiles device capabilities including CPU, RAM, GPU, codecs, and platform. Use this to understand the user's hardware for optimization. ```typescript import { getDeviceProfile } from '@openreel/core'; const profile = await getDeviceProfile(); console.log(`Device Tier: ${profile.overallTier}`); console.log(`GPU: ${profile.gpu.renderer}`); console.log(`H.264 Hardware Support: ${profile.encoding.h264.hardware}`); // Make recommendations based on profile if (profile.overallTier === 'low') { recommendQuality('480p'); } else if (profile.overallTier === 'high') { recommendQuality('4K'); } ``` -------------------------------- ### Add a Clip to the Timeline Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/timeline-managers.md Use the addClip method to add a media item to a specific track at a given start time and duration. The pixelsPerSecond parameter influences snapping behavior. ```typescript const result = await clipManager.addClip(timeline, { trackId: 'track-video-1', mediaId: 'media-123', startTime: 2.5, duration: 5, }); if (result.success) { console.log(`Clip added: ${result.clipId}`); } ``` -------------------------------- ### Access Core Engines as Singletons Source: https://github.com/augani/openreel-video/blob/main/_autodocs/INDEX.md Import and initialize core engines once to reuse them throughout your application. This ensures consistent access to engine functionalities. ```typescript import { getVideoEngine, getAudioEngine, getExportEngine, getMediaEngine, getPlaybackController, getGSAPEngine, getDeviceProfile, } from '@openreel/core'; // Initialize once, reuse everywhere const videoEngine = getVideoEngine(); const audioEngine = getAudioEngine(); ``` -------------------------------- ### Directly Instantiate API Controllers Source: https://github.com/augani/openreel-video/blob/main/_autodocs/README.md Import and create new instances of various controllers and managers as needed. This approach is suitable for components that require their own independent instances. ```typescript import { PlaybackController, ClipManager, TrackManager, ProjectSerializer, CacheManager, } from '@openreel/core'; // Create instances as needed const playback = new PlaybackController({ frameRate: 30 }); const clipManager = new ClipManager(); const trackManager = new TrackManager(); ``` -------------------------------- ### Get GPU Information Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/device-capabilities.md Retrieves information about the device's GPU, including vendor, model, performance tier, and hardware encoding support. Essential for graphics and video processing capabilities. ```typescript function getGpuInfo(): GpuInfo // Example usage would involve calling this function and inspecting the returned GpuInfo object. ``` -------------------------------- ### exportVideo() Source: https://github.com/augani/openreel-video/blob/main/_autodocs/api-reference/export-engine.md Exports a project as a video file with specified settings and optional progress/error callbacks. ```APIDOC ## exportVideo(project: Project, settings: VideoExportSettings, onProgress?: (progress: ExportProgress) => void, onError?: (error: ExportError) => void) ### Description Exports a project as a video file. ### Method `async exportVideo(project: Project, settings: VideoExportSettings, onProgress?: (progress: ExportProgress) => void, onError?: (error: ExportError) => void): Promise` ### Parameters #### Path Parameters - **project** (Project) - Required - The project to export - **settings** (VideoExportSettings) - Required - Video export configuration - **onProgress** ((progress: ExportProgress) => void) - Optional - Callback for export progress updates - **onError** ((error: ExportError) => void) - Optional - Callback for export errors ### Returns - **Promise**: Result containing output blob or error ### Example ```typescript const settings: VideoExportSettings = { format: 'mp4', codec: 'h264', width: 1920, height: 1080, frameRate: 30, bitrate: 5000, bitrateMode: 'cbr', quality: 80, keyframeInterval: 60, audioSettings: { format: 'aac', sampleRate: 48000, bitDepth: 16, bitrate: 192, channels: 2, }, }; const result = await engine.exportVideo( project, settings, (progress) => console.log(`Progress: ${progress.progress}%`) ); if (result.success && result.blob) { downloadBlob(result.blob, 'output.mp4'); } ``` ``` -------------------------------- ### Default Audio Export Settings Source: https://github.com/augani/openreel-video/blob/main/_autodocs/configuration.md Provides the default configuration for audio exports, including format, sample rate, bit depth, and bitrate. This can be used as a starting point for custom configurations. ```typescript const DEFAULT_AUDIO_SETTINGS: AudioExportSettings = { format: 'mp3', sampleRate: 48000, bitDepth: 16, bitrate: 320, channels: 2, }; ```