# Funscript Format

> Documentation for the Funscript interactive script format.

---

## Overview

Funscript is a standard JSON-based format for describing time-synced device
actions. It's primarily used for stroker devices but can be adapted for any
position-based device.

### File Extension

`.funscript`

---

## Format Specification

### Basic Structure

```json
{
  "version": "1.0",
  "inverted": false,
  "range": 100,
  "actions": [
    { "at": 0, "pos": 0 },
    { "at": 500, "pos": 100 },
    { "at": 1000, "pos": 0 }
  ],
  "metadata": {
    "creator": "Aphrodite",
    "description": "Auto-generated script",
    "duration": 60000,
    "license": "CC BY-NC-SA 4.0",
    "notes": "",
    "performers": [],
    "script_url": "",
    "tags": [],
    "title": "Generated Script",
    "type": "basic",
    "video_url": ""
  }
}
```

### Fields

| Field      | Type    | Required | Description                   |
| ---------- | ------- | -------- | ----------------------------- |
| `version`  | string  | No       | Format version                |
| `inverted` | boolean | No       | Invert position values        |
| `range`    | number  | No       | Position range (default: 100) |
| `actions`  | array   | Yes      | Array of timed actions        |
| `metadata` | object  | No       | Optional metadata             |

### Action Object

| Field | Type   | Description                  |
| ----- | ------ | ---------------------------- |
| `at`  | number | Timestamp in milliseconds    |
| `pos` | number | Position (0-100, or 0-range) |

---

## Aphrodite Integration

### Funscript Parser

```typescript
// libs/aphrodite/devices/src/funscript/parser.ts
export interface FunscriptAction {
  at: number;
  pos: number;
}

export interface FunscriptMetadata {
  creator?: string;
  description?: string;
  duration?: number;
  title?: string;
  type?: string;
}

export interface Funscript {
  version?: string;
  inverted?: boolean;
  range?: number;
  actions: FunscriptAction[];
  metadata?: FunscriptMetadata;
}

export function parseFunscript(content: string): Funscript {
  const data = JSON.parse(content);

  if (!Array.isArray(data.actions)) {
    throw new Error('Invalid funscript: missing actions array');
  }

  return {
    version: data.version || '1.0',
    inverted: data.inverted || false,
    range: data.range || 100,
    actions: data.actions.map((a: any) => ({
      at: Number(a.at),
      pos: Number(a.pos),
    })),
    metadata: data.metadata,
  };
}

export function serializeFunscript(script: Funscript): string {
  return JSON.stringify(script, null, 2);
}
```

### Funscript Generator

```typescript
// libs/aphrodite/devices/src/funscript/generator.ts
export interface GeneratorOptions {
  duration: number; // Total duration in ms
  bpm?: number; // Beats per minute
  pattern?: 'stroke' | 'pulse' | 'random' | 'wave';
  intensity?: number; // 0-100, affects position range
}

export function generateFunscript(options: GeneratorOptions): Funscript {
  const { duration, bpm = 120, pattern = 'stroke', intensity = 100 } = options;

  const actions: FunscriptAction[] = [];
  const intervalMs = (60 / bpm) * 1000;
  const maxPos = intensity;
  const minPos = 100 - intensity;
  let time = 0;
  let position = minPos;

  while (time < duration) {
    actions.push({ at: time, pos: position });

    switch (pattern) {
      case 'stroke':
        position = position === minPos ? maxPos : minPos;
        time += intervalMs / 2;
        break;
      case 'pulse':
        position = position < 50 ? maxPos : minPos;
        time += intervalMs / 4;
        break;
      case 'random':
        position = Math.floor(Math.random() * (maxPos - minPos)) + minPos;
        time += intervalMs / 2;
        break;
      case 'wave':
        const progress = (time % intervalMs) / intervalMs;
        position = Math.floor(
          minPos +
            ((maxPos - minPos) * (Math.sin(progress * Math.PI * 2) + 1)) / 2
        );
        time += 50; // Fine granularity for smooth wave
        break;
    }
  }

  return {
    version: '1.0',
    inverted: false,
    range: 100,
    actions,
    metadata: {
      creator: 'Aphrodite',
      duration,
      title: `Generated ${pattern} pattern`,
      type: pattern,
    },
  };
}
```

