# Media API Reference

Complete reference for Lilith's media management APIs including uploads,
processing, delivery, and CDN integration.

---

## Media Assets

### Upload Media

```http
POST /v1/media
```

Upload a media asset (audio, video, image).

**Request:** `multipart/form-data`

| Field         | Type     | Description               |
| ------------- | -------- | ------------------------- |
| `file`        | file     | Media file                |
| `type`        | string   | `audio`, `video`, `image` |
| `title`       | string   | Display title             |
| `description` | string   | Optional description      |
| `tags`        | string[] | Categorization tags       |
| `license`     | string   | Content license type      |

**Response:**

```json
{
  "media_id": "med_abc123",
  "type": "audio",
  "title": "Morning Meditation",
  "url": "https://cdn.lilith.app/media/med_abc123.mp3",
  "duration_ms": 600000,
  "size_bytes": 12500000,
  "format": "mp3",
  "status": "processing",
  "created_at": "2026-01-03T10:00:00Z"
}
```

### Direct Upload (Presigned URL)

```http
POST /v1/media/upload-direct
```

Get a presigned URL for direct upload to storage.

**Request Body:**

```json
{
  "filename": "meditation.mp3",
  "content_type": "audio/mpeg",
  "size_bytes": 12500000
}
```

**Response:**

```json
{
  "upload_url": "https://storage.lilith.app/upload?sig=...",
  "media_id": "med_pending123",
  "expires_at": "2026-01-03T11:00:00Z",
  "fields": {
    "key": "uploads/med_pending123",
    "policy": "...",
    "signature": "..."
  }
}
```

### List Media

```http
GET /v1/media
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `type` | string | Filter by type | |
`status` | string | `pending`, `processing`, `ready`, `failed` | | `tags` |
string[] | Filter by tags | | `limit` | number | Max results (default: 50) | |
`offset` | number | Pagination offset |

### Get Media Details

```http
GET /v1/media/{id}
```

**Response:**

```json
{
  "media_id": "med_abc123",
  "type": "audio",
  "title": "Morning Meditation",
  "description": "A 10-minute guided breathing exercise",
  "url": "https://cdn.lilith.app/media/med_abc123.mp3",
  "signed_url": null,
  "duration_ms": 600000,
  "size_bytes": 12500000,
  "format": "mp3",
  "sample_rate": 48000,
  "bitrate": 320000,
  "channels": 2,
  "codec": "mp3",
  "status": "ready",
  "metadata": {
    "artist": "Lilith Guides",
    "album": "Morning Sessions"
  },
  "tags": ["meditation", "breathing", "morning"],
  "license": "cc-by-nc",
  "checksum": "sha256:abc123...",
  "created_at": "2026-01-03T10:00:00Z",
  "updated_at": "2026-01-03T10:05:00Z"
}
```

### Update Media

```http
PATCH /v1/media/{id}
```

**Request Body:**

```json
{
  "title": "Updated Title",
  "description": "Updated description",
  "tags": ["meditation", "updated"]
}
```

### Delete Media

```http
DELETE /v1/media/{id}
```

---

## Signed URLs

### Generate Signed URL

```http
GET /v1/media/{id}/signed-url
POST /v1/media/{id}/signed-url
```

Generate time-limited, authenticated access URL.

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `expires` | number | TTL in seconds
(default: 3600) | | `ip_restrict` | boolean | Restrict to requester IP | |
`user_bound` | boolean | Bind to user token |

**Response:**

```json
{
  "signed_url": "https://cdn.lilith.app/media/med_abc123.mp3?sig=...",
  "expires_at": "2026-01-03T11:00:00Z",
  "cdn_headers": {
    "Cache-Control": "private, max-age=3600"
  }
}
```

---

## Media Processing

### Trigger Processing

```http
POST /v1/media/{id}/process
```

**Request Body:**

```json
{
  "operations": [
    { "type": "transcode", "format": "opus", "bitrate": 128000 },
    { "type": "normalize", "target_lufs": -16 },
    { "type": "generate_waveform" },
    { "type": "extract_transcript" }
  ],
  "callback_url": "https://your-app.com/webhook"
}
```

### Get Processing Status

```http
GET /v1/media/{id}/processing-status
```

**Response:**

```json
{
  "media_id": "med_abc123",
  "status": "processing",
  "operations": [
    { "type": "transcode", "status": "complete", "progress": 100 },
    { "type": "normalize", "status": "in_progress", "progress": 45 },
    { "type": "generate_waveform", "status": "pending", "progress": 0 }
  ],
  "started_at": "2026-01-03T10:00:00Z",
  "estimated_completion": "2026-01-03T10:10:00Z"
}
```

---

## Quality Analysis

### Analyze Quality

```http
GET /v1/media/{id}/quality-analysis
POST /v1/media/{id}/quality-analysis
```

**Response:**

```json
{
  "media_id": "med_abc123",
  "quality_score": 0.92,
  "analysis": {
    "audio": {
      "lufs": -16.2,
      "peak_db": -1.5,
      "dynamic_range_db": 12,
      "snr_db": 45,
      "clipping_detected": false,
      "artifacts": [],
      "silence_ratio": 0.05
    }
  },
  "recommendations": [
    "Audio levels are optimal",
    "Consider reducing silence at end"
  ],
  "analyzed_at": "2026-01-03T10:05:00Z"
}
```

---

## Waveform

### Get Waveform Data

```http
GET /v1/media/{id}/waveform
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `resolution` | number | Samples per second
(default: 10) | | `format` | string | `json`, `png`, `svg` |

