Multi-Connection Striping (#44)
Browse files* New Feature added
* Update README.md
* Update README.md
* Update README.md
* Update README.md
* 2.1.0 - SUBSCRIPTION added
* Update start.sh
* Free Mode Toggle, Automatic Stream Cleanup, Manual IMDb/TMDb Override - Added
- 🆓 **Free Mode Toggle** – Administrators can turn off the `SUBSCRIPTION` requirement in `config.env` to allow all users immediate access via an automatically generated API token.
- 🔄 **Automatic Stream Cleanup** – Deleting a source message in the Telegram channel instantly deletes all corresponding streams and qualities from the Stremio Addon Database and Admin Panel, preventing dead links.
- 🏷️ **Manual IMDb/TMDb Override** – Users can instantly update or fix incorrect metadata for a file by simply editing the Telegram channel message caption and pasting the correct IMDb/TMDB URL.
* Proxy and DC aware Bot option added
- 🛡️ **Stream Stability & Recovery** – Intelligent `b""` empty-chunk fallback that securely pads video streams with zero bytes, and reduced chunk retry lockups (from 6 to 3) to instantaneously recover from stalled parts without breaking the video player.
- 🎯 **DC-Aware Bot Selection** – The underlying streaming load-balancer now ensures that a bot located in the exact same Data Center as the media file is prioritized. This substantially minimizes cross-DC round-trips and timeouts.
- 🌐 **Addon Proxy Integration** – Built-in functionality targeting `config.env` configurations (`Proxy`, `ProxyType`, `HTTP_Proxy_URL`, `SHOW_ProxyAndNonProxyBoth`) allows instant proxying or caching of video streams (such as routing through Cloudflare Workers) natively on Stremio.
* sample config for proxy
# Proxy Configs
Proxy=True
ProxyType=HTTPS
HTTP_Proxy_URL="" #example https://PROXYURL/?url=
SHOW_ProxyAndNonProxyBoth=True # this will show both link proxy and non proxy both
* proxy corrected
* Multi-Connection Striping
dc to dc distribution and
Multiplied Bandwidth: If 3 bots fetch concurrently, you theoretically leap from 10 MB/s to 30 MB/s for a single 4K stream since the Telegram API rate limits apply to the individual bot tokens, not the overarching FastAPI server!
the "pro trick" used by high-speed download managers (like Internet Download Manager) to multiply download speeds—it's called Multi-Connection Striping.
Right now, as we put in the README, Telegram limits the download speed per bot/session. So if Telegram caps one bot at 10 MB/s, your stream can only ever reach 10 MB/s, even if you have 3 workers fetching chunks. They are all bottlenecked by that single bot limit.
If we rewrite the streamer to use all matching DC bots simultaneously on a single stream: Worker 1 → Fetches chunk 1 via Bot A Worker 2 → Fetches chunk 2 via Bot B Worker 3 → Fetches chunk 3 via Bot C
---------
Co-authored-by: vflixa1prime <vflixa1prime@atomicmail.io>
Co-authored-by: Karan Adhikari <doc.adhikari@gmail.com>
|
@@ -259,7 +259,19 @@ async def media_streamer(
|
|
| 259 |
target_dc = file_id.dc_id
|
| 260 |
LOGGER.debug(f"File msg_id={msg_id} is in DC {target_dc}")
|
| 261 |
|
| 262 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
tg_client = multi_clients[index]
|
| 264 |
|
| 265 |
if tg_client not in _streamer_by_client:
|
|
@@ -316,6 +328,7 @@ async def media_streamer(
|
|
| 316 |
meta=meta,
|
| 317 |
parallelism=parallelism,
|
| 318 |
request=request,
|
|
|
|
| 319 |
)
|
| 320 |
|
| 321 |
asyncio.create_task(track_usage_from_stats(stream_id, token, token_data))
|
|
|
|
| 259 |
target_dc = file_id.dc_id
|
| 260 |
LOGGER.debug(f"File msg_id={msg_id} is in DC {target_dc}")
|
| 261 |
|
| 262 |
+
def _score(idx: int) -> int:
|
| 263 |
+
from Backend.pyrofork.bot import work_loads, client_failures
|
| 264 |
+
return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
|
| 265 |
+
|
| 266 |
+
# Multi-connection striping: get all matching bots in DC, otherwise fallback globally
|
| 267 |
+
dc_clients = [idx for idx, dc in client_dc_map.items() if dc == target_dc and idx in multi_clients]
|
| 268 |
+
if dc_clients:
|
| 269 |
+
client_pool = sorted(dc_clients, key=_score)
|
| 270 |
+
else:
|
| 271 |
+
client_pool = [select_best_client(target_dc)]
|
| 272 |
+
|
| 273 |
+
# Primary client is the healthiest one
|
| 274 |
+
index = client_pool[0]
|
| 275 |
tg_client = multi_clients[index]
|
| 276 |
|
| 277 |
if tg_client not in _streamer_by_client:
|
|
|
|
| 328 |
meta=meta,
|
| 329 |
parallelism=parallelism,
|
| 330 |
request=request,
|
| 331 |
+
client_pool=client_pool,
|
| 332 |
)
|
| 333 |
|
| 334 |
asyncio.create_task(track_usage_from_stats(stream_id, token, token_data))
|
|
@@ -2,7 +2,7 @@ import asyncio
|
|
| 2 |
import time
|
| 3 |
import secrets
|
| 4 |
from collections import deque
|
| 5 |
-
from typing import Dict, List, Union, Optional, Tuple
|
| 6 |
import traceback
|
| 7 |
from fastapi import Request
|
| 8 |
from pyrogram import Client, raw, utils
|
|
@@ -117,19 +117,20 @@ class ByteStreamer:
|
|
| 117 |
|
| 118 |
async def prefetch_stream(
|
| 119 |
self,
|
| 120 |
-
file_id
|
| 121 |
client_index: int,
|
| 122 |
offset: int,
|
| 123 |
first_part_cut: int,
|
| 124 |
last_part_cut: int,
|
| 125 |
part_count: int,
|
| 126 |
chunk_size: int,
|
| 127 |
-
prefetch: int
|
| 128 |
-
stream_id:
|
| 129 |
-
meta:
|
| 130 |
-
parallelism: int =
|
| 131 |
-
request
|
| 132 |
-
|
|
|
|
| 133 |
if not stream_id:
|
| 134 |
stream_id = secrets.token_hex(8)
|
| 135 |
|
|
@@ -160,47 +161,59 @@ class ByteStreamer:
|
|
| 160 |
q: asyncio.Queue = asyncio.Queue(maxsize=queue_maxsize)
|
| 161 |
stop_event = asyncio.Event()
|
| 162 |
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
location = await self._get_location(file_id)
|
| 165 |
|
| 166 |
async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
|
| 167 |
-
"""Fetch one chunk with timeout, exponential back-off, and bot
|
| 168 |
-
|
| 169 |
-
Retry schedule (max 3 tries):
|
| 170 |
-
tries 0 → same bot / same session, 15 s timeout each
|
| 171 |
-
tries 1-2 → try a healthier fallback bot (if available),
|
| 172 |
-
still with 15 s timeout
|
| 173 |
-
On every TimeoutError the primary client's failure counter is incremented
|
| 174 |
-
so select_best_client will avoid it for future requests.
|
| 175 |
"""
|
|
|
|
|
|
|
|
|
|
| 176 |
tries = 0
|
| 177 |
while tries < 3 and not stop_event.is_set():
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
if tries >= 1 and len(
|
| 182 |
-
# Pick the best *other* client by score = workload + 3×failures
|
| 183 |
def _score(idx):
|
| 184 |
return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
|
| 185 |
fallback_idx = min(
|
| 186 |
-
(i for i in
|
| 187 |
key=_score,
|
| 188 |
default=None,
|
| 189 |
)
|
| 190 |
if fallback_idx is not None:
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
LOGGER.debug(
|
| 198 |
-
"Chunk fallback: seq=%s try=%s primary=%s → fallback=%s",
|
| 199 |
-
seq_idx, tries, client_index, fallback_idx,
|
| 200 |
-
)
|
| 201 |
-
except Exception:
|
| 202 |
-
use_session = media_session # revert if fallback session fails
|
| 203 |
-
use_client_idx = client_index
|
| 204 |
|
| 205 |
# --- attempt the fetch with a hard timeout ---
|
| 206 |
try:
|
|
@@ -218,8 +231,8 @@ class ByteStreamer:
|
|
| 218 |
return seq_idx, None
|
| 219 |
|
| 220 |
# If we succeeded via a fallback, mark primary as degraded
|
| 221 |
-
if use_client_idx !=
|
| 222 |
-
client_failures[
|
| 223 |
return seq_idx, chunk_bytes
|
| 224 |
|
| 225 |
except asyncio.TimeoutError:
|
|
@@ -241,7 +254,7 @@ class ByteStreamer:
|
|
| 241 |
|
| 242 |
LOGGER.error(
|
| 243 |
"Failed to fetch chunk seq=%s off=%s after 3 retries, client=%s",
|
| 244 |
-
seq_idx, off,
|
| 245 |
)
|
| 246 |
return seq_idx, None
|
| 247 |
|
|
|
|
| 2 |
import time
|
| 3 |
import secrets
|
| 4 |
from collections import deque
|
| 5 |
+
from typing import Dict, List, Union, Optional, Tuple, AsyncGenerator
|
| 6 |
import traceback
|
| 7 |
from fastapi import Request
|
| 8 |
from pyrogram import Client, raw, utils
|
|
|
|
| 117 |
|
| 118 |
async def prefetch_stream(
|
| 119 |
self,
|
| 120 |
+
file_id,
|
| 121 |
client_index: int,
|
| 122 |
offset: int,
|
| 123 |
first_part_cut: int,
|
| 124 |
last_part_cut: int,
|
| 125 |
part_count: int,
|
| 126 |
chunk_size: int,
|
| 127 |
+
prefetch: int,
|
| 128 |
+
stream_id: str,
|
| 129 |
+
meta: dict,
|
| 130 |
+
parallelism: int = 1,
|
| 131 |
+
request = None,
|
| 132 |
+
client_pool: list = None,
|
| 133 |
+
) -> AsyncGenerator[bytes, None]:
|
| 134 |
if not stream_id:
|
| 135 |
stream_id = secrets.token_hex(8)
|
| 136 |
|
|
|
|
| 161 |
q: asyncio.Queue = asyncio.Queue(maxsize=queue_maxsize)
|
| 162 |
stop_event = asyncio.Event()
|
| 163 |
|
| 164 |
+
multi_clients = getattr(self, "_multi_clients", None)
|
| 165 |
+
if multi_clients is None:
|
| 166 |
+
from Backend.pyrofork.bot import multi_clients
|
| 167 |
+
|
| 168 |
+
client_pool = client_pool or [client_index]
|
| 169 |
+
|
| 170 |
+
active_pool = []
|
| 171 |
+
pool_sessions = {}
|
| 172 |
+
for c in client_pool:
|
| 173 |
+
c_streamer = ByteStreamer._instances.get(c)
|
| 174 |
+
if c_streamer is None and c in multi_clients:
|
| 175 |
+
c_streamer = ByteStreamer(multi_clients[c], c)
|
| 176 |
+
if c_streamer:
|
| 177 |
+
try:
|
| 178 |
+
pool_sessions[c] = await c_streamer._get_media_session(file_id)
|
| 179 |
+
active_pool.append(c)
|
| 180 |
+
except Exception as e:
|
| 181 |
+
LOGGER.error("Could not get session for bot %s: %s", c, e)
|
| 182 |
+
|
| 183 |
+
if not active_pool:
|
| 184 |
+
active_pool = [client_index]
|
| 185 |
+
pool_sessions[client_index] = await self._get_media_session(file_id)
|
| 186 |
+
|
| 187 |
+
LOGGER.debug("Striping stream %s across clients: %s", stream_id, active_pool)
|
| 188 |
+
|
| 189 |
location = await self._get_location(file_id)
|
| 190 |
|
| 191 |
async def fetch_chunk_with_retries(seq_idx: int, off: int) -> Tuple[int, Optional[bytes]]:
|
| 192 |
+
"""Fetch one chunk with timeout, exponential back-off, and round-robin bot striping.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
"""
|
| 194 |
+
primary_client_idx = active_pool[seq_idx % len(active_pool)]
|
| 195 |
+
primary_session = pool_sessions[primary_client_idx]
|
| 196 |
+
|
| 197 |
tries = 0
|
| 198 |
while tries < 3 and not stop_event.is_set():
|
| 199 |
+
use_session = primary_session
|
| 200 |
+
use_client_idx = primary_client_idx
|
| 201 |
+
|
| 202 |
+
if tries >= 1 and len(active_pool) > 1:
|
|
|
|
| 203 |
def _score(idx):
|
| 204 |
return work_loads.get(idx, 0) + 3 * client_failures.get(idx, 0)
|
| 205 |
fallback_idx = min(
|
| 206 |
+
(i for i in active_pool if i != primary_client_idx),
|
| 207 |
key=_score,
|
| 208 |
default=None,
|
| 209 |
)
|
| 210 |
if fallback_idx is not None:
|
| 211 |
+
use_session = pool_sessions[fallback_idx]
|
| 212 |
+
use_client_idx = fallback_idx
|
| 213 |
+
LOGGER.debug(
|
| 214 |
+
"Chunk fallback: seq=%s try=%s primary=%s → fallback=%s",
|
| 215 |
+
seq_idx, tries, primary_client_idx, fallback_idx,
|
| 216 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
|
| 218 |
# --- attempt the fetch with a hard timeout ---
|
| 219 |
try:
|
|
|
|
| 231 |
return seq_idx, None
|
| 232 |
|
| 233 |
# If we succeeded via a fallback, mark primary as degraded
|
| 234 |
+
if use_client_idx != primary_client_idx:
|
| 235 |
+
client_failures[primary_client_idx] = client_failures.get(primary_client_idx, 0) + 1
|
| 236 |
return seq_idx, chunk_bytes
|
| 237 |
|
| 238 |
except asyncio.TimeoutError:
|
|
|
|
| 254 |
|
| 255 |
LOGGER.error(
|
| 256 |
"Failed to fetch chunk seq=%s off=%s after 3 retries, client=%s",
|
| 257 |
+
seq_idx, off, primary_client_idx,
|
| 258 |
)
|
| 259 |
return seq_idx, None
|
| 260 |
|