### Install Project Dependencies
Source: https://github.com/opencut-app/opencut/blob/main/apps/transcription/README.md
Installs all the Python packages listed in the 'requirements.txt' file. This ensures that all necessary libraries for the transcription functionality are available in the active virtual environment.
```bash
pip install -r requirements.txt
```
--------------------------------
### Setup Modal for Transcription
Source: https://github.com/opencut-app/opencut/blob/main/apps/transcription/README.md
Configures the Modal client for use with your account. This typically involves authenticating with the Modal service by opening a browser window for user verification.
```bash
python -m modal setup
```
--------------------------------
### Docker Compose for OpenCut Services
Source: https://github.com/opencut-app/opencut/blob/main/CLAUDE.md
This bash snippet demonstrates how to start the necessary Docker services for local development of OpenCut, specifically the database and Redis.
```bash
# Start local database and Redis
docker-compose up -d
```
--------------------------------
### Create Python Virtual Environment
Source: https://github.com/opencut-app/opencut/blob/main/apps/transcription/README.md
Creates an isolated Python environment named 'env'. This is crucial for managing project-specific dependencies and avoiding conflicts with globally installed packages.
```bash
python -m venv env
```
--------------------------------
### Copy Environment File (Bash/Windows)
Source: https://github.com/opencut-app/opencut/blob/main/README.md
Copies the example environment file to a local configuration file. This is a common step before configuring environment-specific variables. Supports Unix/Linux/Mac, Windows Command Prompt, and PowerShell.
```bash
# Unix/Linux/Mac
cp .env.example .env.local
# Windows Command Prompt
copy .env.example .env.local
# Windows PowerShell
Copy-Item .env.example .env.local
```
--------------------------------
### Test Transcription Script
Source: https://github.com/opencut-app/opencut/blob/main/apps/transcription/README.md
Runs the 'transcription.py' script using the Modal CLI to test the transcription functionality. This executes the script in the Modal cloud environment.
```bash
modal run transcription.py
```
--------------------------------
### Deploy Transcription Function
Source: https://github.com/opencut-app/opencut/blob/main/apps/transcription/README.md
Deploys the 'transcription.py' script to the Modal platform, making it available for remote execution. This step is necessary before setting up secrets for the deployed function.
```bash
modal deploy transcription.py
```
--------------------------------
### Bun Development Commands for OpenCut
Source: https://github.com/opencut-app/opencut/blob/main/CLAUDE.md
This snippet shows essential Bun commands for developing the OpenCut monorepo. It covers root-level commands for starting all apps, building, linting, and formatting, as well as specific commands for the web application and database operations.
```bash
# Root level development
bun dev # Start all apps in development mode
bun build # Build all apps
bun lint # Lint all code using Ultracite
bun format # Format all code using Ultracite
# Web app specific (from apps/web/)
cd apps/web
bun run dev # Start Next.js development server with Turbopack
bun run build # Build for production
bun run lint # Run Biome linting
bun run lint:fix # Fix linting issues automatically
bun run format # Format code with Biome
# Database operations (from apps/web/)
bun run db:generate # Generate Drizzle migrations
bun run db:migrate # Run migrations
bun run db:push:local # Push schema to local development database
bun run db:push:prod # Push schema to production database
```
--------------------------------
### OpenCut Environment Variables Setup
Source: https://github.com/opencut-app/opencut/blob/main/CLAUDE.md
This snippet details the required environment variables for the OpenCut web application, typically found in `apps/web/.env.local`. It includes configurations for the database, authentication, Redis, and content management systems.
```bash
# Database
DATABASE_URL="postgresql://opencut:opencutthegoat@localhost:5432/opencut"
# Authentication
BETTER_AUTH_SECRET="your-generated-secret-here"
BETTER_AUTH_URL="http://localhost:3000"
# Redis
UPSTASH_REDIS_REST_URL="http://localhost:8079"
UPSTASH_REDIS_REST_TOKEN="example_token"
# Content Management
MARBLE_WORKSPACE_KEY="workspace-key"
NEXT_PUBLIC_MARBLE_API_URL="https://api.marblecms.com"
```
--------------------------------
### Configure Cloudflare Secrets for Modal
Source: https://github.com/opencut-app/opencut/blob/main/apps/transcription/README.md
Sets up essential environment variables as Modal secrets for interacting with Cloudflare R2 storage. These secrets enable the transcription script to download audio files and manage their deletion after processing.
```bash
CLOUDFLARE_ACCOUNT_ID=your-account-id
R2_ACCESS_KEY_ID=your-access-key-id
R2_SECRET_ACCESS_KEY=your-secret-access-key
R2_BUCKET_NAME=opencut-transcription
```
--------------------------------
### Activate Python Virtual Environment
Source: https://github.com/opencut-app/opencut/blob/main/apps/transcription/README.md
Activates the 'env' virtual environment. Activation modifies the shell's PATH to prioritize the environment's Python interpreter and scripts. This step is OS-dependent.
```bash
env\Scripts\activate
```
```bash
source env/bin/activate
```
--------------------------------
### Media Store API: Upload and Manage Media Files
Source: https://context7.com/opencut-app/opencut/llms.txt
This snippet illustrates the Media Store API for handling media file uploads and management within a project. It includes functions to determine file type, get image dimensions, calculate media duration, generate video thumbnails, add media files, load project media, and remove media files. Dependencies include utility functions from the media store itself.
```typescript
import { useMediaStore, getFileType, getImageDimensions, getMediaDuration } from '@/stores/media-store';
// Upload a video file to the project
async function uploadVideo(projectId: string, file: File) {
const mediaStore = useMediaStore.getState();
const fileType = getFileType(file);
if (fileType === 'video') {
const duration = await getMediaDuration(file);
const { generateVideoThumbnail } = await import('@/stores/media-store');
const { thumbnailUrl, width, height } = await generateVideoThumbnail(file);
await mediaStore.addMediaFile(projectId, {
name: file.name,
type: 'video',
file,
url: URL.createObjectURL(file),
duration,
thumbnailUrl,
width,
height,
});
}
}
// Load all media files for a project
async function loadMedia(projectId: string) {
const mediaStore = useMediaStore.getState();
await mediaStore.loadProjectMedia(projectId);
const { mediaFiles } = mediaStore;
console.log(`Loaded ${mediaFiles.length} media files`);
}
// Remove a media file and cascade delete from timeline
async function removeMedia(projectId: string, mediaId: string) {
const mediaStore = useMediaStore.getState();
await mediaStore.removeMediaFile(projectId, mediaId);
}
```
--------------------------------
### Search Freesound.org for Sound Effects API
Source: https://context7.com/opencut-app/opencut/llms.txt
Searches Freesound.org for royalty-free sound effects. Requires a GET request to the /api/sounds/search endpoint with query parameters for search term, type, page, sort order, and minimum rating. Returns a list of sound effect results.
```bash
# GET /api/sounds/search
curl "http://localhost:3000/api/sounds/search?q=explosion&type=effects&page=1&sort=downloads&min_rating=3"
# Response
{
"count": 1250,
"next": "http://localhost:3000/api/sounds/search?page=2",
"previous": null,
"results": [
{
"id": 123456,
"name": "Big Explosion",
"description": "Massive explosion sound effect",
"url": "https://freesound.org/people/user/sounds/123456/",
"previewUrl": "https://cdn.freesound.org/previews/123/123456_preview.mp3",
"downloadUrl": "https://freesound.org/apiv2/sounds/123456/download/",
"duration": 5.2,
"filesize": 512000,
"type": "mp3",
"channels": 2,
"bitrate": 192000,
"bitdepth": 16,
"samplerate": 44100,
"username": "soundartist",
"tags": ["explosion", "boom", "blast"],
"license": "Attribution",
"created": "2024-01-15T10:30:00Z",
"downloads": 5432,
"rating": 4.5,
"ratingCount": 89
}
],
"query": "explosion",
"type": "effects",
"page": 1,
"pageSize": 20,
"sort": "downloads",
"minRating": 3
}
```
--------------------------------
### Manage Video Editing Projects with Project Store API (TypeScript)
Source: https://context7.com/opencut-app/opencut/llms.txt
This section shows how to interact with the `useProjectStore` to manage video editing projects. It covers creating new projects, loading existing ones, configuring project settings like canvas size and background, adding bookmarks, and listing projects with filtering. It relies on the `@/stores/project-store` module and types from `@/types/project`.
```typescript
import { useProjectStore } from '@/stores/project-store';
// Create a new project
async function createProject(name: string) {
const projectStore = useProjectStore.getState();
const projectId = await projectStore.createNewProject(name);
return projectId;
}
// Load an existing project
async function loadProject(projectId: string) {
const projectStore = useProjectStore.getState();
try {
await projectStore.loadProject(projectId);
const { activeProject } = projectStore;
console.log('Project loaded:', activeProject?.name);
} catch (error) {
console.error('Failed to load project:', error);
}
}
// Update canvas size and background
async function configureProject() {
const projectStore = useProjectStore.getState();
await projectStore.updateCanvasSize(
{ width: 1920, height: 1080 },
'preset'
);
await projectStore.updateBackgroundType('blur', {
blurIntensity: 8,
});
await projectStore.updateProjectFps(30);
}
// Manage bookmarks
async function addBookmark(time: number) {
const projectStore = useProjectStore.getState();
await projectStore.toggleBookmark(time);
}
// List all projects with filtering
function listProjects(searchQuery: string, sortOption: string) {
const projectStore = useProjectStore.getState();
const projects = projectStore.getFilteredAndSortedProjects(
searchQuery,
sortOption
);
return projects;
}
```
--------------------------------
### Persist Project Data with Storage Service API (TypeScript)
Source: https://context7.com/opencut-app/opencut/llms.txt
This code utilizes the `storageService` to persist project data, including project metadata, timelines, and media files, using IndexedDB and OPFS. It provides functions to save a complete project and load it back. It also includes a utility to check storage support and capacity. Dependencies include `@/lib/storage/storage-service` and types from `@/types/project`, `@/types/media`, and `@/types/timeline`.
```typescript
import { storageService } from '@/lib/storage/storage-service';
import { TProject } from '@/types/project';
import { MediaFile } from '@/types/media';
import { TimelineTrack } from '@/types/timeline';
// Save a complete project with all data
async function saveProject(project: TProject, tracks: TimelineTrack[], mediaFiles: MediaFile[]) {
// Save project metadata
await storageService.saveProject({ project });
// Save timeline for the current scene
const currentSceneId = project.currentSceneId;
await storageService.saveTimeline({
projectId: project.id,
tracks,
sceneId: currentSceneId,
});
// Save all media files
for (const mediaItem of mediaFiles) {
await storageService.saveMediaFile({
projectId: project.id,
mediaItem,
});
}
}
// Load a complete project
async function loadCompleteProject(projectId: string) {
const project = await storageService.loadProject({ id: projectId });
if (!project) {
throw new Error('Project not found');
}
const currentSceneId = project.currentSceneId;
const [tracks, mediaFiles] = await Promise.all([
storageService.loadTimeline({ projectId, sceneId: currentSceneId }),
storageService.loadAllMediaFiles({ projectId }),
]);
return { project, tracks: tracks || [], mediaFiles };
}
// Check storage support and capacity
async function checkStorage() {
const info = await storageService.getStorageInfo();
console.log('Projects:', info.projects);
console.log('OPFS supported:', info.isOPFSSupported);
console.log('IndexedDB supported:', info.isIndexedDBSupported);
const projectInfo = await storageService.getProjectStorageInfo({
projectId: 'project-uuid'
});
console.log('Media items:', projectInfo.mediaItems);
console.log('Has timeline:', projectInfo.hasTimeline);
}
```
--------------------------------
### Control Video Playback and Timeline Scrubbing with Playback Store API (TypeScript)
Source: https://context7.com/opencut-app/opencut/llms.txt
This snippet demonstrates how to use the `usePlaybackStore` hook to control video playback. It includes functions for playing, pausing, seeking, setting volume, and playback speed. Dependencies include the `@/stores/playback-store` module.
```typescript
import { usePlaybackStore } from '@/stores/playback-store';
// React component with playback controls
function PlaybackControls() {
const { isPlaying, currentTime, duration, play, pause, seek, setVolume, setSpeed } = usePlaybackStore();
return (
);
}
```
--------------------------------
### Timeline Store API: Manage Tracks and Elements
Source: https://context7.com/opencut-app/opencut/llms.txt
This snippet demonstrates how to interact with the timeline store to add and manage media and text elements on the timeline. It includes functionalities for adding tracks, elements, multi-selection, splitting, ripple editing, and undo/redo operations. Dependencies include Zustand for state management and custom constants.
```typescript
import { useTimelineStore } from '@/stores/timeline-store';
import { TIMELINE_CONSTANTS } from '@/constants/timeline-constants';
// Add a media file to the timeline
const timelineStore = useTimelineStore.getState();
const trackId = timelineStore.addTrack('media');
timelineStore.addElementToTrack(trackId, {
type: 'media',
mediaId: 'media-file-uuid',
name: 'My Video Clip',
duration: 45.5,
startTime: 0,
trimStart: 0,
trimEnd: 0,
muted: false,
});
// Add a text overlay to the timeline
const textTrackId = timelineStore.insertTrackAt('text', 0);
timelineStore.addElementToTrack(textTrackId, {
type: 'text',
name: 'Title',
content: 'My Video Title',
duration: TIMELINE_CONSTANTS.DEFAULT_TEXT_DURATION,
startTime: 2.5,
trimStart: 0,
trimEnd: 0,
fontSize: 48,
fontFamily: 'Inter',
color: '#ffffff',
backgroundColor: 'transparent',
textAlign: 'center',
fontWeight: 'bold',
fontStyle: 'normal',
textDecoration: 'none',
x: 0,
y: 0,
rotation: 0,
opacity: 1,
});
// Multi-select and split elements at playhead
timelineStore.selectElement('track-1', 'element-1', false);
timelineStore.selectElement('track-2', 'element-2', true);
timelineStore.splitSelected(5.0); // Split at 5 seconds
// Enable ripple editing and delete with ripple
timelineStore.toggleRippleEditing();
timelineStore.deleteSelected('track-1', 'element-1');
// Undo/redo operations
timelineStore.undo();
timelineStore.redo();
```
--------------------------------
### React Hooks for Editor Functionality
Source: https://context7.com/opencut-app/opencut/llms.txt
Provides custom React hooks for common editor functionalities. Includes hooks for playback controls, custom keybindings with registration and unregistration, and timeline zoom controls.
```typescript
import { usePlaybackControls } from '@/hooks/use-playback-controls';
import { useKeybindings } from '@/hooks/use-keybindings';
import { useTimelineZoom } from '@/hooks/use-timeline-zoom';
// Playback keyboard shortcuts
function Editor() {
usePlaybackControls();
// Enables: Space (play/pause), Arrow keys (frame stepping), Home/End
return
);
}
```
--------------------------------
### Media Processing with ffmpeg-utils in TypeScript
Source: https://github.com/opencut-app/opencut/blob/main/CLAUDE.md
Illustrates the usage of a utility function `processVideo` from `@/lib/ffmpeg-utils` for media processing. This function likely handles video encoding, manipulation, or other operations using FFmpeg, taking input files and options as arguments.
```typescript
import { processVideo } from '@/lib/ffmpeg-utils';
const processedVideo = await processVideo(inputFile, options);
```
--------------------------------
### Transcribe Audio to Text using Whisper AI API
Source: https://context7.com/opencut-app/opencut/llms.txt
Generates captions from audio files using the Whisper AI model. Requires a POST request to the /api/transcribe endpoint with a JSON payload containing the filename and language. Returns the transcribed text and segments.
```bash
# POST /api/transcribe
curl -X POST http://localhost:3000/api/transcribe \
-H "Content-Type: application/json" \
-d '{
"filename": "audio.mp3",
"language": "en"
}'
# Response
{
"text": "This is the complete transcription.",
"segments": [
{
"id": 0,
"start": 0.0,
"end": 2.5,
"text": "This is the complete transcription.",
"tokens": [123, 456],
"temperature": 0.0,
"avg_logprob": -0.5,
"compression_ratio": 1.2,
"no_speech_prob": 0.01
}
],
"language": "en"
}
```
--------------------------------
### Zustand Store Usage in React
Source: https://github.com/opencut-app/opencut/blob/main/CLAUDE.md
Shows how to consume a Zustand store in a React component. It destructures specific state properties and actions from the `useTimelineStore` hook, enabling direct access to the application's state management.
```typescript
const { tracks, addTrack, updateTrack } = useTimelineStore();
```
--------------------------------
### Export Video Project to MP4 or WebM
Source: https://context7.com/opencut-app/opencut/llms.txt
Exports a video project to MP4 or WebM format with customizable options like quality, FPS, and audio inclusion. It includes progress tracking and cancellation support. Dependencies include '@/lib/export' and '@/types/export'.
```typescript
import { exportProject, getExportMimeType, getExportFileExtension } from '@/lib/export';
import { ExportOptions } from '@/types/export';
// Export project with progress tracking
async function exportVideo() {
const options: ExportOptions = {
format: 'mp4',
quality: 'high',
fps: 30,
includeAudio: true,
onProgress: (progress: number) => {
console.log(`Export progress: ${Math.round(progress * 100)}%`);
},
onCancel: () => {
// Return true to cancel export
return false;
},
};
const result = await exportProject(options);
if (result.success && result.buffer) {
const blob = new Blob([result.buffer], {
type: getExportMimeType(options.format)
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `my-video${getExportFileExtension(options.format)}`;
a.click();
URL.revokeObjectURL(url);
} else if (result.cancelled) {
console.log('Export cancelled by user');
} else {
console.error('Export failed:', result.error);
}
}
// Export with different quality levels
async function exportWithQuality(quality: 'low' | 'medium' | 'high' | 'very_high') {
const result = await exportProject({
format: 'webm',
quality,
includeAudio: true,
onProgress: (p) => console.log(`${(p * 100).toFixed(1)}%`),
});
return result;
}
```
--------------------------------
### Transcription API
Source: https://context7.com/opencut-app/opencut/llms.txt
API to generate text captions from audio files using the Whisper AI model.
```APIDOC
## Transcription API
### Description
Generates text transcriptions from audio files using the Whisper AI model. Supports specifying the audio filename and language.
### Method
POST
### Endpoint
`/api/transcribe`
### Parameters
#### Request Body
- **filename** (string) - Required - The name of the audio file to transcribe.
- **language** (string) - Optional - The language of the audio (e.g., 'en' for English). If not provided, Whisper will attempt to auto-detect.
### Request Example
```bash
curl -X POST http://localhost:3000/api/transcribe \
-H "Content-Type: application/json" \
-d '{
"filename": "audio.mp3",
"language": "en"
}'
```
### Response
#### Success Response (200)
- **text** (string) - The complete transcribed text.
- **segments** (array) - An array of segment objects, each containing details about a part of the transcription.
- **id** (number) - Unique identifier for the segment.
- **start** (number) - Start time of the segment in seconds.
- **end** (number) - End time of the segment in seconds.
- **text** (string) - The transcribed text for this segment.
- **tokens** (array) - Array of token IDs.
- **temperature** (number) - Temperature used during transcription.
- **avg_logprob** (number) - Average log probability of the segment.
- **compression_ratio** (number) - Compression ratio of the segment.
- **no_speech_prob** (number) - Probability of no speech in the segment.
- **language** (string) - The detected or specified language of the audio.
#### Response Example
```json
{
"text": "This is the complete transcription.",
"segments": [
{
"id": 0,
"start": 0.0,
"end": 2.5,
"text": "This is the complete transcription.",
"tokens": [123, 456],
"temperature": 0.0,
"avg_logprob": -0.5,
"compression_ratio": 1.2,
"no_speech_prob": 0.01
}
],
"language": "en"
}
```
#### Error Response (e.g., 400, 500)
- **error** (string) - A message describing the error.
Example:
```json
{
"error": "Audio file not found or could not be processed."
}
```
```
--------------------------------
### Sound Effects Search API
Source: https://context7.com/opencut-app/opencut/llms.txt
API to search for royalty-free sound effects on Freesound.org.
```APIDOC
## Sound Effects Search API
### Description
Searches the Freesound.org database for royalty-free sound effects based on various query parameters.
### Method
GET
### Endpoint
`/api/sounds/search`
### Parameters
#### Query Parameters
- **q** (string) - Required - The search query (e.g., 'explosion', 'car').
- **type** (string) - Optional - Filter by sound type (e.g., 'effects', 'music').
- **page** (integer) - Optional - The page number for results. Defaults to 1.
- **sort** (string) - Optional - Sorting order (e.g., 'downloads', 'rating', 'duration', 'created_desc'). Defaults to 'relevance'.
- **min_rating** (number) - Optional - Minimum rating for results (0.0 to 5.0).
- **duration_min** (number) - Optional - Minimum duration in seconds.
- **duration_max** (number) - Optional - Maximum duration in seconds.
- **license** (string) - Optional - Filter by license type (e.g., 'Attribution', 'CC0').
### Request Example
```bash
curl "http://localhost:3000/api/sounds/search?q=explosion&type=effects&page=1&sort=downloads&min_rating=3"
```
### Response
#### Success Response (200)
- **count** (integer) - Total number of results matching the query.
- **next** (string | null) - URL for the next page of results, or null if there are no more pages.
- **previous** (string | null) - URL for the previous page of results, or null if this is the first page.
- **results** (array) - An array of sound effect objects.
- **id** (integer) - Freesound ID of the sound.
- **name** (string) - Name of the sound effect.
- **description** (string) - Description of the sound effect.
- **url** (string) - URL to the sound's page on Freesound.
- **previewUrl** (string) - URL to a preview of the sound.
- **downloadUrl** (string) - URL to download the sound file.
- **duration** (number) - Duration of the sound in seconds.
- **filesize** (integer) - Size of the file in bytes.
- **type** (string) - File type (e.g., 'mp3', 'wav').
- **channels** (integer) - Number of audio channels.
- **bitrate** (integer) - Bitrate in bits per second.
- **bitdepth** (integer) - Bit depth.
- **samplerate** (integer) - Sample rate in Hz.
- **username** (string) - Username of the uploader.
- **tags** (array) - Array of tags associated with the sound.
- **license** (string) - License type.
- **created** (string) - Date and time the sound was uploaded (ISO 8601 format).
- **downloads** (integer) - Number of times the sound has been downloaded.
- **rating** (number) - Average rating of the sound.
- **ratingCount** (integer) - Number of ratings received.
- **query** (string) - The original search query.
- **type** (string) - The filtered sound type.
- **page** (integer) - The current page number.
- **pageSize** (integer) - The number of results per page.
- **sort** (string) - The applied sorting order.
- **minRating** (number) - The minimum rating filter applied.
#### Response Example
```json
{
"count": 1250,
"next": "http://localhost:3000/api/sounds/search?page=2",
"previous": null,
"results": [
{
"id": 123456,
"name": "Big Explosion",
"description": "Massive explosion sound effect",
"url": "https://freesound.org/people/user/sounds/123456/",
"previewUrl": "https://cdn.freesound.org/previews/123/123456_preview.mp3",
"downloadUrl": "https://freesound.org/apiv2/sounds/123456/download/",
"duration": 5.2,
"filesize": 512000,
"type": "mp3",
"channels": 2,
"bitrate": 192000,
"bitdepth": 16,
"samplerate": 44100,
"username": "soundartist",
"tags": ["explosion", "boom", "blast"],
"license": "Attribution",
"created": "2024-01-15T10:30:00Z",
"downloads": 5432,
"rating": 4.5,
"ratingCount": 89
}
],
"query": "explosion",
"type": "effects",
"page": 1,
"pageSize": 20,
"sort": "downloads",
"minRating": 3
}
```
#### Error Response (e.g., 400, 500)
- **error** (string) - A message describing the error.
Example:
```json
{
"error": "Invalid query parameters."
}
```
```
--------------------------------
### Generate Secure Secret (Various Methods)
Source: https://github.com/opencut-app/opencut/blob/main/README.md
Provides multiple methods for generating a secure random string, commonly used for application secrets like BETTER_AUTH_SECRET. Includes options for Unix/Linux/Mac, Windows PowerShell, and cross-platform Node.js.
```bash
# Unix/Linux/Mac
openssl rand -base64 32
# Windows PowerShell (simple method)
[System.Web.Security.Membership]::GeneratePassword(32, 0)
# Cross-platform (using Node.js)
node -e "console.log(require('crypto').randomBytes(32).toString('base64'))"
# Or use an online generator: https://generate-secret.vercel.app/32
```
--------------------------------
### Export API
Source: https://context7.com/opencut-app/opencut/llms.txt
API for exporting timelines to video files such as MP4 or WebM. It supports various quality settings and progress tracking.
```APIDOC
## Export API
### Description
Exports a project timeline to video files (MP4 or WebM) with configurable quality and progress callbacks.
### Method
POST
### Endpoint
`/api/export` (Assumed based on usage)
### Parameters
#### Request Body
- **format** (string) - Required - The desired video format ('mp4' or 'webm').
- **quality** (string) - Optional - The video quality setting ('low', 'medium', 'high', 'very_high'). Defaults to 'high'.
- **fps** (number) - Optional - Frames per second for the exported video. Defaults to 30.
- **includeAudio** (boolean) - Optional - Whether to include audio in the export. Defaults to true.
- **onProgress** (function) - Optional - A callback function that receives export progress (0 to 1).
- **onCancel** (function) - Optional - A callback function that should return true if the export should be cancelled.
### Request Example
```typescript
const options = {
format: 'mp4',
quality: 'high',
fps: 30,
includeAudio: true,
onProgress: (progress: number) => {
console.log(`Export progress: ${Math.round(progress * 100)}%`);
}
};
// Call exportProject(options) from your application
```
### Response
#### Success Response (200)
- **success** (boolean) - True if the export was successful.
- **buffer** (ArrayBuffer | null) - The video file data as an ArrayBuffer if successful, otherwise null.
- **cancelled** (boolean) - True if the export was cancelled by the user.
- **error** (string | null) - An error message if the export failed, otherwise null.
#### Response Example
```json
{
"success": true,
"buffer": "... ArrayBuffer data ...",
"cancelled": false,
"error": null
}
```
#### Error Response (e.g., 500)
```json
{
"success": false,
"buffer": null,
"cancelled": false,
"error": "Failed to export video due to an internal error."
}
```
```
--------------------------------
### TypeScript Error Handling Try-Catch Block
Source: https://github.com/opencut-app/opencut/blob/main/CLAUDE.md
Demonstrates a common error handling pattern in TypeScript using a try-catch block. It attempts an operation, returning success or failure with an error message. This pattern is useful for managing potential exceptions during asynchronous operations.
```typescript
try {
const result = await processData();
return { success: true, data: result };
} catch (error) {
console.error('Operation failed:', error);
return { success: false, error: error.message };
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.