Clean bot folder
Browse files- bot/encoder.py +0 -308
bot/encoder.py
DELETED
|
@@ -1,308 +0,0 @@
|
|
| 1 |
-
"""Video encoding module using FFmpeg."""
|
| 2 |
-
import logging
|
| 3 |
-
import subprocess
|
| 4 |
-
import re
|
| 5 |
-
import json
|
| 6 |
-
from pathlib import Path
|
| 7 |
-
from typing import Optional, Dict, Callable
|
| 8 |
-
from uuid import uuid4
|
| 9 |
-
from config import Config
|
| 10 |
-
from bot.database import db
|
| 11 |
-
|
| 12 |
-
logger = logging.getLogger(__name__)
|
| 13 |
-
|
| 14 |
-
class VideoEncoder:
|
| 15 |
-
"""Handler for video encoding using FFmpeg."""
|
| 16 |
-
|
| 17 |
-
def __init__(self):
|
| 18 |
-
self.encode_dir = Config.ENCODE_DIR
|
| 19 |
-
self.temp_dir = Config.TEMP_DIR
|
| 20 |
-
self.ffmpeg_path = Config.FFMPEG_PATH
|
| 21 |
-
self.ffprobe_path = Config.FFPROBE_PATH
|
| 22 |
-
self.active_encodes: Dict[str, subprocess.Popen] = {}
|
| 23 |
-
|
| 24 |
-
def get_video_info(self, file_path: Path) -> Optional[Dict]:
|
| 25 |
-
"""Get video file information using ffprobe."""
|
| 26 |
-
try:
|
| 27 |
-
cmd = [
|
| 28 |
-
self.ffprobe_path,
|
| 29 |
-
"-v", "error",
|
| 30 |
-
"-show_format",
|
| 31 |
-
"-show_streams",
|
| 32 |
-
"-of", "json",
|
| 33 |
-
str(file_path)
|
| 34 |
-
]
|
| 35 |
-
|
| 36 |
-
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 37 |
-
if result.returncode == 0:
|
| 38 |
-
return json.loads(result.stdout)
|
| 39 |
-
return None
|
| 40 |
-
except Exception as e:
|
| 41 |
-
logger.error(f"ffprobe error: {e}")
|
| 42 |
-
return None
|
| 43 |
-
|
| 44 |
-
def get_duration(self, file_path: Path) -> float:
|
| 45 |
-
"""Get video duration in seconds."""
|
| 46 |
-
try:
|
| 47 |
-
cmd = [
|
| 48 |
-
self.ffprobe_path,
|
| 49 |
-
"-v", "error",
|
| 50 |
-
"-show_entries", "format=duration",
|
| 51 |
-
"-of", "default=noprint_wrappers=1:nokey=1",
|
| 52 |
-
str(file_path)
|
| 53 |
-
]
|
| 54 |
-
|
| 55 |
-
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 56 |
-
return float(result.stdout.strip()) if result.returncode == 0 else 0.0
|
| 57 |
-
except Exception:
|
| 58 |
-
return 0.0
|
| 59 |
-
|
| 60 |
-
def get_audio_info(self, file_path: Path) -> Optional[Dict]:
|
| 61 |
-
"""Get audio stream information using ffprobe."""
|
| 62 |
-
try:
|
| 63 |
-
cmd = [
|
| 64 |
-
self.ffprobe_path,
|
| 65 |
-
"-v", "error",
|
| 66 |
-
"-select_streams", "a:0",
|
| 67 |
-
"-show_entries", "stream=codec_name,bit_rate",
|
| 68 |
-
"-of", "json",
|
| 69 |
-
str(file_path)
|
| 70 |
-
]
|
| 71 |
-
|
| 72 |
-
result = subprocess.run(cmd, capture_output=True, text=True)
|
| 73 |
-
if result.returncode == 0:
|
| 74 |
-
data = json.loads(result.stdout)
|
| 75 |
-
if 'streams' and len(data.get('streams', [])) > 0:
|
| 76 |
-
stream = data['streams'][0]
|
| 77 |
-
return {
|
| 78 |
-
'codec': stream.get('codec_name', 'Unknown'),
|
| 79 |
-
'bitrate': stream.get('bit_rate', 'Unknown')
|
| 80 |
-
}
|
| 81 |
-
return None
|
| 82 |
-
except Exception as e:
|
| 83 |
-
logger.error(f"ffprobe audio error: {e}")
|
| 84 |
-
return None
|
| 85 |
-
|
| 86 |
-
def encode_video(self, input_path: Path, user_id: int,
|
| 87 |
-
settings: Optional[Dict] = None,
|
| 88 |
-
progress_callback: Optional[Callable[[int, str], None]] = None) -> Optional[Path]:
|
| 89 |
-
"""Encode video with specified settings.
|
| 90 |
-
|
| 91 |
-
Args:
|
| 92 |
-
input_path: Path to input video
|
| 93 |
-
user_id: Telegram user ID
|
| 94 |
-
settings: Encoding settings (uses user defaults if not provided)
|
| 95 |
-
progress_callback: Callback function(progress_percent, status_message)
|
| 96 |
-
|
| 97 |
-
Returns:
|
| 98 |
-
Path to encoded file or None if failed
|
| 99 |
-
"""
|
| 100 |
-
task_id = str(uuid4())
|
| 101 |
-
|
| 102 |
-
# Get user settings or use defaults
|
| 103 |
-
if settings is None:
|
| 104 |
-
settings = db.get_user_settings(user_id)
|
| 105 |
-
|
| 106 |
-
# Build output path
|
| 107 |
-
output_name = f"{input_path.stem}_encoded.mkv"
|
| 108 |
-
output_path = self.encode_dir / str(user_id) / output_name
|
| 109 |
-
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 110 |
-
|
| 111 |
-
# Add to database
|
| 112 |
-
db.add_encode_task(task_id, user_id, str(input_path), str(output_path), settings)
|
| 113 |
-
|
| 114 |
-
try:
|
| 115 |
-
db.update_encode_status(task_id, "encoding")
|
| 116 |
-
|
| 117 |
-
# Build FFmpeg command
|
| 118 |
-
cmd = self._build_ffmpeg_command(input_path, output_path, settings)
|
| 119 |
-
|
| 120 |
-
logger.info(f"Starting encode: {' '.join(cmd)}")
|
| 121 |
-
|
| 122 |
-
# Get video duration for progress calculation
|
| 123 |
-
duration = self.get_duration(input_path)
|
| 124 |
-
|
| 125 |
-
# Start encode process
|
| 126 |
-
process = subprocess.Popen(
|
| 127 |
-
cmd,
|
| 128 |
-
stdout=subprocess.PIPE,
|
| 129 |
-
stderr=subprocess.PIPE,
|
| 130 |
-
text=True,
|
| 131 |
-
bufsize=1,
|
| 132 |
-
universal_newlines=True
|
| 133 |
-
)
|
| 134 |
-
|
| 135 |
-
self.active_encodes[task_id] = process
|
| 136 |
-
|
| 137 |
-
# Monitor progress
|
| 138 |
-
last_progress = 0
|
| 139 |
-
for line in process.stderr:
|
| 140 |
-
line = line.strip()
|
| 141 |
-
if "time=" in line and duration > 0:
|
| 142 |
-
progress = self._parse_progress(line, duration)
|
| 143 |
-
if progress and progress_callback and abs(progress - last_progress) >= 5:
|
| 144 |
-
progress_callback(progress, f"Encoding... {progress}%")
|
| 145 |
-
db.update_encode_status(task_id, "encoding", progress)
|
| 146 |
-
last_progress = progress
|
| 147 |
-
|
| 148 |
-
process.wait()
|
| 149 |
-
|
| 150 |
-
if process.returncode == 0:
|
| 151 |
-
db.update_encode_status(task_id, "completed", 100)
|
| 152 |
-
|
| 153 |
-
if progress_callback:
|
| 154 |
-
progress_callback(100, "Encoding completed!")
|
| 155 |
-
|
| 156 |
-
logger.info(f"Encoding completed: {output_path}")
|
| 157 |
-
return output_path
|
| 158 |
-
else:
|
| 159 |
-
stderr = process.stderr.read() if process.stderr else "Unknown error"
|
| 160 |
-
error_msg = f"Encoding failed: {stderr}"
|
| 161 |
-
db.update_encode_status(task_id, "failed", error=error_msg)
|
| 162 |
-
logger.error(error_msg)
|
| 163 |
-
return None
|
| 164 |
-
|
| 165 |
-
except Exception as e:
|
| 166 |
-
error_msg = f"Encoding error: {e}"
|
| 167 |
-
db.update_encode_status(task_id, "failed", error=error_msg)
|
| 168 |
-
logger.error(error_msg)
|
| 169 |
-
return None
|
| 170 |
-
finally:
|
| 171 |
-
if task_id in self.active_encodes:
|
| 172 |
-
del self.active_encodes[task_id]
|
| 173 |
-
|
| 174 |
-
def _build_ffmpeg_command(self, input_path: Path, output_path: Path, settings: Dict) -> list:
|
| 175 |
-
"""Build FFmpeg command based on settings."""
|
| 176 |
-
cmd = [
|
| 177 |
-
self.ffmpeg_path,
|
| 178 |
-
"-i", str(input_path),
|
| 179 |
-
"-y", # Overwrite output
|
| 180 |
-
]
|
| 181 |
-
|
| 182 |
-
# Video codec settings
|
| 183 |
-
codec = settings.get("codec", Config.DEFAULT_CODEC)
|
| 184 |
-
crf = settings.get("crf", Config.DEFAULT_CRF)
|
| 185 |
-
preset = settings.get("preset", Config.DEFAULT_PRESET)
|
| 186 |
-
resolution = settings.get("resolution", "original")
|
| 187 |
-
|
| 188 |
-
# Video filter
|
| 189 |
-
vf_parts = []
|
| 190 |
-
if resolution != "original":
|
| 191 |
-
height = resolution.replace("p", "")
|
| 192 |
-
vf_parts.append(f"scale=-2:{height}")
|
| 193 |
-
|
| 194 |
-
# Apply video filter if any
|
| 195 |
-
if vf_parts:
|
| 196 |
-
cmd.extend(["-vf", ",".join(vf_parts)])
|
| 197 |
-
|
| 198 |
-
# Video codec configuration
|
| 199 |
-
cmd.extend([
|
| 200 |
-
"-c:v", codec,
|
| 201 |
-
"-preset", preset,
|
| 202 |
-
"-crf", str(crf),
|
| 203 |
-
"-pix_fmt", "yuv420p",
|
| 204 |
-
])
|
| 205 |
-
|
| 206 |
-
# 10-bit support for HEVC/H265
|
| 207 |
-
if "265" in codec or "hevc" in codec.lower():
|
| 208 |
-
cmd.extend(["-pix_fmt", "yuv420p10le"])
|
| 209 |
-
|
| 210 |
-
# Audio codec settings
|
| 211 |
-
audio_codec = settings.get("audio_codec", Config.DEFAULT_AUDIO_CODEC)
|
| 212 |
-
audio_bitrate = settings.get("audio_bitrate", Config.DEFAULT_AUDIO_BITRATE)
|
| 213 |
-
|
| 214 |
-
cmd.extend([
|
| 215 |
-
"-c:a", audio_codec,
|
| 216 |
-
"-b:a", audio_bitrate,
|
| 217 |
-
])
|
| 218 |
-
|
| 219 |
-
# Audio channels
|
| 220 |
-
if "channels" in settings:
|
| 221 |
-
cmd.extend(["-ac", str(settings["channels"])])
|
| 222 |
-
|
| 223 |
-
# Hardsub subtitles
|
| 224 |
-
if settings.get("hardsub", False):
|
| 225 |
-
cmd.extend([
|
| 226 |
-
"-vf", "subtitles='" + str(input_path) + "'",
|
| 227 |
-
])
|
| 228 |
-
|
| 229 |
-
# Copy subtitle streams if not hardsubbing
|
| 230 |
-
if not settings.get("hardsub", False):
|
| 231 |
-
cmd.extend(["-c:s", "copy"])
|
| 232 |
-
|
| 233 |
-
# Faststart for web playback
|
| 234 |
-
cmd.extend(["-movflags", "+faststart"])
|
| 235 |
-
|
| 236 |
-
# Output file
|
| 237 |
-
cmd.append(str(output_path))
|
| 238 |
-
|
| 239 |
-
return cmd
|
| 240 |
-
|
| 241 |
-
def _parse_progress(self, line: str, duration: float) -> Optional[int]:
|
| 242 |
-
"""Parse encoding progress from FFmpeg output."""
|
| 243 |
-
match = re.search(r'time=(\d+):(\d+):(\d+\.?\d*)', line)
|
| 244 |
-
if match and duration > 0:
|
| 245 |
-
hours, minutes, seconds = match.groups()
|
| 246 |
-
current_time = float(hours) * 3600 + float(minutes) * 60 + float(seconds)
|
| 247 |
-
progress = int((current_time / duration) * 100)
|
| 248 |
-
return min(progress, 100)
|
| 249 |
-
return None
|
| 250 |
-
|
| 251 |
-
def cancel_encode(self, task_id: str) -> bool:
|
| 252 |
-
"""Cancel an active encoding."""
|
| 253 |
-
if task_id in self.active_encodes:
|
| 254 |
-
process = self.active_encodes[task_id]
|
| 255 |
-
process.terminate()
|
| 256 |
-
try:
|
| 257 |
-
process.wait(timeout=5)
|
| 258 |
-
except subprocess.TimeoutExpired:
|
| 259 |
-
process.kill()
|
| 260 |
-
|
| 261 |
-
db.update_encode_status(task_id, "cancelled")
|
| 262 |
-
del self.active_encodes[task_id]
|
| 263 |
-
return True
|
| 264 |
-
return False
|
| 265 |
-
|
| 266 |
-
def reencode_audio(self, input_path: Path, output_path: Path,
|
| 267 |
-
audio_codec: str = "aac", bitrate: str = "128k",
|
| 268 |
-
channels: int = 2) -> bool:
|
| 269 |
-
"""Re-encode only audio stream."""
|
| 270 |
-
try:
|
| 271 |
-
cmd = [
|
| 272 |
-
self.ffmpeg_path,
|
| 273 |
-
"-i", str(input_path),
|
| 274 |
-
"-c:v", "copy",
|
| 275 |
-
"-c:a", audio_codec,
|
| 276 |
-
"-b:a", bitrate,
|
| 277 |
-
"-ac", str(channels),
|
| 278 |
-
"-y",
|
| 279 |
-
str(output_path)
|
| 280 |
-
]
|
| 281 |
-
|
| 282 |
-
result = subprocess.run(cmd, capture_output=True)
|
| 283 |
-
return result.returncode == 0
|
| 284 |
-
except Exception as e:
|
| 285 |
-
logger.error(f"Audio re-encode error: {e}")
|
| 286 |
-
return False
|
| 287 |
-
|
| 288 |
-
def extract_audio(self, input_path: Path, output_path: Path,
|
| 289 |
-
audio_codec: str = "mp3") -> bool:
|
| 290 |
-
"""Extract audio from video."""
|
| 291 |
-
try:
|
| 292 |
-
cmd = [
|
| 293 |
-
self.ffmpeg_path,
|
| 294 |
-
"-i", str(input_path),
|
| 295 |
-
"-vn", # No video
|
| 296 |
-
"-c:a", audio_codec,
|
| 297 |
-
"-y",
|
| 298 |
-
str(output_path)
|
| 299 |
-
]
|
| 300 |
-
|
| 301 |
-
result = subprocess.run(cmd, capture_output=True)
|
| 302 |
-
return result.returncode == 0
|
| 303 |
-
except Exception as e:
|
| 304 |
-
logger.error(f"Audio extract error: {e}")
|
| 305 |
-
return False
|
| 306 |
-
|
| 307 |
-
# Global encoder instance
|
| 308 |
-
encoder = VideoEncoder()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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