The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
refactor(ffmpeg): 合并流程收进 FFmpegStep._runMerge
XiaoYouChRda6ce8b23ecc
diff --git a/features/bili_pack/task.py b/features/bili_pack/task.pyindex 0eb27433..7d5c4821 100644--- a/features/bili_pack/task.py+++ b/features/bili_pack/task.py@@ -1,8 +1,6 @@from __future__ import annotations-import asyncioimport shutil-from contextlib import suppressfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -616,79 +614,18 @@ class BilibiliMergeStep(FFmpegStep):shutil.copyfileobj(seg, f)tmp.replace(path)- hasVideo = self._videoPath.exists()- hasAudio = self._audioPath.exists()-- if hasVideo and hasAudio:- if self._timeRange:- await self._runWithTrim()- else:- await super().run(reportSpeed, waitForSpeedLimit)- return-- singleInput = self._videoPath if hasVideo else self._audioPath if hasAudio else None- if not singleInput:+ sources = [p for p in (self._videoPath, self._audioPath) if p.exists()]+ if not sources:deletePlaceholder(Path(self.outputPath))returnif self._timeRange:- await self._runWithTrim()+ preArgs, postArgs = self._buildTrimArgs()+ await self._runMerge(sources, sourceArgs=preArgs, outputArgs=[*postArgs, "-f", "mp4"])+ elif len(sources) == 2:+ await self._runMerge(sources)else:- singleInput.replace(self.outputPath)-- async def _runWithTrim(self) -> None:- from ffmpeg_pack.config import ffmpegRuntime- from app.platform.filesystem import deletePath-- ffmpegPath = ffmpegRuntime.path()- ffprobePath = ffmpegRuntime.ffprobePath()- if not ffmpegPath or not ffprobePath:- raise TaskError("{name} 未安装,请在设置中安装", name="FFmpeg")-- probeInput = self._videoPath if self._videoPath.exists() else self._audioPath- totalDuration = await self._probeDuration(ffprobePath, probeInput)-- preArgs, postArgs = self._buildTrimArgs()- args = [ffmpegPath, "-y", "-v", "error", "-nostats", "-progress", "pipe:1"]- for path in (self._videoPath, self._audioPath):- if path.exists():- args.extend([*preArgs, "-i", str(path)])- args.extend([*postArgs, "-c", "copy", "-f", "mp4", self.outputPath])-- process = await asyncio.create_subprocess_exec(- *args,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- progressTask = asyncio.create_task(self._readProgress(process.stdout, totalDuration))-- try:- await process.wait()- await progressTask-- if process.returncode != 0:- stderr = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()- raise TaskError(- "FFmpeg 合并失败({code}):{detail}",- code=process.returncode,- detail=stderr or "unknown error",- )-- if self.shouldDeleteSource:- for path in (self._videoPath, self._audioPath):- if path.exists():- deletePath(path)- except asyncio.CancelledError:- self.setStatus(TaskStatus.PAUSED)- if process.returncode is None:- process.kill()- await process.wait()- if not progressTask.done():- progressTask.cancel()- with suppress(asyncio.CancelledError):- await progressTask- raise+ sources[0].replace(self.outputPath)@dataclass(kw_only=True)diff --git a/features/ffmpeg_pack/manifest.toml b/features/ffmpeg_pack/manifest.tomlindex 279d2a21..8e130fe6 100644--- a/features/ffmpeg_pack/manifest.toml+++ b/features/ffmpeg_pack/manifest.toml@@ -2,5 +2,5 @@entry = "pack.py"class = "FFmpegPack"dependencies = ["http_pack"]-version = "1.1.1"+version = "1.1.2"gdMinVersion = "4.4.5"diff --git a/features/ffmpeg_pack/task.py b/features/ffmpeg_pack/task.pyindex 33bb9d37..3e9fc1d3 100644--- a/features/ffmpeg_pack/task.py+++ b/features/ffmpeg_pack/task.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+from collections.abc import Sequencefrom contextlib import suppressfrom dataclasses import dataclassfrom pathlib import Path@@ -51,21 +52,30 @@ class FFmpegStep(TaskStep):return toResourcePath(self.task, "audio", self.audioExtension)async def run(self, reportSpeed, waitForSpeedLimit) -> None:-+ await self._runMerge([self._videoPath, self._audioPath])++ async def _runMerge(+ self,+ sources: list[Path],+ *,+ sourceArgs: Sequence[str] = (),+ extraInputArgs: Sequence[str] = (),+ outputArgs: Sequence[str] = (),+ ) -> None:ffmpegPath = ffmpegRuntime.path()ffprobePath = ffmpegRuntime.ffprobePath()if not ffmpegPath or not ffprobePath:raise TaskError("{name} 未安装,请在设置中安装", name="FFmpeg")- totalDuration = await self._probeDuration(ffprobePath, self._videoPath)+ totalDuration = await self._probeDuration(ffprobePath, sources[0])++ args = [ffmpegPath, "-y", "-v", "error", "-nostats", "-progress", "pipe:1"]+ for source in sources:+ args.extend([*sourceArgs, "-i", str(source)])+ args.extend([*extraInputArgs, "-c", "copy", *outputArgs, self.outputPath])process = await asyncio.create_subprocess_exec(- ffmpegPath,- "-y", "-v", "error", "-nostats", "-progress", "pipe:1",- "-i", str(self._videoPath),- "-i", str(self._audioPath),- "-c", "copy",- self.outputPath,+ *args,stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.PIPE,@@ -78,14 +88,14 @@ class FFmpegStep(TaskStep):if process.returncode != 0:stderr = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()- for inputPath in (self._videoPath, self._audioPath):- if inputPath.exists():- with open(inputPath, "rb") as f:+ for source in sources:+ if source.exists():+ with open(source, "rb") as f:boxType = f.read(8)[4:8]if boxType not in ISOBMFF_BOX_TYPES:raise TaskError("文件不是有效的媒体格式,可能受 DRM 保护或下载不完整:{name}",- name=inputPath.name,+ name=source.name,)raise TaskError("FFmpeg 合并失败({code}):{detail}",@@ -94,8 +104,8 @@ class FFmpegStep(TaskStep):)if self.shouldDeleteSource:- for path in (self._videoPath, self._audioPath):- deletePath(path)+ for source in sources:+ deletePath(source)except asyncio.CancelledError:self.setStatus(TaskStatus.PAUSED)if process.returncode is None:diff --git a/features/yt_dlp_pack/manifest.toml b/features/yt_dlp_pack/manifest.tomlindex d75f829f..805858d2 100644--- a/features/yt_dlp_pack/manifest.toml+++ b/features/yt_dlp_pack/manifest.toml@@ -2,5 +2,5 @@entry = "pack.py"class = "YouTubePack"dependencies = ["http_pack", "ffmpeg_pack"]-version = "1.3.4"+version = "1.3.5"gdMinVersion = "4.4.5"diff --git a/features/yt_dlp_pack/task.py b/features/yt_dlp_pack/task.pyindex c45eda37..67422875 100644--- a/features/yt_dlp_pack/task.py+++ b/features/yt_dlp_pack/task.py@@ -7,7 +7,6 @@ import shutilimport tempfileimport threadingfrom collections.abc import Iterable, Iterator-from contextlib import suppressfrom dataclasses import dataclass, fieldfrom itertools import countfrom pathlib import Path@@ -626,7 +625,7 @@ class YouTubeMergeStep(FFmpegStep):if hasVideo and hasAudio:if self.metadataTitle or self.chapters or self._timeRange:- await self._runWithMetadata()+ await self._runWithMetadata([self._videoPath, self._audioPath])else:await super().run(reportSpeed, waitForSpeedLimit)return@@ -640,155 +639,28 @@ class YouTubeMergeStep(FFmpegStep):if isSameContainer and not (self.metadataTitle or self.chapters or self._timeRange):singleInput.replace(self.outputPath)else:- await self._runSingleWithMetadata(singleInput)-- async def _runSingleWithMetadata(self, inputPath: Path) -> None:- from ffmpeg_pack.config import ffmpegRuntime- from app.platform.filesystem import deletePath-- ffmpegPath = ffmpegRuntime.path()- ffprobePath = ffmpegRuntime.ffprobePath()- if not ffmpegPath or not ffprobePath:- raise TaskError("{name} 未安装,请在设置中安装", name="FFmpeg")-- totalDuration = await self._probeDuration(ffprobePath, inputPath)+ await self._runWithMetadata([singleInput])+ async def _runWithMetadata(self, sources: list[Path]) -> None:preArgs, postArgs = self._buildTrimArgs()- args = [- ffmpegPath,- "-y", "-v", "error", "-nostats", "-progress", "pipe:1",- *preArgs,- "-i", str(inputPath),- ]-- chaptersFile = None- if self.chapters:- chaptersFile = self._createChaptersFile()- args.extend(["-f", "ffmetadata", "-i", chaptersFile])-- args.extend(postArgs)-- args.extend(["-c", "copy"])-- if self.chapters and chaptersFile:- args.extend(["-map", "0", "-map_metadata", "1"])-+ chaptersFile = self._createChaptersFile() if self.chapters else None+ outputArgs = list(postArgs)+ if chaptersFile:+ for index in range(len(sources)):+ outputArgs.extend(["-map", str(index)])+ outputArgs.extend(["-map_metadata", str(len(sources))])if self.metadataTitle:- args.extend(["-metadata", f"title={self.metadataTitle}"])+ outputArgs.extend(["-metadata", f"title={self.metadataTitle}"])if self.metadataArtist:- args.extend(["-metadata", f"artist={self.metadataArtist}"])-- args.extend(["-f", "mp4", self.outputPath])-- process = await asyncio.create_subprocess_exec(- *args,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- progressTask = asyncio.create_task(self._readProgress(process.stdout, totalDuration))-+ outputArgs.extend(["-metadata", f"artist={self.metadataArtist}"])+ outputArgs.extend(["-f", "mp4"])try:- await process.wait()- await progressTask-- if process.returncode != 0:- stderr = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()- raise TaskError(- "FFmpeg 写入元数据失败({code}):{detail}",- code=process.returncode,- detail=stderr or "unknown error",- )-- if self.shouldDeleteSource:- deletePath(inputPath)- except asyncio.CancelledError:- self.setStatus(TaskStatus.PAUSED)- if process.returncode is None:- process.kill()- await process.wait()- if not progressTask.done():- progressTask.cancel()- with suppress(asyncio.CancelledError):- await progressTask- raise- finally:- if chaptersFile:- Path(chaptersFile).unlink(missing_ok=True)-- async def _runWithMetadata(self) -> None:- from ffmpeg_pack.config import ffmpegRuntime- from app.platform.filesystem import deletePath-- ffmpegPath = ffmpegRuntime.path()- ffprobePath = ffmpegRuntime.ffprobePath()- if not ffmpegPath or not ffprobePath:- raise TaskError("{name} 未安装,请在设置中安装", name="FFmpeg")-- totalDuration = await self._probeDuration(ffprobePath, self._videoPath)-- preArgs, postArgs = self._buildTrimArgs()- args = [- ffmpegPath,- "-y", "-v", "error", "-nostats", "-progress", "pipe:1",- *preArgs,- "-i", str(self._videoPath),- *preArgs,- "-i", str(self._audioPath),- ]-- chaptersFile = None- if self.chapters:- chaptersFile = self._createChaptersFile()- args.extend(["-f", "ffmetadata", "-i", chaptersFile])-- args.extend(postArgs)-- args.extend(["-c", "copy"])-- if self.chapters and chaptersFile:- args.extend(["-map", "0", "-map", "1", "-map_metadata", "2"])-- if self.metadataTitle:- args.extend(["-metadata", f"title={self.metadataTitle}"])- if self.metadataArtist:- args.extend(["-metadata", f"artist={self.metadataArtist}"])-- args.extend(["-f", "mp4", self.outputPath])-- process = await asyncio.create_subprocess_exec(- *args,- stdin=asyncio.subprocess.DEVNULL,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- )- progressTask = asyncio.create_task(self._readProgress(process.stdout, totalDuration))-- try:- await process.wait()- await progressTask-- if process.returncode != 0:- stderr = (await process.stderr.read()).decode("utf-8", errors="ignore").strip()- raise TaskError(- "FFmpeg 合并失败({code}):{detail}",- code=process.returncode,- detail=stderr or "unknown error",- )-- if self.shouldDeleteSource:- for path in (self._videoPath, self._audioPath):- deletePath(path)- except asyncio.CancelledError:- self.setStatus(TaskStatus.PAUSED)- if process.returncode is None:- process.kill()- await process.wait()- if not progressTask.done():- progressTask.cancel()- with suppress(asyncio.CancelledError):- await progressTask- raise+ await self._runMerge(+ sources,+ sourceArgs=preArgs,+ extraInputArgs=["-f", "ffmetadata", "-i", chaptersFile] if chaptersFile else [],+ outputArgs=outputArgs,+ )finally:if chaptersFile:Path(chaptersFile).unlink(missing_ok=True)