Skip to content

The only downloader you need. 下载器的集大成者。

feat(ffmpeg): 添加 FFmpeg 一键安装功能

XiaoYouChR69eef722a971
diff --git a/app/bases/models.py b/app/bases/models.py
index cdf7b035..9efd253a 100644
--- a/app/bases/models.py
+++ b/app/bases/models.py
@@ -233,7 +233,7 @@ class PackConfig:
def getDialogCards(self, parent: "QWidget") -> Iterable["SettingCard"]:
"""在解析时往解析窗口加入设置卡片"""
- raise NotImplementedError
+ return []
def tr(self, text: str) -> str:
return QCoreApplication.translate(self.__class__.__name__, text)
diff --git a/features/ffmpeg_pack/config.py b/features/ffmpeg_pack/config.py
new file mode 100644
index 00000000..16c970f5
--- /dev/null
+++ b/features/ffmpeg_pack/config.py
@@ -0,0 +1,229 @@
+import asyncio
+import shutil
+import sys
+from pathlib import Path
+from typing import TYPE_CHECKING, Iterable
+
+from PySide6.QtCore import QStandardPaths, Qt, Signal
+from PySide6.QtWidgets import QFileDialog
+from qfluentwidgets import (
+ ConfigItem,
+ ConfigValidator,
+ FluentIcon,
+ FolderValidator,
+ SettingCard,
+ SettingCardGroup,
+ ToolButton, PrimaryPushButton,
+)
+
+from app.bases.models import PackConfig
+from app.services.core_service import coreService
+from app.services.feature_service import featureService
+from app.supports.config import cfg
+from app.supports.recorder import taskRecorder
+from app.supports.utils import showMessageBox
+
+if TYPE_CHECKING:
+ from app.view.pages.setting_page import SettingPage
+
+
+class ExecutablePathValidator(ConfigValidator):
+ def validate(self, value) -> bool:
+ return isinstance(value, str)
+
+ def correct(self, value) -> str:
+ if not isinstance(value, str):
+ return ""
+ return str(Path(value)).replace("\\", "/") if value else ""
+
+
+def _executableName(name: str) -> str:
+ return f"{name}.exe" if sys.platform == "win32" else name
+
+
+def _guessInstallRoot(ffmpegPath: str) -> str:
+ path = Path(ffmpegPath)
+ if path.parent.name.lower() == "bin":
+ return str(path.parent.parent).replace("\\", "/")
+ return str(path.parent).replace("\\", "/")
+
+
+def _resolveExecutable(name: str, configuredPath: str) -> str:
+ path = Path(configuredPath)
+ if configuredPath and path.is_file():
+ return str(path).replace("\\", "/")
+
+ installFolder = Path(ffmpegConfig.installFolder.value)
+ for candidate in (installFolder / "bin" / _executableName(name), installFolder / _executableName(name)):
+ if candidate.is_file():
+ return str(candidate).replace("\\", "/")
+
+ found = shutil.which(name)
+ return str(found).replace("\\", "/") if found else ""
+
+
+def resolveFFmpegExecutables() -> tuple[str, str]:
+ ffmpegPath = _resolveExecutable("ffmpeg", ffmpegConfig.ffmpegPath.value)
+ ffprobePath = _resolveExecutable("ffprobe", ffmpegConfig.ffprobePath.value)
+ return ffmpegPath, ffprobePath
+
+
+def setPreferredFFmpegExecutables(ffmpegPath: str, ffprobePath: str):
+ cfg.set(ffmpegConfig.ffmpegPath, ffmpegPath)
+ cfg.set(ffmpegConfig.ffprobePath, ffprobePath)
+
+
+async def queryFFmpegRuntime() -> dict[str, str]:
+ ffmpegPath, ffprobePath = resolveFFmpegExecutables()
+ runtimeInfo = {
+ "ffmpegPath": ffmpegPath,
+ "ffprobePath": ffprobePath,
+ "version": "",
+ "installPath": "",
+ }
+ if not ffmpegPath or not ffprobePath:
+ return runtimeInfo
+
+ process = await asyncio.create_subprocess_exec(
+ ffmpegPath,
+ "-version",
+ stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ stdout, _ = await process.communicate()
+ if process.returncode != 0:
+ return runtimeInfo
+
+ firstLine = stdout.decode("utf-8", errors="ignore").splitlines()
+ versionLine = firstLine[0].strip() if firstLine else ""
+ version = versionLine.removeprefix("ffmpeg version ").split(" Copyright", 1)[0].strip()
+ runtimeInfo["version"] = version or versionLine
+ runtimeInfo["installPath"] = _guessInstallRoot(ffmpegPath)
+ return runtimeInfo
+
+
+class FFmpegInstallFolderCard(SettingCard):
+ pathChanged = Signal(str)
+
+ def __init__(self, parent=None):
+ super().__init__(FluentIcon.FOLDER, self.tr("FFmpeg 安装目录"), ffmpegConfig.installFolder.value, parent)
+ self.chooseFolderButton = ToolButton(FluentIcon.FOLDER, self)
+ self.restoreDefaultButton = ToolButton(FluentIcon.CANCEL, self)
+ self.hBoxLayout.addWidget(self.chooseFolderButton, 0, Qt.AlignmentFlag.AlignRight)
+ self.hBoxLayout.addSpacing(8)
+ self.hBoxLayout.addWidget(self.restoreDefaultButton, 0, Qt.AlignmentFlag.AlignRight)
+ self.hBoxLayout.addSpacing(16)
+
+ self.chooseFolderButton.clicked.connect(self._chooseFolder)
+ self.restoreDefaultButton.clicked.connect(self._restoreDefault)
+ self.chooseFolderButton.setToolTip(self.tr("浏览文件夹"))
+ self.restoreDefaultButton.setToolTip(self.tr("恢复默认路径"))
+
+ def _updatePath(self, path: str):
+ cfg.set(ffmpegConfig.installFolder, path)
+ # 修改安装目录时,清空安装器写入的首选路径,重新回到目录/PATH 探测逻辑
+ cfg.set(ffmpegConfig.ffmpegPath, "")
+ cfg.set(ffmpegConfig.ffprobePath, "")
+ self.setContent(ffmpegConfig.installFolder.value)
+ self.pathChanged.emit(ffmpegConfig.installFolder.value)
+
+ def _chooseFolder(self):
+ folder = QFileDialog.getExistingDirectory(self.window(), self.tr("选择 FFmpeg 安装目录"))
+ if folder:
+ self._updatePath(folder)
+
+ def _restoreDefault(self):
+ self._updatePath(f"{QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppLocalDataLocation)}/GhostDownloader/FFmpeg")
+
+
+class FFmpegRuntimeCard(SettingCard):
+ def __init__(self, parent=None):
+ super().__init__(FluentIcon.INFO, self.tr("当前 FFmpeg"), self.tr("正在检测 FFmpeg 运行时..."), parent)
+ self.installButton = PrimaryPushButton(self.tr("一键安装"), self)
+ self.refreshButton = ToolButton(FluentIcon.SYNC, self)
+ self.hBoxLayout.addWidget(self.installButton, 0, Qt.AlignmentFlag.AlignRight)
+ self.hBoxLayout.addSpacing(8)
+ self.hBoxLayout.addWidget(self.refreshButton, 0, Qt.AlignmentFlag.AlignRight)
+ self.hBoxLayout.addSpacing(16)
+ self.installButton.setVisible(sys.platform == "win32")
+ self.installButton.clicked.connect(self._onInstallClicked)
+ self.refreshButton.clicked.connect(self.refreshStatus)
+
+ def refreshStatus(self):
+ self.refreshButton.setEnabled(False)
+ self.setContent(self.tr("正在检测 FFmpeg 运行时..."))
+ coreService.runCoroutine(queryFFmpegRuntime(), self._onRuntimeLoaded)
+
+ def _onRuntimeLoaded(self, result, error: str | None):
+ self.refreshButton.setEnabled(True)
+ if error:
+ self.setContent(self.tr("检测 FFmpeg 运行时失败"))
+ return
+
+ runtimeInfo = result or {}
+ ffmpegPath = str(runtimeInfo.get("ffmpegPath") or "").strip()
+ ffprobePath = str(runtimeInfo.get("ffprobePath") or "").strip()
+ version = str(runtimeInfo.get("version") or "").strip()
+ installPath = str(runtimeInfo.get("installPath") or "").strip()
+
+ if ffmpegPath and ffprobePath:
+ content = self.tr("版本: {0}\n安装路径: {1}").format(version or self.tr("未知"), installPath or ffmpegPath)
+ else:
+ content = self.tr("未检测到可用的 ffmpeg 和 ffprobe")
+ self.setContent(content)
+
+ async def _createInstallTask(self):
+ from .task import createWindowsInstallTask
+
+ return await createWindowsInstallTask()
+
+ def _onInstallClicked(self):
+ if sys.platform != "win32":
+ return
+
+ self.installButton.setEnabled(False)
+ self.installButton.setText(self.tr("准备中..."))
+ coreService.runCoroutine(self._createInstallTask(), self._onInstallTaskCreated)
+
+ def _onInstallTaskCreated(self, result, error: str | None):
+ self.installButton.setEnabled(True)
+ self.installButton.setText(self.tr("一键安装"))
+
+ if error or result is None:
+ showMessageBox(self.window(), self.tr("安装 FFmpeg 失败"), error or self.tr("无法创建安装任务"))
+ return
+
+ mainWindow = self.window()
+ task = result
+ setattr(task, "_featurePackName", "ffmpeg_pack")
+
+ try:
+ card = featureService.createTaskCard(task, mainWindow)
+ taskRecorder.add(task, False)
+ mainWindow.taskPage.addCard(card)
+ card.resumeTask()
+ taskRecorder.flush()
+ except Exception as e:
+ showMessageBox(mainWindow, self.tr("安装 FFmpeg 失败"), repr(e))
+
+
+class FFmpegConfig(PackConfig):
+ installFolder = ConfigItem("FFmpeg", "InstallFolder", f"{QStandardPaths.writableLocation(QStandardPaths.StandardLocation.AppLocalDataLocation)}/GhostDownloader/FFmpeg", FolderValidator())
+ ffmpegPath = ConfigItem("FFmpeg", "PreferredFFmpegPath", "", ExecutablePathValidator())
+ ffprobePath = ConfigItem("FFmpeg", "PreferredFFprobePath", "", ExecutablePathValidator())
+
+ def loadSettingCards(self, settingPage: "SettingPage"):
+ self.ffmpegGroup = SettingCardGroup(self.tr("FFmpeg"), settingPage.container)
+ self.installFolderCard = FFmpegInstallFolderCard(self.ffmpegGroup)
+ self.runtimeCard = FFmpegRuntimeCard(self.ffmpegGroup)
+
+ self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())
+
+ self.ffmpegGroup.addSettingCard(self.installFolderCard)
+ self.ffmpegGroup.addSettingCard(self.runtimeCard)
+ settingPage.vBoxLayout.addWidget(self.ffmpegGroup)
+
+ self.runtimeCard.refreshStatus()
+
+
+ffmpegConfig = FFmpegConfig()
diff --git a/features/ffmpeg_pack/manifest.toml b/features/ffmpeg_pack/manifest.toml
index 90158411..784ec150 100644
--- a/features/ffmpeg_pack/manifest.toml
+++ b/features/ffmpeg_pack/manifest.toml
@@ -1,3 +1,3 @@
[pack]
entry = "pack.py"
-dependencies = []
+dependencies = ["http_pack"]
diff --git a/features/ffmpeg_pack/pack.py b/features/ffmpeg_pack/pack.py
index 843e266e..55c6a0f5 100644
--- a/features/ffmpeg_pack/pack.py
+++ b/features/ffmpeg_pack/pack.py
@@ -1,6 +1,16 @@
from app.bases.interfaces import FeaturePack
-from .task import FFmpegStage, FFmpegWorker
+from app.bases.models import Task
+from app.view.components.cards import UniversalTaskCard
+
+from .config import ffmpegConfig
+from .task import FFmpegInstallTask, FFmpegStage, FFmpegWorker
class FFmpegPack(FeaturePack):
- pass
+ taskType = FFmpegInstallTask
+ config = ffmpegConfig
+
+ def createTaskCard(self, task: Task, parent=None):
+ if isinstance(task, FFmpegInstallTask):
+ return UniversalTaskCard(task, parent)
+ return None
diff --git a/features/ffmpeg_pack/task.py b/features/ffmpeg_pack/task.py
index 6e59fc74..bcf8f9e1 100644
--- a/features/ffmpeg_pack/task.py
+++ b/features/ffmpeg_pack/task.py
@@ -1,14 +1,119 @@
import asyncio
+import platform
import shutil
+import sys
+import zipfile
from contextlib import suppress
from dataclasses import dataclass, field
from pathlib import Path
-from typing import Any
+from typing import Any, TYPE_CHECKING
+import niquests
from loguru import logger
from app.bases.interfaces import Worker
-from app.bases.models import TaskStage, TaskStatus
+from app.bases.models import Task, TaskStage, TaskStatus
+from app.supports.config import DEFAULT_HEADERS, cfg
+from app.supports.utils import getProxies
+from .config import (
+ ffmpegConfig,
+ resolveFFmpegExecutables,
+ setPreferredFFmpegExecutables,
+)
+
+if TYPE_CHECKING:
+ from features.http_pack.task import HttpTaskStage, HttpWorker
+else:
+ from http_pack.task import HttpTaskStage, HttpWorker
+
+
+_FFMPEG_RELEASE_API = "https://api.github.com/repos/BtbN/FFmpeg-Builds/releases/latest"
+_FFMPEG_HEADERS = {
+ "accept": "application/vnd.github+json",
+ "user-agent": DEFAULT_HEADERS["user-agent"],
+}
+
+
+def _executableName(name: str) -> str:
+ return f"{name}.exe" if sys.platform == "win32" else name
+
+
+def _normalizePath(path: Path | str) -> str:
+ return str(Path(path)).replace("\\", "/")
+
+
+def _detectWindowsTarget() -> tuple[str, str]:
+ if sys.platform != "win32":
+ raise RuntimeError("一键安装 FFmpeg 仅支持 Windows 平台")
+
+ machine = platform.machine().lower()
+ if machine in {"amd64", "x86_64"}:
+ return "win64", "x64"
+ if machine in {"arm64", "aarch64"}:
+ return "winarm64", "arm64"
+ raise RuntimeError(f"不支持的 Windows 架构: {platform.machine()}")
+
+
+def _selectReleaseAsset(assets: list[dict[str, Any]]) -> dict[str, Any]:
+ target, _ = _detectWindowsTarget()
+ candidates: list[tuple[int, dict[str, Any]]] = []
+ for asset in assets:
+ name = str(asset.get("name") or "")
+ lowerName = name.lower()
+ if target not in lowerName or not lowerName.endswith(".zip") or "shared" in lowerName:
+ continue
+
+ score = 0
+ if "master-latest" in lowerName:
+ score += 100
+ if "-gpl" in lowerName:
+ score += 10
+ if "-latest-" in lowerName:
+ score += 5
+ candidates.append((score, asset))
+
+ if not candidates:
+ raise RuntimeError(f"未找到适用于当前平台的 FFmpeg 安装包: {target}")
+
+ candidates.sort(key=lambda item: item[0], reverse=True)
+ return candidates[0][1]
+
+
+async def _requestLatestReleaseAsset() -> dict[str, Any]:
+ client = niquests.AsyncSession(headers=_FFMPEG_HEADERS.copy(), timeout=30, happy_eyeballs=True)
+ client.trust_env = False
+
+ try:
+ response = await client.get(
+ _FFMPEG_RELEASE_API,
+ proxies=getProxies(),
+ verify=cfg.SSLVerify.value,
+ allow_redirects=True,
+ )
+ try:
+ response.raise_for_status()
+ payload = response.json()
+ finally:
+ response.close()
+ finally:
+ await client.close()
+
+ assets = payload.get("assets")
+ if not isinstance(assets, list):
+ raise RuntimeError("GitHub Release 返回了无效的 assets 数据")
+
+ asset = _selectReleaseAsset(assets)
+ downloadUrl = str(asset.get("browser_download_url") or "").strip()
+ assetName = str(asset.get("name") or "").strip()
+ size = int(asset.get("size") or 0)
+ if not downloadUrl or not assetName or size <= 0:
+ raise RuntimeError("GitHub Release 返回了不完整的 FFmpeg 安装包信息")
+
+ return {
+ "name": assetName,
+ "url": downloadUrl,
+ "size": size,
+ }
@dataclass
@@ -57,11 +162,7 @@ class FFmpegWorker(Worker):
return self._parseDuration(stdout.decode("utf-8", errors="ignore").strip())
- async def _probeVideoDuration(self, ffprobe: str | None) -> float:
- if not ffprobe:
- logger.warning("未找到 ffprobe,视频合并进度将在完成时更新")
- return 0.0
-
+ async def _probeVideoDuration(self, ffprobe: str) -> float:
return await self._probeDuration(ffprobe, self.stage.videoPath)
async def _readProgress(self, stream: asyncio.StreamReader | None, totalDuration: float):
@@ -86,11 +187,10 @@ class FFmpegWorker(Worker):
self.stage.progress = 100
async def run(self):
- ffmpeg = shutil.which("ffmpeg")
- if not ffmpeg:
+ ffmpeg, ffprobe = resolveFFmpegExecutables()
+ if not ffmpeg or not ffprobe:
self.stage.setStatus(TaskStatus.FAILED)
- raise RuntimeError("未找到 ffmpeg,请先将 ffmpeg 加入 PATH")
- ffprobe = shutil.which("ffprobe")
+ raise RuntimeError("未找到可用的 ffmpeg 和 ffprobe,请先在设置中安装或配置 FFmpeg")
outputPath = Path(self.stage.resolvePath)
outputPath.parent.mkdir(parents=True, exist_ok=True)
@@ -155,3 +255,269 @@ class FFmpegWorker(Worker):
continue
except Exception as e:
logger.error(f"failed to cleanup temporary file {path}: {repr(e)}")
+
+
+@dataclass
+class FFmpegExtractStage(TaskStage):
+ archivePath: str
+ installFolder: str
+ ffmpegPath: str
+ ffprobePath: str
+ cleanupArchive: bool = field(default=True)
+
+
+class FFmpegExtractWorker(Worker):
+ chunkSize = 1048576
+
+ def __init__(self, stage: FFmpegExtractStage):
+ super().__init__(stage)
+ self.stage = stage
+
+ def _removePath(self, path: Path):
+ if path.is_dir() and not path.is_symlink():
+ shutil.rmtree(path, ignore_errors=True)
+ else:
+ with suppress(FileNotFoundError):
+ path.unlink()
+
+ def _updateTaskFileSize(self, extractedSize: int):
+ task = getattr(self.stage, "_task", None)
+ if task is None:
+ return
+
+ archiveSize = int(getattr(task, "archiveSize", 0) or 0)
+ task.fileSize = max(archiveSize + extractedSize, archiveSize)
+
+ def _resolveExtractedRoot(self, tempDir: Path) -> Path:
+ children = list(tempDir.iterdir())
+ if len(children) == 1 and children[0].is_dir():
+ return children[0]
+ return tempDir
+
+ def _findExecutable(self, root: Path, name: str) -> Path | None:
+ directPath = root / "bin" / name
+ if directPath.is_file():
+ return directPath
+
+ for candidate in root.rglob(name):
+ if candidate.is_file():
+ return candidate
+
+ return None
+
+ async def _extractArchive(self, archivePath: Path, tempDir: Path, totalSize: int):
+ extractedBytes = 0
+ speedBytes = 0
+ speedTime = asyncio.get_running_loop().time()
+
+ with zipfile.ZipFile(archivePath) as archive:
+ infos = [info for info in archive.infolist() if not info.is_dir()]
+ for info in infos:
+ targetPath = tempDir / info.filename
+ targetPath.parent.mkdir(parents=True, exist_ok=True)
+
+ with archive.open(info, "r") as source, open(targetPath, "wb") as target:
+ while True:
+ chunk = source.read(self.chunkSize)
+ if not chunk:
+ break
+
+ target.write(chunk)
+ extractedBytes += len(chunk)
+ self.stage.receivedBytes = extractedBytes
+ if totalSize > 0:
+ self.stage.progress = min(99.5, max(0.0, extractedBytes / totalSize * 100))
+
+ now = asyncio.get_running_loop().time()
+ if now - speedTime >= 0.5:
+ self.stage.speed = int((extractedBytes - speedBytes) / (now - speedTime))
+ speedBytes = extractedBytes
+ speedTime = now
+ await asyncio.sleep(0)
+
+ def _installExtractedFiles(self, extractedRoot: Path, installDir: Path, archiveName: str, tempDirName: str) -> tuple[str, str]:
+ for child in installDir.iterdir():
+ if child.name in {archiveName, tempDirName}:
+ continue
+ self._removePath(child)
+
+ for child in list(extractedRoot.iterdir()):
+ target = installDir / child.name
+ if target.exists():
+ self._removePath(target)
+ shutil.move(str(child), str(target))
+
+ ffmpegPath = self._findExecutable(installDir, _executableName("ffmpeg"))
+ ffprobePath = self._findExecutable(installDir, _executableName("ffprobe"))
+ if ffmpegPath is None or ffprobePath is None:
+ raise RuntimeError("安装包解压完成,但未找到 ffmpeg 或 ffprobe 可执行文件")
+
+ return _normalizePath(ffmpegPath), _normalizePath(ffprobePath)
+
+ async def run(self):
+ if sys.platform != "win32":
+ self.stage.setStatus(TaskStatus.FAILED)
+ raise RuntimeError("当前平台不支持 FFmpeg 一键安装")
+
+ archivePath = Path(self.stage.archivePath)
+ if not archivePath.is_file():
+ self.stage.setStatus(TaskStatus.FAILED)
+ raise FileNotFoundError(f"未找到 FFmpeg 安装包: {archivePath}")
+
+ installDir = Path(self.stage.installFolder)
+ tempDir = installDir / ".extracting"
+
+ try:
+ self.stage.progress = 0
+ self.stage.speed = 0
+ self.stage.receivedBytes = 0
+
+ installDir.mkdir(parents=True, exist_ok=True)
+ if tempDir.exists():
+ shutil.rmtree(tempDir, ignore_errors=True)
+ tempDir.mkdir(parents=True, exist_ok=True)
+
+ with zipfile.ZipFile(archivePath) as archive:
+ extractSize = sum(info.file_size for info in archive.infolist() if not info.is_dir())
+
+ self._updateTaskFileSize(extractSize)
+ await self._extractArchive(archivePath, tempDir, extractSize)
+
+ extractedRoot = self._resolveExtractedRoot(tempDir)
+ ffmpegPath, ffprobePath = self._installExtractedFiles(
+ extractedRoot,
+ installDir,
+ archivePath.name,
+ tempDir.name,
+ )
+
+ task = getattr(self.stage, "_task", None)
+ if task is not None:
+ task.ffmpegPath = ffmpegPath
+ task.ffprobePath = ffprobePath
+
+ cfg.set(ffmpegConfig.installFolder, _normalizePath(installDir))
+ setPreferredFFmpegExecutables(ffmpegPath, ffprobePath)
+
+ if self.stage.cleanupArchive and archivePath.exists():
+ archivePath.unlink()
+
+ self.stage.ffmpegPath = ffmpegPath
+ self.stage.ffprobePath = ffprobePath
+ self.stage.setStatus(TaskStatus.COMPLETED)
+ except asyncio.CancelledError:
+ self.stage.setStatus(TaskStatus.PAUSED)
+ raise
+ except Exception:
+ self.stage.setStatus(TaskStatus.FAILED)
+ raise
+ finally:
+ if tempDir.exists():
+ shutil.rmtree(tempDir, ignore_errors=True)
+
+
+@dataclass(kw_only=True)
+class FFmpegInstallTask(Task):
+ url: str
+ assetName: str
+ headers: dict = field(default_factory=lambda: _FFMPEG_HEADERS.copy())
+ proxies: dict = field(default_factory=getProxies)
+ blockNum: int = field(default=8)
+ installFolder: str
+ archiveSize: int = field(default=0)
+ archivePath: str = field(default="")
+ ffmpegPath: str = field(default="")
+ ffprobePath: str = field(default="")
+
+ @property
+ def resolvePath(self) -> str:
+ return self.ffmpegPath or self.archivePath or str(Path(self.installFolder) / self.title)
+
+ def __post_init__(self):
+ super().__post_init__()
+ self.syncStagePaths()
+
+ def syncStagePaths(self):
+ installDir = Path(self.installFolder)
+ self.path = installDir
+ self.archivePath = _normalizePath(installDir / self.assetName)
+ self.ffmpegPath = _normalizePath(installDir / "bin" / _executableName("ffmpeg"))
+ self.ffprobePath = _normalizePath(installDir / "bin" / _executableName("ffprobe"))
+
+ for stage in self.stages:
+ if isinstance(stage, HttpTaskStage):
+ stage.resolvePath = self.archivePath
+ elif isinstance(stage, FFmpegExtractStage):
+ stage.archivePath = self.archivePath
+ stage.installFolder = _normalizePath(installDir)
+ stage.ffmpegPath = self.ffmpegPath
+ stage.ffprobePath = self.ffprobePath
+
+ async def run(self):
+ self.stages.sort(key=lambda stage: stage.stageIndex)
+ try:
+ for stage in self.stages:
+ if self.status != TaskStatus.RUNNING:
+ break
+ if stage.status == TaskStatus.COMPLETED:
+ continue
+
+ if isinstance(stage, HttpTaskStage):
+ await HttpWorker(stage).run()
+ continue
+
+ if isinstance(stage, FFmpegExtractStage):
+ await FFmpegExtractWorker(stage).run()
+ continue
+
+ raise TypeError(f"不支持的 FFmpegInstallTaskStage: {type(stage).__name__}")
+ except asyncio.CancelledError:
+ logger.info(f"{self.title} 停止安装")
+ raise
+ except Exception as e:
+ logger.error(f"{self.title} 安装失败: {repr(e)}")
+ raise
+
+ def __hash__(self):
+ return hash(self.taskId)
+
+
+async def createWindowsInstallTask() -> FFmpegInstallTask:
+ assetInfo = await _requestLatestReleaseAsset()
+ _, archLabel = _detectWindowsTarget()
+ installFolder = ffmpegConfig.installFolder.value
+ installPath = Path(installFolder)
+
+ task = FFmpegInstallTask(
+ title=f"FFmpeg 安装 ({archLabel})",
+ url=assetInfo["url"],
+ assetName=assetInfo["name"],
+ fileSize=assetInfo["size"],
+ headers=_FFMPEG_HEADERS.copy(),
+ proxies=getProxies(),
+ path=installPath,
+ installFolder=installFolder,
+ archiveSize=assetInfo["size"],
+ )
+
+ downloadStage = HttpTaskStage(
+ stageIndex=1,
+ url=task.url,
+ fileSize=assetInfo["size"],
+ headers=task.headers.copy(),
+ proxies=task.proxies,
+ resolvePath=task.archivePath,
+ blockNum=task.blockNum,
+ )
+ extractStage = FFmpegExtractStage(
+ stageIndex=2,
+ archivePath=task.archivePath,
+ installFolder=task.installFolder,
+ ffmpegPath=task.ffmpegPath,
+ ffprobePath=task.ffprobePath,
+ )
+
+ task.addStage(downloadStage)
+ task.addStage(extractStage)
+ task.syncStagePaths()
+ return task