# FFmpeg Stream Proxy — MKV → MP4 Browser Playback

Real-Debrid unrestricted links point to MKV files. Browsers can't play MKV. 
FFmpeg transmuxes MKV → fragmented MP4 in real-time (no re-encode, near-zero CPU).

## Node.js Express Route

```js
import { spawn } from 'child_process';
import https from 'https';

export function streamProxyHandler(req, res) {
  const rdUrl = req.query.url;
  if (!rdUrl) return res.status(400).json({ error: 'Missing url' });

  // HEAD request to detect MKV
  https.request(rdUrl, { method: 'HEAD' }, (headRes) => {
    const isMkv = rdUrl.includes('.mkv') || (headRes.headers['content-type'] || '').includes('matroska');

    if (!isMkv) {
      // Direct proxy for MP4/WEBM
      return https.get(rdUrl, { headers: { 'User-Agent': 'Mozilla/5.0' } }, (proxyRes) => {
        res.set({ 
          'Access-Control-Allow-Origin': '*',
          'Content-Type': proxyRes.headers['content-type'] || 'video/mp4',
          'Cache-Control': 'no-cache',
        });
        res.status(proxyRes.statusCode || 200);
        proxyRes.pipe(res);
      }).on('error', (e) => res.status(500).json({ error: e.message }));
    }

    // Transmux MKV → fragmented MP4
    res.set({
      'Access-Control-Allow-Origin': '*',
      'Content-Type': 'video/mp4',
      'Transfer-Encoding': 'chunked',
      'Cache-Control': 'no-cache',
    });
    res.status(200);

    const ffmpeg = spawn('ffmpeg', [
      '-i', rdUrl,
      '-c', 'copy',                              // Copy codecs, no re-encode
      '-movflags', 'frag_keyframe+empty_moov',   // Fragmented MP4 for instant playback
      '-f', 'mp4',
      '-loglevel', 'error',
      'pipe:1',
    ]);

    ffmpeg.stdout.pipe(res);
    ffmpeg.stderr.on('data', (d) => console.error('[FFMPEG]', d.toString()));
    ffmpeg.on('close', (code) => { if (!res.writableEnded) res.end(); });
    req.on('close', () => ffmpeg.kill('SIGTERM'));
  }).on('error', (e) => res.status(502).json({ error: e.message })).end();
}
```

## Docker

Add to Dockerfile (Alpine): `RUN apk add --no-cache ffmpeg`

## Frontend Usage

```html
<!-- Browser plays the transmuxed stream -->
<video src="/api/stream?url=${encodeURIComponent(rdDownloadUrl)}" controls></video>
```

## Limitations

- **Codec support**: If the MKV contains AV1 (no hardware decode on most machines) or HEVC (Chrome requires paid license), browser still can't play. Show VLC fallback link.
- **Seeking**: Fragmented MP4 supports seeking on supported codecs.
- **Bandwidth**: FFmpeg copies bytes 1:1 — a 71GB 4K REMUX still sends 71GB through the server. For production, use the direct RD link with a player like VLC/MPV that handles MKV natively.

## VLC Fallback

When browser playback fails, show the direct RD download URL:

```html
<a href="${rdUrl}" target="_blank">Open in VLC (Media → Open Network Stream)</a>
```