### Funscript Player

```typescript
// libs/aphrodite/devices/src/funscript/player.ts
export class FunscriptPlayer extends EventEmitter {
  private script: Funscript | null = null;
  private currentIndex = 0;
  private startTime = 0;
  private playing = false;
  private timer: NodeJS.Timer | null = null;

  load(script: Funscript): void {
    this.script = script;
    this.currentIndex = 0;
    this.emit('script.loaded', { actionCount: script.actions.length });
  }

  play(startPosition: number = 0): void {
    if (!this.script) return;

    // Find starting index
    this.currentIndex = this.script.actions.findIndex(
      (a) => a.at >= startPosition
    );
    if (this.currentIndex === -1) this.currentIndex = 0;

    this.startTime = Date.now() - startPosition;
    this.playing = true;

    this.scheduleNextAction();
    this.emit('playback.started', { position: startPosition });
  }

  pause(): void {
    this.playing = false;
    if (this.timer) {
      clearTimeout(this.timer);
      this.timer = null;
    }
    this.emit('playback.paused');
  }

  stop(): void {
    this.pause();
    this.currentIndex = 0;
    this.emit('playback.stopped');
  }

  seek(position: number): void {
    const wasPlaying = this.playing;
    this.stop();
    if (wasPlaying) {
      this.play(position);
    }
  }

  private scheduleNextAction(): void {
    if (!this.script || !this.playing) return;
    if (this.currentIndex >= this.script.actions.length) {
      this.stop();
      this.emit('playback.ended');
      return;
    }

    const action = this.script.actions[this.currentIndex];
    const currentTime = Date.now() - this.startTime;
    const delay = Math.max(0, action.at - currentTime);

    this.timer = setTimeout(() => {
      this.executeAction(action);
      this.currentIndex++;
      this.scheduleNextAction();
    }, delay);
  }

  private executeAction(action: FunscriptAction): void {
    // Calculate speed based on time to next action
    const nextAction = this.script?.actions[this.currentIndex + 1];
    const duration = nextAction ? nextAction.at - action.at : 100;

    this.emit('action', {
      position: action.pos,
      duration,
      timestamp: action.at,
    });
  }
}
```

### Device Integration

```typescript
// libs/aphrodite/devices/src/funscript/device-adapter.ts
export class FunscriptDeviceAdapter {
  constructor(
    private player: FunscriptPlayer,
    private deviceService: HandyService | ButtplugService
  ) {
    this.player.on('action', this.handleAction.bind(this));
  }

  private async handleAction(action: {
    position: number;
    duration: number;
    timestamp: number;
  }): Promise<void> {
    if (this.deviceService instanceof HandyService) {
      await (this.deviceService as HandyService).moveToPosition(
        this.connectionKey,
        action.position,
        action.duration
      );
    } else if (this.deviceService instanceof ButtplugService) {
      // For linear devices
      await (this.deviceService as ButtplugService).linear(
        this.deviceIndex,
        action.position / 100,
        action.duration
      );
    }
  }
}
```

---

## Converting Formats

### CSV to Funscript

```typescript
export function csvToFunscript(csv: string): Funscript {
  const lines = csv
    .split('\n')
    .filter((line) => line.trim() && !line.startsWith('#'));

  const actions = lines.map((line) => {
    const [time, pos] = line.split(',').map(Number);
    return { at: time, pos };
  });

  return {
    version: '1.0',
    actions,
    metadata: {
      creator: 'Aphrodite CSV Converter',
    },
  };
}
```

### Funscript to CSV

```typescript
export function funscriptToCsv(script: Funscript): string {
  const lines = ['#Aphrodite Funscript Export'];
  for (const action of script.actions) {
    lines.push(`${action.at},${action.pos}`);
  }
  return lines.join('\n');
}
```

---

## Document History

| Date       | Version | Changes                       |
| ---------- | ------- | ----------------------------- |
| 2026-01-18 | 1.0.0   | Initial Funscript Format docs |
