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 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339
|
HW_ACCEL_SUPPORTED = hasattr(av, 'hwdevice')
if HW_ACCEL_SUPPORTED: if platform.system() == 'Darwin': logger.info("硬件加速 (VideoToolbox) 可用。将优先使用 Metal 路径。") else: HW_ACCEL_SUPPORTED = False logger.warning("PyAV 支持硬件加速,但当前系统不是 macOS。VideoToolbox 不可用。") logger.warning("所有视频处理将回退到纯软件模式。") else: logger.warning("当前 PyAV 环境中未找到硬件加速模块 ('av.hwdevice')。") logger.warning("所有视频处理将回退到纯软件模式,速度会较慢。") logger.warning("要解决此问题,请确保您的项目解释器配置正确,并使用了完整编译的 PyAV 库。")
@logger.catch def crop_video_pyav( input_video_path: str, output_video_path: str, crop_x: float, crop_y: float, crop_w: float, crop_h: float, log_queue=None, min_short_side_output_px: Optional[int] = None, assigned_gpu_id: Optional[int] = None, **kwargs ) -> bool: """ 根据环境自动选择最佳方式裁剪视频。
如果支持硬件加速,则尝试使用Metal路径;否则,或Metal路径失败时, 自动回退到纯软件路径。 """ crop_params = { 'x': crop_x, 'y': crop_y, 'w': crop_w, 'h': crop_h }
if HW_ACCEL_SUPPORTED: try: logger.info(f"检测到硬件加速支持,尝试 Metal 路径...") success = _crop_video_pyav_metal( input_video_path, output_video_path, crop_params, min_short_side_output_px ) if not success: logger.warning("硬件加速路径执行失败,自动降级到纯软件模式。") success = _crop_video_software( input_video_path, output_video_path, crop_params, min_short_side_output_px ) return success except Exception as e: logger.opt(exception=True).error(f"硬件加速路径执行时发生意外异常: {e}") logger.warning("自动降级到纯软件模式。") return _crop_video_software( input_video_path, output_video_path, crop_params, min_short_side_output_px ) else: logger.info(f"未检测到硬件加速支持,使用纯软件路径。") return _crop_video_software( input_video_path, output_video_path, crop_params, min_short_side_output_px )
@logger.catch def _crop_video_pyav_metal( input_video_path: str, output_video_path: str, crop_rect: Dict, min_short_side_output_px: Optional[int] = None, ) -> bool: """ 使用 PyAV 和 VideoToolbox (Metal) 进行硬件加速的视频裁剪。 这是一个内部函数,假设硬件支持已确认。 """ logger.info(f"Metal路径: 开始处理 {os.path.basename(input_video_path)}")
crop_w_f = int(crop_rect['w']) - (int(crop_rect['w']) % 2) crop_h_f = int(crop_rect['h']) - (int(crop_rect['h']) % 2) crop_x_f = int(crop_rect['x']) - (int(crop_rect['x']) % 2) crop_y_f = int(crop_rect['y']) - (int(crop_rect['y']) % 2) if crop_w_f <= 0 or crop_h_f <= 0: return False
final_w, final_h = crop_w_f, crop_h_f needs_scaling = False if min_short_side_output_px and min(crop_w_f, crop_h_f) < min_short_side_output_px: needs_scaling = True scale_factor = min_short_side_output_px / min(crop_w_f, crop_h_f) final_w = math.ceil((crop_w_f * scale_factor) / 2) * 2 final_h = math.ceil((crop_h_f * scale_factor) / 2) * 2
input_container = None output_container = None
try: logger.debug("Metal路径: 创建 VideoToolbox 上下文。") hw_device = av.hwdevice.Device("videotoolbox")
input_container = av.open(input_video_path, mode='r') output_container = av.open(output_video_path, mode='w') in_stream = input_container.streams.video[0] in_stream.thread_type = "AUTO"
logger.debug("Metal路径: 配置硬件解码。") hw_pix_fmt = 'videotoolbox'
def get_hw_format(formats): for fmt in formats: if fmt.name == hw_pix_fmt: return fmt raise av.EncoderNotFoundError(f"未找到 '{hw_pix_fmt}' 硬件格式。")
in_stream.codec_context.get_format = get_hw_format
logger.debug("Metal路径: 配置滤镜图。") graph = av.filter.Graph() buffer_src = graph.add_buffer(template=in_stream)
filter_chain = f"crop={crop_w_f}:{crop_h_f}:{crop_x_f}:{crop_y_f}" if needs_scaling: filter_chain += f",scale={final_w}:{final_h}"
buffer_sink = graph.add("buffersink")
buffer_src.link_to(graph.add_filter(filter_chain, "filters")) graph.get_filter("filters").link_to(buffer_sink)
graph.configure() logger.info(f"Metal路径: 滤镜图配置成功: '{filter_chain}'")
logger.debug("Metal路径: 配置硬件编码。") rate = in_stream.base_rate or in_stream.guessed_rate or in_stream.average_rate out_stream = output_container.add_stream("h264_videotoolbox", rate=rate) out_stream.width = final_w out_stream.height = final_h out_stream.pix_fmt = "nv12" out_stream.time_base = in_stream.time_base
in_audio_stream = next((s for s in input_container.streams if s.type == 'audio'), None) if in_audio_stream: out_audio_stream = output_container.add_stream('aac', template=in_audio_stream) streams_to_demux = (in_stream, in_audio_stream) else: out_audio_stream = None streams_to_demux = in_stream
for packet in input_container.demux(streams_to_demux): if packet.dts is None: continue
if packet.stream.type == 'video': for frame in packet.decode(): graph.push(frame) while True: try: filtered_frame = buffer_sink.pull() for out_packet in out_stream.encode(filtered_frame): output_container.mux(out_packet) except (av.error.EOFError, av.error.BlockingIOError): break elif out_audio_stream and packet.stream.type == 'audio': packet.stream = out_audio_stream output_container.mux(packet)
logger.debug("Metal路径: 冲洗滤镜和编码器。") graph.push(None) while True: try: filtered_frame = buffer_sink.pull() for out_packet in out_stream.encode(filtered_frame): output_container.mux(out_packet) except (av.error.EOFError, av.error.BlockingIOError): break
for out_packet in out_stream.encode(None): output_container.mux(out_packet)
output_container.close() input_container.close()
logger.info(f"Metal路径: 视频处理成功 -> {os.path.basename(output_video_path)}") return True
except Exception as e: logger.opt(exception=True).error(f"Metal路径处理时发生致命错误: {e}") if output_container: output_container.close() if input_container: input_container.close() if os.path.exists(output_video_path): try: os.remove(output_video_path) except OSError: pass return False
@logger.catch def _crop_video_software( input_video_path: str, output_video_path: str, crop_rect: Dict, min_short_side_output_px: Optional[int] = None, ) -> bool: """ 使用纯软件 (CPU) 进行视频裁剪的备用方法。 这个方法总是可用的,但速度比硬件加速慢。 它确保输出尺寸为偶数,以兼容H.264等编码器。 """ logger.info(f"软件路径: 开始处理 {os.path.basename(input_video_path)}")
input_container = None output_container = None success = False
try: x, y, w, h = int(crop_rect['x']), int(crop_rect['y']), int(crop_rect['w']), int(crop_rect['h']) if w <= 0 or h <= 0: logger.error(f"裁剪尺寸无效 (w={w}, h={h})。") return False
final_w, final_h = w, h needs_scaling = False
if min_short_side_output_px and min(w, h) < min_short_side_output_px: needs_scaling = True scale_factor = min_short_side_output_px / min(w, h) final_w = int(w * scale_factor) final_h = int(h * scale_factor)
final_w = final_w - (final_w % 2) final_h = final_h - (final_h % 2)
if final_w <= 0 or final_h <= 0: logger.error(f"计算后的输出尺寸无效 ({final_w}x{final_h})。") return False
with av.open(input_video_path, mode='r') as in_container: with av.open(output_video_path, mode='w') as out_container:
in_video_stream = next((s for s in in_container.streams if s.type == 'video'), None) if not in_video_stream: logger.error("输入文件中未找到视频流。") return False in_video_stream.thread_type = "AUTO"
in_audio_stream = next((s for s in in_container.streams if s.type == 'audio'), None) in_subtitle_stream = next((s for s in in_container.streams if s.type == 'subtitle'), None)
out_video_stream = out_container.add_stream_from_template(in_video_stream) out_video_stream.width = final_w out_video_stream.height = final_h
out_audio_stream = out_container.add_stream_from_template(in_audio_stream) if in_audio_stream else None out_subtitle_stream = out_container.add_stream_from_template( in_subtitle_stream) if in_subtitle_stream else None
streams_to_demux = [s for s in [in_video_stream, in_audio_stream, in_subtitle_stream] if s]
for packet in in_container.demux(streams_to_demux): if packet.dts is None: continue
if packet.stream.type == 'video': for frame in packet.decode(): img = frame.to_image()
cropped_img = img.crop((x, y, x + w, y + h))
if needs_scaling: cropped_img = cropped_img.resize((final_w, final_h))
new_frame = av.VideoFrame.from_image(cropped_img) new_frame.pts = frame.pts
for out_packet in out_video_stream.encode(new_frame): out_container.mux(out_packet)
elif packet.stream.type == 'audio' and out_audio_stream: packet.stream = out_audio_stream out_container.mux(packet)
elif packet.stream.type == 'subtitle' and out_subtitle_stream: packet.stream = out_subtitle_stream out_container.mux(packet)
logger.debug("软件路径: 冲洗视频编码器。") for out_packet in out_video_stream.encode(None): out_container.mux(out_packet)
success = True logger.info(f"软件路径: 视频处理成功 -> {os.path.basename(output_video_path)}") return True
except Exception as e: logger.opt(exception=True).error(f"软件路径处理时发生错误: {e}") return False finally: if output_container and not output_container.closed: output_container.close() if input_container and not input_container.closed: input_container.close() if not success and os.path.exists(output_video_path): try: os.remove(output_video_path) logger.info(f"已清理失败的输出文件: {output_video_path}") except OSError as err: logger.warning(f"清理失败的输出文件时出错: {err}")
|