**Response (JSON):**

```json
{
  "media_id": "med_abc123",
  "duration_ms": 600000,
  "sample_rate": 10,
  "peaks": [0.1, 0.3, 0.5, 0.7, 0.4, ...],
  "rms": [0.05, 0.15, 0.25, ...],
  "format": "json"
}
```

---

## Batch Operations

### Batch Upload

```http
POST /v1/media/batch
```

**Request Body:**

```json
{
  "operations": [
    {
      "action": "create",
      "data": {
        "title": "Meditation 1",
        "upload_url": "https://..."
      }
    },
    {
      "action": "create",
      "data": {
        "title": "Meditation 2",
        "upload_url": "https://..."
      }
    }
  ]
}
```

**Response:**

```json
{
  "batch_id": "batch_xyz",
  "results": [
    { "media_id": "med_001", "status": "created" },
    { "media_id": "med_002", "status": "created" }
  ]
}
```

---

## Storage Statistics

### Get Storage Stats

```http
GET /v1/media/storage-stats
```

**Response:**

```json
{
  "total_assets": 15000,
  "total_size_bytes": 500000000000,
  "by_type": {
    "audio": { "count": 12000, "size_bytes": 400000000000 },
    "video": { "count": 2000, "size_bytes": 90000000000 },
    "image": { "count": 1000, "size_bytes": 10000000000 }
  },
  "by_status": {
    "ready": 14500,
    "processing": 300,
    "failed": 200
  },
  "cdn_egress_bytes": 10000000000000
}
```

---

## Transcripts

### Get Transcript

```http
GET /v1/media/{id}/transcript
```

**Query Parameters:** | Parameter | Type | Description |
|-----------|------|-------------| | `format` | string | `json`, `srt`, `vtt` |
| `language` | string | Translation language |

**Response (JSON):**

```json
{
  "media_id": "med_abc123",
  "language": "en",
  "segments": [
    {
      "start_ms": 0,
      "end_ms": 5000,
      "text": "Welcome to this meditation.",
      "confidence": 0.98,
      "speaker": "guide"
    }
  ],
  "word_timings": [{ "word": "Welcome", "start_ms": 0, "end_ms": 500 }]
}
```

### Update Transcript

```http
PUT /v1/media/{id}/transcript
```

---

## HLS/DASH Streaming

### Get Streaming Manifest

```http
GET /v1/media/{id}/stream/manifest.m3u8
GET /v1/media/{id}/stream/manifest.mpd
```

### Get Segment

```http
GET /v1/media/{id}/stream/segments/{segmentFile}
```

---

## CDN Management

### Invalidate CDN Cache

```http
POST /v1/media/{id}/cdn-invalidate
```

### Get CDN Status

```http
GET /v1/media/{id}/cdn-status
```

**Response:**

```json
{
  "media_id": "med_abc123",
  "cdn_cached": true,
  "edge_locations": ["us-east-1", "eu-west-1", "ap-southeast-1"],
  "cache_hits": 15000,
  "bandwidth_bytes": 5000000000
}
```

---

## DRM (Future)

### Get DRM Keys

```http
GET /v1/media/{id}/drm-keys
```

Note: DRM support (Widevine/FairPlay) is on the roadmap.

---

## Error Codes

| Code                      | Description                 |
| ------------------------- | --------------------------- |
| `media.not_found`         | Media asset not found       |
| `media.invalid_format`    | Unsupported file format     |
| `media.too_large`         | File exceeds size limit     |
| `media.processing_failed` | Processing operation failed |
| `media.url_expired`       | Signed URL has expired      |
| `media.quota_exceeded`    | Storage quota exceeded      |

---

## Rate Limits

| Endpoint    | Limit       |
| ----------- | ----------- |
| Upload      | 10 req/min  |
| Get/List    | 100 req/min |
| Processing  | 20 req/min  |
| Signed URLs | 200 req/min |

---

## Supported Formats

### Audio

- Input: WAV, MP3, FLAC, OGG, M4A, AAC
- Output: MP3, Opus, AAC, FLAC

### Video

- Input: MP4, MOV, AVI, MKV, WebM
- Output: MP4 (H.264/H.265), WebM (VP9)

### Image

- Input: JPEG, PNG, WebP, GIF, SVG
- Output: JPEG, PNG, WebP

---

## Related Documentation

- [Audio Streaming Guide](/docs/guides/audio-streaming.md)
- [Media Service README](/services/media/README.md)
- [CDN Configuration](/docs/infrastructure/cdn.md)
