This guide provides simple examples for common Aja Motion Pipeline operations.
SDK Examples#
Simple Video Processing#
typescript
import { createClient, jobId, configId } from '@aja/motion-pipeline-sdk';
// Create client
const client = createClient({
baseUrl: 'https://api.aja.oshun.io',
auth: { type: 'api-key', apiKey: process.env.AJA_API_KEY! },
});
// Submit a video for processing
async function processVideo(videoUrl: string) {
const result = await client.submitJob({
input: {
type: 'url',
url: videoUrl,
filename: 'my-video.mp4',
},
pipelineConfig: {
name: 'my-quick-config',
domain: 'general',
qualityPreset: 'standard',
},
});
if (!result.success) {
throw new Error(`Failed to submit: ${result.error.message}`);
}
console.log('Job submitted:', result.data.jobId);
return result.data.jobId;
}
// Usage
const jid = await processVideo('https://example.com/dance-video.mp4');
Check Job Status#
typescript
async function checkStatus(id: string) {
const result = await client.getJob(jobId(id));
if (!result.success) {
throw new Error(`Failed to get job: ${result.error.message}`);
}
const job = result.data;
console.log(`Status: ${job.status}`);
console.log(`Progress: ${(job.progress ?? 0) * 100}%`);
return job;
}
Wait for Completion#
typescript
async function waitForCompletion(id: string, maxWaitMs = 3600000) {
const startTime = Date.now();
const jid = jobId(id);
while (Date.now() - startTime < maxWaitMs) {
const result = await client.getJob(jid);
if (!result.success) {
throw new Error(`Failed to get job: ${result.error.message}`);
}
const { status, progress } = result.data;
console.log(`${status}: ${((progress ?? 0) * 100).toFixed(1)}%`);
if (status === 'completed') {
return result.data;
}
if (status === 'failed') {
throw new Error(`Job failed: ${result.data.error ?? 'Unknown error'}`);
}
if (status === 'cancelled') {
throw new Error('Job was cancelled');
}
// Wait 5 seconds before next check
await new Promise((r) => setTimeout(r, 5000));
}
throw new Error('Timeout waiting for job');
}
Download Results#
typescript
async function downloadMotion(id: string, format = 'fbx') {
const jid = jobId(id);
// Generate download URL
const result = await client.generateDownloadUrl(jid, {
format,
expiresIn: 3600, // 1 hour
});
if (!result.success) {
throw new Error(`Failed to get download URL: ${result.error.message}`);
}
console.log('Download URL:', result.data.url);
console.log('Expires:', result.data.expiresAt);
return result.data.url;
}
Complete Workflow#
typescript
async function extractMotion(videoUrl: string) {
// 1. Submit job
const submitResult = await client.submitJob({
input: {
type: 'url',
url: videoUrl,
filename: videoUrl.split('/').pop() ?? 'video.mp4',
},
pipelineConfig: {
name: 'extraction-workflow',
domain: 'dance',
qualityPreset: 'high',
},
});
if (!submitResult.success) {
throw new Error(submitResult.error.message);
}
const jid = submitResult.data.jobId;
console.log('Job submitted:', jid);
// 2. Wait for completion
const job = await waitForCompletion(String(jid));
console.log('Job completed!');
// 3. Download results
const fbxUrl = await downloadMotion(String(jid), 'fbx');
const bvhUrl = await downloadMotion(String(jid), 'bvh');
return { jid, fbxUrl, bvhUrl };
}
// Run it
const result = await extractMotion('https://example.com/yoga-session.mp4');
console.log('Motion files ready:', result);
CLI Examples#
Process a Single Video#
bash
# Basic processing
aja process video.mp4
# With quality preset
aja process --preset high video.mp4
# With domain optimization
aja process --domain dance --preset high video.mp4
# Wait for completion and download
aja process --wait --output ./output video.mp4
Process Multiple Videos#
bash
# Multiple files
aja process video1.mp4 video2.mp4 video3.mp4
# Using glob patterns
aja process "videos/*.mp4"
# Recursive directory processing
aja process -r ./videos
# With output formats
aja process --format fbx bvh "videos/*.mp4"
Check Job Status#
bash
# Get job status
aja jobs status job-abc-123
# Watch status updates
aja jobs status -w job-abc-123
# List all jobs
aja jobs list
# List failed jobs
aja jobs list --status failed
Convert Motion Formats#
bash
# Convert BVH to FBX
aja convert motion.bvh fbx
# Convert with skeleton retargeting
aja convert --skeleton mixamo motion.bvh fbx
# Batch conversion
aja convert "*.bvh" fbx
# Preview changes
aja convert --dry-run "*.bvh" glb
Inspect Motion Quality#
bash
# Basic inspection
aja inspect motion.fbx
# Full quality analysis
aja inspect --all motion.fbx
# Check quality threshold
aja inspect --quality --threshold 0.9 motion.fbx
# Output as JSON
aja inspect --format json motion.fbx
Configuration Examples#
Create Configuration#
typescript
// SDK
const result = await client.createConfig({
name: 'yoga-production',
description: 'High-quality yoga motion capture',
domain: 'yoga',
qualityPreset: 'high',
});
if (result.success) {
console.log('Config created:', result.data.id);
}
bash
# CLI
aja config create yoga-production --domain yoga --preset high
# From YAML file
aja config create -f config.yaml
YAML Configuration File#
yaml
# config.yaml
name: dance-production
description: Professional dance motion capture
domain: dance
qualityPreset: high
List Configurations#
typescript
// SDK
const result = await client.listConfigs();
if (result.success) {
for (const config of result.data.configs) {
console.log(`${config.name}: ${config.domain} (${config.qualityPreset})`);
}
}
bash
# CLI
aja config list
aja config list --verbose
Webhook Integration#
Express Webhook Handler#
typescript
import express from 'express';
const app = express();
app.use(express.json());
interface WebhookPayload {
event: 'completed' | 'failed';
jobId: string;
timestamp: string;
data: {
status: string;
outputs?: Array<{ format: string; name: string; sizeBytes: number }>;
error?: { code: string; message: string };
};
}
app.post('/webhooks/aja', (req, res) => {
const payload = req.body as WebhookPayload;
console.log(`Received ${payload.event} for job ${payload.jobId}`);
if (payload.event === 'completed') {
console.log('Outputs:', payload.data.outputs);
// Process completed job...
} else if (payload.event === 'failed') {
console.log('Error:', payload.data.error?.message);
// Handle failed job...
}
res.sendStatus(200);
});
app.listen(3000);
Submit with Webhook#
typescript
await client.submitJob({
input: {
type: 'url',
url: 'https://example.com/video.mp4',
filename: 'video.mp4',
},
pipelineConfig: configId('config-123'),
options: {
webhook: {
url: 'https://myapp.com/webhooks/aja',
events: ['completed', 'failed'],
},
},
});
Streaming Progress#
Real-Time Progress Updates#
typescript
import { jobId } from '@aja/motion-pipeline-sdk';
const jid = jobId('job-abc-123');
const unsubscribe = client.streamJobProgress(jid, {
onProgress: (event) => {
const { stage, progress, message } = event.data;
console.log(`[${stage}] ${(progress * 100).toFixed(1)}% - ${message}`);
},
onStageChange: (event) => {
console.log(`Now processing: ${event.data.stage}`);
},
onComplete: (event) => {
console.log('Job completed!');
console.log('Outputs:', event.data.outputs);
unsubscribe();
},
onError: (event) => {
console.error('Job failed:', event.data.error);
unsubscribe();
},
});
// Later: stop listening
// unsubscribe();
Health Monitoring#
Check Service Health#
typescript
const healthResult = await client.health();
if (healthResult.success) {
const { status, uptimeSeconds, components } = healthResult.data;
console.log(`Status: ${status}`);
console.log(`Uptime: ${Math.floor(uptimeSeconds / 3600)} hours`);
if (components) {
for (const [name, component] of Object.entries(components)) {
console.log(` ${name}: ${component.status}`);
}
}
}
Check Queue Status#
typescript
const queueResult = await client.queueStats();
if (queueResult.success) {
const { waiting, active, completed, failed, delayed } = queueResult.data;
console.log(`Waiting: ${waiting}`);
console.log(`Active: ${active}`);
console.log(`Completed: ${completed}`);
console.log(`Failed: ${failed}`);
console.log(`Delayed: ${delayed}`);
}
bash
# CLI
aja health
aja health --include-queue --include-components
Error Handling#
Handle API Errors#
typescript
const result = await client.submitJob(request);
if (!result.success) {
const { code, message, details } = result.error;
switch (code) {
case 'INVALID_INPUT':
console.error('Invalid video:', message);
// Show user-friendly error
break;
case 'QUOTA_EXCEEDED':
console.error('Rate limit exceeded');
// Implement backoff
break;
case 'UNAUTHORIZED':
console.error('Invalid API key');
// Refresh credentials
break;
case 'SERVICE_UNAVAILABLE':
console.error('Service down, retrying...');
// Retry with backoff
break;
default:
console.error('Unexpected error:', message);
}
return;
}
// Success path
const job = result.data;
Retry with Backoff#
typescript
async function submitWithRetry(
request: CreateJobRequest,
maxRetries = 3
): Promise<JobSubmitResponse> {
let lastError: Error | null = null;
let delay = 1000;
for (let attempt = 0; attempt < maxRetries; attempt++) {
const result = await client.submitJob(request);
if (result.success) {
return result.data;
}
// Don't retry client errors
if (['INVALID_INPUT', 'UNAUTHORIZED'].includes(result.error.code)) {
throw new Error(result.error.message);
}
lastError = new Error(result.error.message);
console.log(`Attempt ${attempt + 1} failed, retrying in ${delay}ms...`);
await new Promise((r) => setTimeout(r, delay));
delay *= 2; // Exponential backoff
}
throw lastError ?? new Error('Max retries exceeded');
}