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
| import subprocess import json import os from typing import List, Dict, Optional from dataclasses import dataclass from concurrent.futures import ThreadPoolExecutor, Future import tempfile
@dataclass class TranscodeProfile: """转码配置文件""" name: str width: int height: int video_bitrate: int audio_bitrate: int framerate: int = 30 keyframe_interval: int = 2 video_codec: str = "libx264" audio_codec: str = "aac" preset: str = "veryfast" profile: str = "baseline" level: str = "3.1"
class LiveTranscoder: """直播转码器""" def __init__(self, max_workers: int = 4): self.max_workers = max_workers self.executor = ThreadPoolExecutor(max_workers=max_workers) self.active_jobs: Dict[str, Future] = {} self.profiles = self._create_default_profiles() def _create_default_profiles(self) -> List[TranscodeProfile]: """创建默认转码配置""" return [ TranscodeProfile( name="1080p", width=1920, height=1080, video_bitrate=4000, audio_bitrate=128, preset="fast", profile="high", level="4.0" ), TranscodeProfile( name="720p", width=1280, height=720, video_bitrate=2500, audio_bitrate=128, preset="fast", profile="main", level="3.1" ), TranscodeProfile( name="480p", width=854, height=480, video_bitrate=1200, audio_bitrate=96, preset="veryfast", profile="baseline", level="3.0" ), TranscodeProfile( name="360p", width=640, height=360, video_bitrate=800, audio_bitrate=64, preset="veryfast", profile="baseline", level="3.0" ) ] def start_transcoding(self, input_url: str, stream_id: str, output_profiles: Optional[List[str]] = None) -> bool: """开始转码""" if stream_id in self.active_jobs: print(f"Transcoding already active for stream {stream_id}") return False if output_profiles is None: output_profiles = ["1080p", "720p", "480p", "360p"] selected_profiles = [p for p in self.profiles if p.name in output_profiles] if not selected_profiles: print(f"No valid profiles found for {output_profiles}") return False print(f"Starting transcoding for stream {stream_id}") print(f"Input: {input_url}") print(f"Profiles: {[p.name for p in selected_profiles]}") future = self.executor.submit( self._transcode_stream, input_url, stream_id, selected_profiles ) self.active_jobs[stream_id] = future return True def stop_transcoding(self, stream_id: str) -> bool: """停止转码""" if stream_id not in self.active_jobs: print(f"No active transcoding for stream {stream_id}") return False future = self.active_jobs[stream_id] future.cancel() del self.active_jobs[stream_id] print(f"Transcoding stopped for stream {stream_id}") return True def _transcode_stream(self, input_url: str, stream_id: str, profiles: List[TranscodeProfile]): """执行转码""" try: output_dir = f"/tmp/live_output/{stream_id}" os.makedirs(output_dir, exist_ok=True) processes = [] for profile in profiles: output_path = f"{output_dir}/{profile.name}" os.makedirs(output_path, exist_ok=True) cmd = self._build_ffmpeg_command(input_url, profile, output_path) print(f"Starting transcoding for {profile.name}") print(f"Command: {' '.join(cmd)}") process = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True ) processes.append((profile.name, process)) self._monitor_transcoding_processes(processes, stream_id) except Exception as e: print(f"Transcoding error for stream {stream_id}: {e}") def _build_ffmpeg_command(self, input_url: str, profile: TranscodeProfile, output_path: str) -> List[str]: """构建FFmpeg命令""" cmd = [ "ffmpeg", "-i", input_url, "-c:v", profile.video_codec, "-preset", profile.preset, "-profile:v", profile.profile, "-level", profile.level, "-b:v", f"{profile.video_bitrate}k", "-maxrate", f"{int(profile.video_bitrate * 1.2)}k", "-bufsize", f"{profile.video_bitrate * 2}k", "-vf", f"scale={profile.width}:{profile.height}", "-r", str(profile.framerate), "-g", str(profile.framerate * profile.keyframe_interval), "-c:a", profile.audio_codec, "-b:a", f"{profile.audio_bitrate}k", "-ar", "44100", "-ac", "2", "-f", "hls", "-hls_time", "4", "-hls_list_size", "10", "-hls_flags", "delete_segments", "-hls_segment_filename", f"{output_path}/segment_%03d.ts", f"{output_path}/playlist.m3u8" ] return cmd def _monitor_transcoding_processes(self, processes: List[tuple], stream_id: str): """监控转码进程""" try: while True: active_processes = [] for profile_name, process in processes: if process.poll() is None: active_processes.append((profile_name, process)) else: return_code = process.returncode if return_code == 0: print(f"Transcoding completed for {profile_name}") else: stderr = process.stderr.read() print(f"Transcoding failed for {profile_name}: {stderr}") if not active_processes: break processes = active_processes time.sleep(5) except Exception as e: print(f"Error monitoring transcoding processes: {e}") for _, process in processes: if process.poll() is None: process.terminate() def get_transcoding_status(self, stream_id: str) -> Optional[Dict]: """获取转码状态""" if stream_id not in self.active_jobs: return None future = self.active_jobs[stream_id] status = { 'stream_id': stream_id, 'running': not future.done(), 'profiles': [p.name for p in self.profiles] } if future.done(): try: future.result() status['status'] = 'completed' except Exception as e: status['status'] = 'failed' status['error'] = str(e) else: status['status'] = 'running' return status def add_custom_profile(self, profile: TranscodeProfile): """添加自定义转码配置""" self.profiles.append(profile) print(f"Added custom profile: {profile.name}") def shutdown(self): """关闭转码器""" print("Shutting down transcoder...") for stream_id, future in self.active_jobs.items(): future.cancel() print(f"Cancelled transcoding for {stream_id}") self.active_jobs.clear() self.executor.shutdown(wait=True) print("Transcoder shutdown completed")
def demo_live_transcoder(): print("Live Transcoder Demo") print("===================") transcoder = LiveTranscoder(max_workers=2) custom_profile = TranscodeProfile( name="240p", width=426, height=240, video_bitrate=400, audio_bitrate=64, preset="ultrafast", profile="baseline" ) transcoder.add_custom_profile(custom_profile) input_streams = [ "rtmp://input.example.com/live/stream1", "rtmp://input.example.com/live/stream2" ] print("\nStarting transcoding jobs...") for i, input_url in enumerate(input_streams): stream_id = f"stream_{i+1}" profiles = ["720p", "480p", "360p"] if i == 0 else ["1080p", "720p", "240p"] success = transcoder.start_transcoding(input_url, stream_id, profiles) print(f"Stream {stream_id}: {'✓' if success else '✗'}") print("\nMonitoring transcoding status...") for _ in range(6): time.sleep(5) print(f"\n--- Status Update ---") for i in range(len(input_streams)): stream_id = f"stream_{i+1}" status = transcoder.get_transcoding_status(stream_id) if status: print(f"Stream {stream_id}: {status['status']}") if status['running']: print(f" Profiles: {', '.join(status['profiles'])}") else: print(f"Stream {stream_id}: Not found") print("\nStopping transcoding...") for i in range(len(input_streams)): stream_id = f"stream_{i+1}" transcoder.stop_transcoding(stream_id) transcoder.shutdown() print("\nLive transcoder demo completed")
if __name__ == "__main__": demo_live_transcoder()
|