File size: 11,082 Bytes
7cb306b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
"""Video encoding module using FFmpeg."""
import logging
import subprocess
import re
import json
from pathlib import Path
from typing import Optional, Dict, Callable
from uuid import uuid4
from config import Config
from bot.database import db

logger = logging.getLogger(__name__)

class VideoEncoder:
    """Handler for video encoding using FFmpeg."""
    
    def __init__(self):
        self.encode_dir = Config.ENCODE_DIR
        self.temp_dir = Config.TEMP_DIR
        self.ffmpeg_path = Config.FFMPEG_PATH
        self.ffprobe_path = Config.FFPROBE_PATH
        self.active_encodes: Dict[str, subprocess.Popen] = {}
    
    def get_video_info(self, file_path: Path) -> Optional[Dict]:
        """Get video file information using ffprobe."""
        try:
            cmd = [
                self.ffprobe_path,
                "-v", "error",
                "-show_format",
                "-show_streams",
                "-of", "json",
                str(file_path)
            ]
            
            result = subprocess.run(cmd, capture_output=True, text=True)
            if result.returncode == 0:
                return json.loads(result.stdout)
            return None
        except Exception as e:
            logger.error(f"ffprobe error: {e}")
            return None
    
    def get_duration(self, file_path: Path) -> float:
        """Get video duration in seconds."""
        try:
            cmd = [
                self.ffprobe_path,
                "-v", "error",
                "-show_entries", "format=duration",
                "-of", "default=noprint_wrappers=1:nokey=1",
                str(file_path)
            ]
            
            result = subprocess.run(cmd, capture_output=True, text=True)
            return float(result.stdout.strip()) if result.returncode == 0 else 0.0
        except Exception:
            return 0.0
    
    def get_audio_info(self, file_path: Path) -> Optional[Dict]:
        """Get audio stream information using ffprobe."""
        try:
            cmd = [
                self.ffprobe_path,
                "-v", "error",
                "-select_streams", "a:0",
                "-show_entries", "stream=codec_name,bit_rate",
                "-of", "json",
                str(file_path)
            ]
            
            result = subprocess.run(cmd, capture_output=True, text=True)
            if result.returncode == 0:
                data = json.loads(result.stdout)
                if 'streams' and len(data.get('streams', [])) > 0:
                    stream = data['streams'][0]
                    return {
                        'codec': stream.get('codec_name', 'Unknown'),
                        'bitrate': stream.get('bit_rate', 'Unknown')
                    }
            return None
        except Exception as e:
            logger.error(f"ffprobe audio error: {e}")
            return None
    
    def encode_video(self, input_path: Path, user_id: int, 
                     settings: Optional[Dict] = None,
                     progress_callback: Optional[Callable[[int, str], None]] = None) -> Optional[Path]:
        """Encode video with specified settings.
        
        Args:
            input_path: Path to input video
            user_id: Telegram user ID
            settings: Encoding settings (uses user defaults if not provided)
            progress_callback: Callback function(progress_percent, status_message)
            
        Returns:
            Path to encoded file or None if failed
        """
        task_id = str(uuid4())
        
        # Get user settings or use defaults
        if settings is None:
            settings = db.get_user_settings(user_id)
        
        # Build output path
        output_name = f"{input_path.stem}_encoded.mkv"
        output_path = self.encode_dir / str(user_id) / output_name
        output_path.parent.mkdir(parents=True, exist_ok=True)
        
        # Add to database
        db.add_encode_task(task_id, user_id, str(input_path), str(output_path), settings)
        
        try:
            db.update_encode_status(task_id, "encoding")
            
            # Build FFmpeg command
            cmd = self._build_ffmpeg_command(input_path, output_path, settings)
            
            logger.info(f"Starting encode: {' '.join(cmd)}")
            
            # Get video duration for progress calculation
            duration = self.get_duration(input_path)
            
            # Start encode process
            process = subprocess.Popen(
                cmd,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                text=True,
                bufsize=1,
                universal_newlines=True
            )
            
            self.active_encodes[task_id] = process
            
            # Monitor progress
            last_progress = 0
            for line in process.stderr:
                line = line.strip()
                if "time=" in line and duration > 0:
                    progress = self._parse_progress(line, duration)
                    if progress and progress_callback and abs(progress - last_progress) >= 5:
                        progress_callback(progress, f"Encoding... {progress}%")
                        db.update_encode_status(task_id, "encoding", progress)
                        last_progress = progress
            
            process.wait()
            
            if process.returncode == 0:
                db.update_encode_status(task_id, "completed", 100)
                
                if progress_callback:
                    progress_callback(100, "Encoding completed!")
                
                logger.info(f"Encoding completed: {output_path}")
                return output_path
            else:
                stderr = process.stderr.read() if process.stderr else "Unknown error"
                error_msg = f"Encoding failed: {stderr}"
                db.update_encode_status(task_id, "failed", error=error_msg)
                logger.error(error_msg)
                return None
                
        except Exception as e:
            error_msg = f"Encoding error: {e}"
            db.update_encode_status(task_id, "failed", error=error_msg)
            logger.error(error_msg)
            return None
        finally:
            if task_id in self.active_encodes:
                del self.active_encodes[task_id]
    
    def _build_ffmpeg_command(self, input_path: Path, output_path: Path, settings: Dict) -> list:
        """Build FFmpeg command based on settings."""
        cmd = [
            self.ffmpeg_path,
            "-i", str(input_path),
            "-y",  # Overwrite output
        ]
        
        # Video codec settings
        codec = settings.get("codec", Config.DEFAULT_CODEC)
        crf = settings.get("crf", Config.DEFAULT_CRF)
        preset = settings.get("preset", Config.DEFAULT_PRESET)
        resolution = settings.get("resolution", "original")
        
        # Video filter
        vf_parts = []
        if resolution != "original":
            height = resolution.replace("p", "")
            vf_parts.append(f"scale=-2:{height}")
        
        # Apply video filter if any
        if vf_parts:
            cmd.extend(["-vf", ",".join(vf_parts)])
        
        # Video codec configuration
        cmd.extend([
            "-c:v", codec,
            "-preset", preset,
            "-crf", str(crf),
            "-pix_fmt", "yuv420p",
        ])
        
        # 10-bit support for HEVC/H265
        if "265" in codec or "hevc" in codec.lower():
            cmd.extend(["-pix_fmt", "yuv420p10le"])
        
        # Audio codec settings
        audio_codec = settings.get("audio_codec", Config.DEFAULT_AUDIO_CODEC)
        audio_bitrate = settings.get("audio_bitrate", Config.DEFAULT_AUDIO_BITRATE)
        
        cmd.extend([
            "-c:a", audio_codec,
            "-b:a", audio_bitrate,
        ])
        
        # Audio channels
        if "channels" in settings:
            cmd.extend(["-ac", str(settings["channels"])])
        
        # Hardsub subtitles
        if settings.get("hardsub", False):
            cmd.extend([
                "-vf", "subtitles='" + str(input_path) + "'",
            ])
        
        # Copy subtitle streams if not hardsubbing
        if not settings.get("hardsub", False):
            cmd.extend(["-c:s", "copy"])
        
        # Faststart for web playback
        cmd.extend(["-movflags", "+faststart"])
        
        # Output file
        cmd.append(str(output_path))
        
        return cmd
    
    def _parse_progress(self, line: str, duration: float) -> Optional[int]:
        """Parse encoding progress from FFmpeg output."""
        match = re.search(r'time=(\d+):(\d+):(\d+\.?\d*)', line)
        if match and duration > 0:
            hours, minutes, seconds = match.groups()
            current_time = float(hours) * 3600 + float(minutes) * 60 + float(seconds)
            progress = int((current_time / duration) * 100)
            return min(progress, 100)
        return None
    
    def cancel_encode(self, task_id: str) -> bool:
        """Cancel an active encoding."""
        if task_id in self.active_encodes:
            process = self.active_encodes[task_id]
            process.terminate()
            try:
                process.wait(timeout=5)
            except subprocess.TimeoutExpired:
                process.kill()
            
            db.update_encode_status(task_id, "cancelled")
            del self.active_encodes[task_id]
            return True
        return False
    
    def reencode_audio(self, input_path: Path, output_path: Path,
                      audio_codec: str = "aac", bitrate: str = "128k",
                      channels: int = 2) -> bool:
        """Re-encode only audio stream."""
        try:
            cmd = [
                self.ffmpeg_path,
                "-i", str(input_path),
                "-c:v", "copy",
                "-c:a", audio_codec,
                "-b:a", bitrate,
                "-ac", str(channels),
                "-y",
                str(output_path)
            ]
            
            result = subprocess.run(cmd, capture_output=True)
            return result.returncode == 0
        except Exception as e:
            logger.error(f"Audio re-encode error: {e}")
            return False
    
    def extract_audio(self, input_path: Path, output_path: Path,
                     audio_codec: str = "mp3") -> bool:
        """Extract audio from video."""
        try:
            cmd = [
                self.ffmpeg_path,
                "-i", str(input_path),
                "-vn",  # No video
                "-c:a", audio_codec,
                "-y",
                str(output_path)
            ]
            
            result = subprocess.run(cmd, capture_output=True)
            return result.returncode == 0
        except Exception as e:
            logger.error(f"Audio extract error: {e}")
            return False

# Global encoder instance
encoder = VideoEncoder()