Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
HOST=0.0.0.0
PORT=7000
BASE_URL=http://127.0.0.1:7000
CACHE_DIR=.cache
CACHE_TTL_SECONDS=86400
MAX_RESULTS=8
MIN_CONFIDENCE=0.55

# Required for OpenSubtitles search/download.
OPENSUBTITLES_API_KEY=
OPENSUBTITLES_TOKEN=
OPENSUBTITLES_USER_AGENT=StremioSubEngine v0.1.0

# none | libretranslate | ollama
TRANSLATOR=none
LIBRETRANSLATE_URL=http://127.0.0.1:5000
LIBRETRANSLATE_API_KEY=
OLLAMA_URL=http://127.0.0.1:11434
OLLAMA_MODEL=qwen3:4b
TRANSLATION_CONCURRENCY=4

# Full media-aware synchronization/ASR. Keep disabled on public Internet hosts unless you understand the SSRF implications.
ENABLE_MEDIA_ACCESS=false
ALLOW_PRIVATE_STREAMS=true
SYNC_ENGINE=ffsubsync
FFSUBSYNC_COMMAND=ffsubsync
ALASS_COMMAND=alass-cli
SYNC_TIMEOUT_MS=180000

ENABLE_ASR=false
PYTHON_COMMAND=python3
ASR_MODEL=small
ASR_DEVICE=auto
ASR_COMPUTE_TYPE=auto
ASR_TIMEOUT_MS=900000
16 changes: 16 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name: CI
on:
push:
branches: [main]
pull_request:

jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm test
- run: npm run check
6 changes: 6 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.cache/
.env
node_modules/
.DS_Store
__pycache__/
*.pyc
12 changes: 12 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
FROM node:22-bookworm-slim

RUN apt-get update && apt-get install -y --no-install-recommends ffmpeg python3 python3-pip ca-certificates \
&& pip3 install --break-system-packages 'ffsubsync==0.5.1' 'faster-whisper>=1.1,<2' \
&& rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY . .
RUN mkdir -p /data/cache
ENV CACHE_DIR=/data/cache HOST=0.0.0.0 PORT=7000
EXPOSE 7000
CMD ["node", "src/index.mjs"]
7 changes: 7 additions & 0 deletions Dockerfile.lite
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
FROM node:22-bookworm-slim
WORKDIR /app
COPY . .
RUN mkdir -p /data/cache
ENV CACHE_DIR=/data/cache HOST=0.0.0.0 PORT=7000 ENABLE_MEDIA_ACCESS=false ENABLE_ASR=false
EXPOSE 7000
CMD ["node", "src/index.mjs"]
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 SaymonMaster14

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
171 changes: 170 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,172 @@
# Stremio Sub Engine

Bootstrap commit. The implementation is developed through pull requests.
A self-hosted Stremio subtitle add-on that treats subtitles as a resolution problem rather than a single-provider lookup:

1. identify the exact video release from `videoHash`, `videoSize`, filename and IMDb/episode identity;
2. rank subtitle candidates by confidence;
3. prefer a correctly timed subtitle in the target language;
4. otherwise use a synchronized subtitle in another language and translate only its text, preserving timestamps;
5. when the Stremio request exposes an accessible `streamUrl`, optionally align against the actual audio with `ffsubsync`/ALASS;
6. if no subtitle exists at all, optionally fall back to `faster-whisper` ASR.

The project intentionally separates **resolution**, **alignment**, and **transformation**. ASR is the last fallback, not the default path.

## What works with Stremio today

Current subtitle requests can include `videoHash`, `videoSize` and `filename`. That is enough for exact OpenSubtitles hash matching and strong release-name matching. Translation works server-side while preserving the matched subtitle's timestamps.

Current Stremio clients do **not universally pass the selected stream URL to subtitle add-ons**. Therefore audio-aware synchronization and ASR cannot be guaranteed by a normal remote add-on today. This repository already implements those code paths and consumes an optional `streamUrl` extra when available.

Full media-aware mode is most useful when this add-on is self-hosted on the same machine/network namespace as a Stremio streaming server, or when the selected stream URL is otherwise reachable from the add-on host.

## Quick start

Requirements for the normal mode:

- Node.js 22+
- an OpenSubtitles REST API key

```bash
cp .env.example .env
# set OPENSUBTITLES_API_KEY in .env
node src/index.mjs
```

Open `http://127.0.0.1:7000/configure`, choose preferences, and press **Install in Stremio**.

No npm dependencies are required at runtime.

## Docker

The default Docker image includes FFmpeg, ffsubsync 0.5.1 and faster-whisper so full media-aware mode can be enabled without changing images:

```bash
cp .env.example .env
docker compose up -d addon
```

For lookup/translation-only deployments, `Dockerfile.lite` omits Python/FFmpeg tooling.

### Free/open-source translation

Two local/self-hostable translation backends are implemented:

- `TRANSLATOR=libretranslate` — LibreTranslate HTTP API.
- `TRANSLATOR=ollama` — an Ollama model using structured JSON batches.

To run LibreTranslate alongside the add-on:

```bash
docker compose --profile translate up -d
```

Set `TRANSLATOR=libretranslate` and, from inside Compose, `LIBRETRANSLATE_URL=http://libretranslate:5000`.

## OpenSubtitles

Configure:

```env
OPENSUBTITLES_API_KEY=...
OPENSUBTITLES_TOKEN=... # optional; useful for authenticated quota
```

The resolver performs bounded searches using exact file hash first, then IMDb/season/episode identity. Results are deduplicated and ranked using:

- OpenSubtitles movie-hash match;
- IMDb identity match;
- release/filename token similarity;
- target-language match;
- trusted-uploader and accessibility metadata.

Only candidates above the configured confidence threshold are returned to Stremio. This avoids auto-selecting a random same-title subtitle just because one exists.

## Translation pipeline

A foreign-language subtitle is only translated when its timing confidence is high enough. The parser converts SRT/WebVTT into cue objects, translates cue text, and renders fresh SRT while leaving cue start/end timestamps unchanged.

Ollama batches cues and requires an equal-length JSON response. LibreTranslate uses bounded concurrency per cue. Generated subtitles are cached on disk.

## Full synchronization

Enable explicit media access:

```env
ENABLE_MEDIA_ACCESS=true
SYNC_ENGINE=ffsubsync
```

When a subtitle request contains `streamUrl`, the materialization pipeline can run:

```text
ffsubsync <streamUrl> -i input.srt -o output.srt \
--multi-segment-sync --segment-count 6 \
--skip-intro-outro --parallel-workers 4 \
--skip-sync-on-low-quality
```

This uses sparse samples across the reference rather than blindly processing the entire movie. `SYNC_ENGINE=alass` is also supported when `alass-cli` is installed.

### Security

Media access is **off by default** because a server that accepts arbitrary stream URLs can become an SSRF primitive. Keep it disabled on public hosts unless stream URL input is trusted and network access is isolated. `ALLOW_PRIVATE_STREAMS=false` rejects obvious loopback/private literal IPs.

## ASR fallback

Enable:

```env
ENABLE_MEDIA_ACCESS=true
ENABLE_ASR=true
ASR_MODEL=small
ASR_DEVICE=auto
ASR_COMPUTE_TYPE=auto
```

If there are no accepted subtitle candidates and an accessible `streamUrl` exists, Stremio receives an ASR fallback subtitle URL. On first fetch, `tools/asr_faster_whisper.py` transcribes the stream and emits SRT. The result is cached.

ASR is deliberately last because it is much more expensive than reusing an existing correctly timed subtitle.

## Stremio endpoints

- `/manifest.json` — unconfigured manifest;
- `/configure` — custom configuration page;
- `/<base64url-prefs>/manifest.json` — configured add-on manifest;
- `/<prefs>/subtitles/{type}/{id}/{extra}.json` — subtitle resolution;
- `/subtitle/{opaque-job-id}.srt` — lazy download/sync/translate/ASR materialization;
- `/health` — enabled provider/capability status without exposing secrets.

The opaque job URL is intentional: selected stream URLs and provider credentials are not embedded in the subtitle URL returned to the player.

## Development

```bash
npm test
npm run check
```

The codebase has zero Node runtime dependencies and uses the built-in Node test runner.

## Architecture

```text
Stremio subtitle request
|
v
release identity (IMDb + hash + filename)
|
v
provider searches -> dedupe -> confidence ranking
|
+-- target language, good timing -------------------+
| |
+-- foreign language, good timing -> translation ---+--> cached SRT
| |
+-- streamUrl available -> audio alignment ---------+
| |
+-- no subtitle -> faster-whisper ASR --------------+
```

## License

MIT.
21 changes: 21 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
services:
addon:
build: .
ports:
- "7000:7000"
env_file: .env
volumes:
- subtitle-cache:/data/cache
restart: unless-stopped

libretranslate:
image: libretranslate/libretranslate:latest
profiles: ["translate"]
environment:
LT_LOAD_ONLY: en,pt,es,fr,de,it
ports:
- "5000:5000"
restart: unless-stopped

volumes:
subtitle-cache:
16 changes: 16 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "stremio-sub-engine",
"version": "0.1.0",
"private": false,
"description": "Self-hosted Stremio subtitle resolution, translation, synchronization and ASR fallback engine.",
"type": "module",
"engines": { "node": ">=22" },
"scripts": {
"start": "node src/index.mjs",
"dev": "node --watch src/index.mjs",
"test": "node --test",
"check": "node tools/check.mjs"
},
"keywords": ["stremio", "subtitles", "opensubtitles", "translation", "ffsubsync", "whisper"],
"license": "MIT"
}
Loading
Loading