The only downloader you need. 下载器的集大成者。
TypeScript asyncasynciobittorentbtcross-platformdownload-managerdownloaderfluent-designftphttp3magnetpyqtpyside6pythonqtquicreactsoftwarestreaming
feat(m3u8): 完善流媒体下载与直播录制
XiaoYouChR7b333beba58d
diff --git a/app/view/components/setting_cards.py b/app/view/components/setting_cards.pyindex 999b1470..b98786df 100644--- a/app/view/components/setting_cards.py+++ b/app/view/components/setting_cards.py@@ -77,6 +77,46 @@ class SpinBoxSettingCard(SettingCard):cfg.set(self.configItem, self.spinBox.value() / self.division)+class LineEditSettingCard(SettingCard):+ """绑定字符串 ConfigItem 的行编辑设置卡"""++ def __init__(+ self,+ icon,+ title,+ content=None,+ configItem: ConfigItem = None,+ parent=None,+ placeholder: str = "",+ ):+ super().__init__(icon, title, content, parent)+ self.configItem = configItem++ self.lineEdit = LineEdit(self)++ self._initWidget(placeholder)+ self._initLayout()+ self._bind()++ def _initWidget(self, placeholder: str):+ self.lineEdit.setMinimumWidth(180)+ self.lineEdit.setClearButtonEnabled(True)+ self.lineEdit.setPlaceholderText(placeholder)+ if self.configItem:+ self.lineEdit.setText(self.configItem.value)++ def _initLayout(self):+ self.hBoxLayout.addWidget(self.lineEdit)+ self.hBoxLayout.addSpacing(16)++ def _bind(self):+ self.lineEdit.editingFinished.connect(self._onEditingFinished)++ def _onEditingFinished(self):+ if self.configItem:+ cfg.set(self.configItem, self.lineEdit.text())++class ProxySettingCard(ExpandGroupSettingCard):"""Custom proxyServer setting card"""@@ -342,6 +382,49 @@ class InstallFolderCard(SettingCard):self._updatePath(self.defaultPath)+class SelectFileCard(SettingCard):+ pathChanged = Signal(str)++ def __init__(self, configItem: ConfigItem, icon, title: str, hint: str,+ browseTitle: str, parent=None):+ super().__init__(icon, title, configItem.value or hint, parent)+ self.configItem = configItem+ self.hint = hint+ self.browseTitle = browseTitle+ self.chooseFileButton = ToolButton(FluentIcon.FOLDER, self)+ self.clearButton = ToolButton(FluentIcon.CANCEL, self)++ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self):+ self.chooseFileButton.setToolTip(self.tr("选择文件"))+ self.chooseFileButton.installEventFilter(ToolTipFilter(self.chooseFileButton))+ self.clearButton.setToolTip(self.tr("清除路径"))+ self.clearButton.installEventFilter(ToolTipFilter(self.clearButton))++ def _initLayout(self):+ self.hBoxLayout.addWidget(self.chooseFileButton, 0, Qt.AlignmentFlag.AlignRight)+ self.hBoxLayout.addSpacing(8)+ self.hBoxLayout.addWidget(self.clearButton, 0, Qt.AlignmentFlag.AlignRight)+ self.hBoxLayout.addSpacing(16)++ def _bind(self):+ self.chooseFileButton.clicked.connect(self._onChooseFile)+ self.clearButton.clicked.connect(lambda: self._updatePath(""))++ def _onChooseFile(self):+ path, _ = QFileDialog.getOpenFileName(self.window(), self.browseTitle)+ if path:+ self._updatePath(path)++ def _updatePath(self, path: str):+ cfg.set(self.configItem, path)+ self.setContent(path or self.hint)+ self.pathChanged.emit(path)++_MAX_HISTORY: Final[int] = 7diff --git a/features/m3u8_pack/cards.py b/features/m3u8_pack/cards.pyindex 83104539..77f2d586 100644--- a/features/m3u8_pack/cards.py+++ b/features/m3u8_pack/cards.py@@ -1,11 +1,34 @@-from PySide6.QtCore import QEvent, QFileInfo, Qt-from PySide6.QtGui import QMouseEvent-from PySide6.QtWidgets import QFileIconProvider, QHBoxLayout, QWidget-from qfluentwidgets import BodyLabel, ImageLabel, LineEdit, StrongBodyLabel+from pathlib import Path+from typing import TYPE_CHECKING, Any, cast++from PySide6.QtCore import QEvent, QFileInfo, Qt, Signal+from PySide6.QtGui import QColor, QMouseEvent, QPainter+from PySide6.QtWidgets import QFileDialog, QFileIconProvider, QHBoxLayout, QVBoxLayout, QWidget+from qfluentwidgets import (+ BodyLabel,+ ComboBox,+ CompactSpinBox,+ FluentIcon,+ IconWidget,+ ImageLabel,+ LineEdit,+ PushButton,+ StrongBodyLabel,+ TransparentToolButton,+ isDarkTheme,+)++from loguru import loggerfrom app.bases.models import Task, TaskStatus+from app.services.core_service import coreService+from app.services.task_service import taskServicefrom app.supports.utils import toReadableSize, toReadableTime-from app.view.components.cards import ResultCard, UniversalTaskCard+from app.view.components.cards import ParseSettingCard, ResultCard, UniversalTaskCard+from app.view.components.editors import AutoSizingEdit++if TYPE_CHECKING:+ from .task import M3U8TaskStageclass M3U8TaskCard(UniversalTaskCard):@@ -49,6 +72,86 @@ class M3U8TaskCard(UniversalTaskCard):self.refreshToggleButton()+class M3U8LiveTaskCard(M3U8TaskCard):+ """直播录制卡:主按钮为「停止并定案」,展示 录制中/等待 与已录时长"""++ def _renderTaskState(self):+ progress, speed, _ = self.task.currentSnapshot()+ self.progressBar.setValue(progress)+ stage = cast("M3U8TaskStage", self.task.stages[0])++ if self.task.status == TaskStatus.RUNNING:+ self.progressBar.setError(False)+ if self.infoLabel.isVisible():+ self.infoLabel.hide()+ self.speedLabel.show()+ self.leftTimeLabel.show()+ self.progressLabel.show()+ self.speedLabel.setText(f"{toReadableSize(speed)}/s")+ self.leftTimeLabel.setText(self._liveTimeText(stage))+ if stage.liveStatus == "Waiting":+ self.progressLabel.setText(self.tr("等待中"))+ self.progressBar.pause()+ else:+ self.progressLabel.setText(self.tr("录制中"))+ self.progressBar.resume()+ elif self.task.status == TaskStatus.COMPLETED:+ self.progressBar.setError(False)+ self.progressBar.hide()+ self.showStatusInfo(self.tr("录制已结束"))+ elif self.task.status == TaskStatus.FAILED:+ self.progressBar.error()+ self.onTaskFailed()+ else:+ self.progressBar.setError(False)+ self.progressBar.pause()+ self.showStatusInfo(self.tr("等待录制"))++ self.refreshToggleButton()++ def _liveTimeText(self, stage: "M3U8TaskStage") -> str:+ elapsed = stage.liveElapsed or "00m00s"+ return f"{elapsed} / {stage.recordLimit}" if stage.recordLimit else elapsed++ def refreshToggleButton(self):+ status = self.task.status+ if status == TaskStatus.RUNNING:+ self.toggleRunningStatusButton.setIcon(FluentIcon.ACCEPT)+ self.toggleRunningStatusButton.setToolTip(self.tr("停止并定案"))+ self.toggleRunningStatusButton.setEnabled(True)+ elif status == TaskStatus.COMPLETED:+ self.toggleRunningStatusButton.setIcon(FluentIcon.ACCEPT)+ self.toggleRunningStatusButton.setEnabled(False)+ else:+ self.toggleRunningStatusButton.setIcon(FluentIcon.PLAY)+ self.toggleRunningStatusButton.setEnabled(True)++ self.verifyHashButton.setVisible(status == TaskStatus.COMPLETED)+ self.verifyHashButton.setEnabled(status == TaskStatus.COMPLETED)++ def toggleRunningStatus(self):+ if self.task.status == TaskStatus.RUNNING:+ self.finalizeRecording()+ else:+ self.resumeTask()++ def finalizeRecording(self):+ # 直播无暂停:停止=取消进程, worker 收尾标 COMPLETED;不走 stopTask 以免 PAUSED 闪烁+ self.toggleRunningStatusButton.setDisabled(True)+ coreService.runCoroutine(coreService._stopTask(self.task), self._onRecordingFinalized)++ def _onRecordingFinalized(self, _result=None, error: str | None = None):+ if error:+ logger.warning("停止直播录制失败 {}: {}", self.task.title, error)+ self._renderTaskState()+ return+ if self.task.status == TaskStatus.COMPLETED and self.cardStatus != TaskStatus.COMPLETED:+ self.onTaskFinished()+ self._renderTaskState()+ if self.task.status != self.cardStatus:+ taskService.scheduleFlush()+ self.cardStatus = self.task.status+class M3U8ResultCard(ResultCard):def __init__(self, task: Task, parent: QWidget = None):@@ -119,3 +222,207 @@ class M3U8ResultCard(ResultCard):def getTask(self) -> Task:return self.task+++class _M3U8EditCard(QWidget):+ """编辑对话框里的多行设置卡,提供 payloadChanged 信号与顶部分隔线"""++ payloadChanged = Signal()++ def paintEvent(self, event):+ painter = QPainter(self)+ painter.setRenderHints(QPainter.RenderHint.Antialiasing)+ painter.setPen(QColor(0, 0, 0, 96 if isDarkTheme() else 48))+ painter.drawLine(self.rect().topLeft(), self.rect().topRight())+++class M3U8TrackEditCard(ParseSettingCard):+ def __init__(self, icon, title: str, parent=None, *, streams: list, initial: str = "") -> None:+ self._streams = streams+ self._initialExpr = initial+ super().__init__(icon, title, parent)++ def initCustomWidget(self) -> None:+ self.trackCombo = ComboBox(self)+ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self) -> None:+ self.trackCombo.setMinimumWidth(220)+ self.trackCombo.addItem(self.tr("默认(最佳)"), userData="")+ selectedIndex = 0+ for index, stream in enumerate(self._streams, start=1):+ expr = stream.get("selectExpr", "")+ self.trackCombo.addItem(stream.get("label", ""), userData=expr)+ if self._initialExpr and expr == self._initialExpr:+ selectedIndex = index+ self.trackCombo.setCurrentIndex(selectedIndex)++ def _initLayout(self) -> None:+ self.hBoxLayout.addWidget(self.trackCombo)+ self.hBoxLayout.addSpacing(16)++ def _bind(self) -> None:+ self.trackCombo.currentIndexChanged.connect(lambda _: self.payloadChanged.emit())++ @property+ def payload(self) -> dict[str, Any]:+ return {"selectVideo": self.trackCombo.currentData() or ""}+++class M3U8RecordLimitEditCard(ParseSettingCard):+ def __init__(self, icon, title: str, parent=None, *, initial: str = "") -> None:+ self._initialLimit = initial+ super().__init__(icon, title, parent)++ def initCustomWidget(self) -> None:+ self.hourSpinBox = CompactSpinBox(self)+ self.minuteSpinBox = CompactSpinBox(self)+ self.secondSpinBox = CompactSpinBox(self)+ self._initWidget()+ self._initLayout()+ self._bind()++ def _initWidget(self) -> None:+ self.hourSpinBox.setRange(0, 99)+ self.minuteSpinBox.setRange(0, 59)+ self.secondSpinBox.setRange(0, 59)+ for box in (self.hourSpinBox, self.minuteSpinBox, self.secondSpinBox):+ box.setFixedWidth(64)+ self._applyLimit(self._initialLimit)++ def _initLayout(self) -> None:+ self.hBoxLayout.addWidget(self.hourSpinBox)+ self.hBoxLayout.addWidget(BodyLabel(":", self))+ self.hBoxLayout.addWidget(self.minuteSpinBox)+ self.hBoxLayout.addWidget(BodyLabel(":", self))+ self.hBoxLayout.addWidget(self.secondSpinBox)+ self.hBoxLayout.addSpacing(16)++ def _bind(self) -> None:+ for box in (self.hourSpinBox, self.minuteSpinBox, self.secondSpinBox):+ box.valueChanged.connect(lambda _: self.payloadChanged.emit())++ def _applyLimit(self, limit: str) -> None:+ parts = limit.split(":") if limit else []+ if len(parts) != 3:+ return+ try:+ hours, minutes, seconds = (int(part) for part in parts)+ except ValueError:+ return+ self.hourSpinBox.setValue(hours)+ self.minuteSpinBox.setValue(minutes)+ self.secondSpinBox.setValue(seconds)++ @property+ def payload(self) -> dict[str, Any]:+ hours = self.hourSpinBox.value()+ minutes = self.minuteSpinBox.value()+ seconds = self.secondSpinBox.value()+ limit = f"{hours:02}:{minutes:02}:{seconds:02}" if hours + minutes + seconds > 0 else ""+ return {"recordLimit": limit}+++class M3U8DecryptionEditCard(_M3U8EditCard):+ def __init__(self, icon, title: str, parent=None, *, keys: list | None = None, keyTextFile: str = "") -> None:+ super().__init__(parent)+ self._keyTextFile = keyTextFile++ # instant widget+ self.iconWidget = IconWidget(icon, self)+ self.titleLabel = BodyLabel(title, self)+ self.keyFileButton = TransparentToolButton(FluentIcon.FOLDER_ADD, self)+ self.keysEdit = AutoSizingEdit(self, minimumVisibleLines=3, maximumVisibleLines=10)+ self.keyFileLabel = BodyLabel(self)++ # instant layout+ self.vBoxLayout = QVBoxLayout(self)+ self.titleRowLayout = QHBoxLayout()++ self._initWidget(keys or [])+ self._initLayout()+ self._bind()++ def _initWidget(self, keys: list) -> None:+ self.iconWidget.setFixedSize(16, 16)+ self.keyFileButton.setToolTip(self.tr("选择 KEY 文本文件"))+ self.keysEdit.setPlaceholderText("KID1:KEY1\nKID2:KEY2")+ self.keysEdit.setPlainText("\n".join(keys))+ self._refreshKeyFileLabel()++ def _initLayout(self) -> None:+ self.titleRowLayout.setSpacing(15)+ self.titleRowLayout.addWidget(self.iconWidget)+ self.titleRowLayout.addWidget(self.titleLabel)+ self.titleRowLayout.addStretch(1)+ self.titleRowLayout.addWidget(self.keyFileLabel)+ self.titleRowLayout.addWidget(self.keyFileButton)++ self.vBoxLayout.setContentsMargins(24, 10, 24, 12)+ self.vBoxLayout.setSpacing(10)+ self.vBoxLayout.addLayout(self.titleRowLayout)+ self.vBoxLayout.addWidget(self.keysEdit)++ def _bind(self) -> None:+ self.keysEdit.textChanged.connect(self.payloadChanged.emit)+ self.keyFileButton.clicked.connect(self._onChooseKeyFile)++ def _onChooseKeyFile(self) -> None:+ path, _ = QFileDialog.getOpenFileName(self, self.tr("选择 KEY 文本文件"))+ if not path:+ return+ self._keyTextFile = path+ self._refreshKeyFileLabel()+ self.payloadChanged.emit()++ def _refreshKeyFileLabel(self) -> None:+ self.keyFileLabel.setText(Path(self._keyTextFile).name if self._keyTextFile else "")++ @property+ def payload(self) -> dict[str, Any]:+ keys = [line.strip() for line in self.keysEdit.toPlainText().splitlines() if line.strip()]+ return {"decryptionKeys": keys, "keyTextFile": self._keyTextFile}+++class M3U8MuxImportEditCard(_M3U8EditCard):+ def __init__(self, icon, title: str, parent=None, *, initial: list | None = None) -> None:+ super().__init__(parent)++ # instant widget+ self.iconWidget = IconWidget(icon, self)+ self.titleLabel = BodyLabel(title, self)+ self.importEdit = AutoSizingEdit(self, minimumVisibleLines=3, maximumVisibleLines=10)++ # instant layout+ self.vBoxLayout = QVBoxLayout(self)+ self.titleRowLayout = QHBoxLayout()++ self._initWidget(initial or [])+ self._initLayout()+ self._bind()++ def _initWidget(self, imports: list) -> None:+ self.iconWidget.setFixedSize(16, 16)+ self.importEdit.setPlaceholderText('path="aud.m4a":lang=eng:name="Audio"')+ self.importEdit.setPlainText("\n".join(imports))++ def _initLayout(self) -> None:+ self.titleRowLayout.setSpacing(15)+ self.titleRowLayout.addWidget(self.iconWidget)+ self.titleRowLayout.addWidget(self.titleLabel)+ self.titleRowLayout.addStretch(1)++ self.vBoxLayout.setContentsMargins(24, 10, 24, 12)+ self.vBoxLayout.setSpacing(10)+ self.vBoxLayout.addLayout(self.titleRowLayout)+ self.vBoxLayout.addWidget(self.importEdit)++ def _bind(self) -> None:+ self.importEdit.textChanged.connect(self.payloadChanged.emit)++ @property+ def payload(self) -> dict[str, Any]:+ imports = [line.strip() for line in self.importEdit.toPlainText().splitlines() if line.strip()]+ return {"muxImports": imports}diff --git a/features/m3u8_pack/config.py b/features/m3u8_pack/config.pyindex 6925158f..0ec48e1f 100644--- a/features/m3u8_pack/config.py+++ b/features/m3u8_pack/config.py@@ -27,7 +27,7 @@ from app.services.core_service import coreServicefrom app.supports.paths import APP_DATA_DIRfrom app.supports.utils import findExecutable, toPosixPathfrom app.view.components.setting_card_group import CollapsibleSettingCardGroup-from app.view.components.setting_cards import InstallFolderCard, SpinBoxSettingCard+from app.view.components.setting_cards import InstallFolderCard, LineEditSettingCard, SelectFileCard, SpinBoxSettingCardif TYPE_CHECKING:from app.view.pages.setting_page import SettingPage@@ -146,6 +146,8 @@ class M3U8Config(PackConfig):f"{APP_DATA_DIR}/M3U8DL",FolderValidator(),)+ associateFileTypes = ConfigItem("M3U8", "AssociateFileTypes", False, BoolValidator())+outputFormat = OptionsConfigItem("M3U8", "OutputFormat", "mp4", OptionsValidator(["mp4", "mkv"]))threadCount = RangeConfigItem("M3U8", "ThreadCount", 8, RangeValidator(1, 64))retryCount = RangeConfigItem("M3U8", "RetryCount", 3, RangeValidator(0, 20))@@ -155,138 +157,180 @@ class M3U8Config(PackConfig):appendUrlParams = ConfigItem("M3U8", "AppendUrlParams", False, BoolValidator())binaryMerge = ConfigItem("M3U8", "BinaryMerge", False, BoolValidator())checkSegmentsCount = ConfigItem("M3U8", "CheckSegmentsCount", True, BoolValidator())- liveRealTimeMerge = ConfigItem("M3U8", "LiveRealTimeMerge", False, BoolValidator())++ # 直播(real-time-merge 对直播恒开,不设开关)liveKeepSegments = ConfigItem("M3U8", "LiveKeepSegments", False, BoolValidator())livePipeMux = ConfigItem("M3U8", "LivePipeMux", False, BoolValidator())- associateFileTypes = ConfigItem("M3U8", "AssociateFileTypes", False, BoolValidator())+ liveFixVtt = ConfigItem("M3U8", "LiveFixVtt", False, BoolValidator())+ liveWaitTime = RangeConfigItem("M3U8", "LiveWaitTime", 0, RangeValidator(0, 100000))+ liveTakeCount = RangeConfigItem("M3U8", "LiveTakeCount", 0, RangeValidator(0, 1000))++ decryptionEngine = OptionsConfigItem(+ "M3U8", "DecryptionEngine", "FFmpeg",+ OptionsValidator(["FFmpeg", "MP4Decrypt", "Shaka Packager"]),+ )+ decryptionBinaryPath = ConfigItem("M3U8", "DecryptionBinaryPath", "")+ mp4RealTimeDecryption = ConfigItem("M3U8", "MP4RealTimeDecryption", True, BoolValidator())++ maxSpeed = RangeConfigItem("M3U8", "MaxSpeed", -1, RangeValidator(-1, 1000000))+ speedUnit = OptionsConfigItem("M3U8", "SpeedUnit", "Mbps", OptionsValidator(["Mbps", "Kbps"]))+ adKeyword = ConfigItem("M3U8", "AdKeyword", "")+ subtitleFormat = OptionsConfigItem("M3U8", "SubtitleFormat", "SRT", OptionsValidator(["SRT", "VTT"]))+ noDateInfo = ConfigItem("M3U8", "NoDateInfo", False, BoolValidator())+ keepImageSegments = ConfigItem("M3U8", "KeepImageSegments", False, BoolValidator())+ delAfterDone = ConfigItem("M3U8", "DelAfterDone", True, BoolValidator())+ customMuxAfterDone = ConfigItem("M3U8", "CustomMuxAfterDone", "")+ selectAllAudioSubtitle = ConfigItem("M3U8", "SelectAllAudioSubtitle", True, BoolValidator())def setupSettings(self, settingPage: "SettingPage"):self.m3u8Group = CollapsibleSettingCardGroup(self.tr("流媒体下载"), "m3u8", settingPage.container)- # macOS 的文件关联在构建时烘进 Info.plist, 运行时开关无意义, 不创建也不显示- if sys.platform != "darwin":- self.associateCard = SwitchSettingCard(- FluentIcon.LINK,- self.tr("关联 M3U8/MPD 文件"),- self.tr("把 .m3u8/.m3u/.mpd 文件的打开方式设为 Ghost Downloader"),- self.associateFileTypes,- self.m3u8Group,- )- self.m3u8Group.addSettingCard(self.associateCard)self.installFolderCard = InstallFolderCard(- m3u8Config.installFolder,+ self.installFolder,f"{APP_DATA_DIR}/M3U8DL",self.tr("N_m3u8DL-RE 安装目录"),self.tr("选择 N_m3u8DL-RE 安装目录"),self.m3u8Group,)self.runtimeCard = M3U8RuntimeCard(self.m3u8Group)- self.outputFormatCard = ComboBoxSettingCard(- self.outputFormat,- FluentIcon.VIDEO,- self.tr("输出容器"),- self.tr("下载完成后优先使用 ffmpeg 混流为指定容器"),- texts=["MP4", "MKV"],- parent=self.m3u8Group,- )- self.threadCountCard = RangeSettingCard(- self.threadCount,- FluentIcon.CLOUD,- self.tr("分片线程数"),- self.tr("传给 N_m3u8DL-RE 的下载线程数"),- self.m3u8Group,- )- self.retryCountCard = RangeSettingCard(- self.retryCount,- FluentIcon.SYNC,- self.tr("分片重试次数"),- self.tr("单个分片下载失败时的最大重试次数"),- self.m3u8Group,- )- self.requestTimeoutCard = SpinBoxSettingCard(- FluentIcon.HISTORY,- self.tr("请求超时"),- self.tr("HTTP 请求超时时间"),- " s",- self.requestTimeout,- self.m3u8Group,- 5,- )- self.autoSelectCard = SwitchSettingCard(- FluentIcon.ACCEPT,- self.tr("自动选择最佳轨道"),- self.tr("默认选择最佳音视频轨道,避免每个链接都手动挑选"),- self.autoSelect,- self.m3u8Group,- )- self.concurrentDownloadCard = SwitchSettingCard(- FluentIcon.PAUSE,- self.tr("并发下载音视频"),- self.tr("同时下载已选择的音频、视频和字幕轨道"),- self.concurrentDownload,- self.m3u8Group,- )- self.appendUrlParamsCard = SwitchSettingCard(- FluentIcon.LINK,- self.tr("追加 URL 参数"),- self.tr("把输入链接上的 Query 参数追加到分片请求"),- self.appendUrlParams,- self.m3u8Group,- )- self.binaryMergeCard = SwitchSettingCard(- FluentIcon.ALIGNMENT,- self.tr("二进制合并"),- self.tr("让 N_m3u8DL-RE 使用二进制方式合并分片"),- self.binaryMerge,- self.m3u8Group,- )- self.checkSegmentsCountCard = SwitchSettingCard(- FluentIcon.SEARCH,- self.tr("校验分片数量"),- self.tr("下载完成后检查实际分片数是否与预期一致"),- self.checkSegmentsCount,- self.m3u8Group,- )- self.liveRealTimeMergeCard = SwitchSettingCard(- FluentIcon.CAMERA,- self.tr("直播实时合并"),- self.tr("录制直播流时边下边合并"),- self.liveRealTimeMerge,- self.m3u8Group,- )- self.liveKeepSegmentsCard = SwitchSettingCard(- FluentIcon.SAVE,- self.tr("直播保留分片"),- self.tr("实时合并直播时仍保留原始分片"),- self.liveKeepSegments,- self.m3u8Group,- )- self.livePipeMuxCard = SwitchSettingCard(- FluentIcon.CODE,- self.tr("直播管道混流"),- self.tr("直播实时合并时通过管道交给 ffmpeg 混流"),- self.livePipeMux,- self.m3u8Group,- )- self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())- for card in (- self.installFolderCard,- self.runtimeCard,- self.outputFormatCard,- self.threadCountCard,- self.retryCountCard,- self.requestTimeoutCard,- self.autoSelectCard,- self.concurrentDownloadCard,- self.appendUrlParamsCard,- self.binaryMergeCard,- self.checkSegmentsCountCard,- self.liveRealTimeMergeCard,- self.liveKeepSegmentsCard,- self.livePipeMuxCard,- ):- self.m3u8Group.addSettingCard(card)+ cards = [self.installFolderCard, self.runtimeCard]+ # macOS 的文件关联在构建时烘进 Info.plist, 运行时开关无意义, 不创建也不显示+ if sys.platform != "darwin":+ cards.append(SwitchSettingCard(+ FluentIcon.LINK,+ self.tr("关联 M3U8/MPD 文件"),+ self.tr("把 .m3u8/.m3u/.mpd 文件的打开方式设为 Ghost Downloader"),+ self.associateFileTypes,+ self.m3u8Group,+ ))+ cards += [+ ComboBoxSettingCard(+ self.outputFormat, FluentIcon.VIDEO, self.tr("输出容器"),+ self.tr("点播下载完成后优先使用 ffmpeg 混流为指定容器"),+ texts=["MP4", "MKV"], parent=self.m3u8Group,+ ),+ RangeSettingCard(+ self.threadCount, FluentIcon.CLOUD, self.tr("分片线程数"),+ self.tr("传给 N_m3u8DL-RE 的下载线程数"), self.m3u8Group,+ ),+ RangeSettingCard(+ self.retryCount, FluentIcon.SYNC, self.tr("分片重试次数"),+ self.tr("单个分片下载失败时的最大重试次数"), self.m3u8Group,+ ),+ SpinBoxSettingCard(+ FluentIcon.HISTORY, self.tr("请求超时"), self.tr("HTTP 请求超时时间"),+ " s", self.requestTimeout, self.m3u8Group, 5,+ ),+ SwitchSettingCard(+ FluentIcon.ACCEPT, self.tr("自动选择最佳轨道"),+ self.tr("默认选择最佳音视频轨道,避免每个链接都手动挑选"),+ self.autoSelect, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.PAUSE, self.tr("并发下载音视频"),+ self.tr("同时下载已选择的音频、视频和字幕轨道"),+ self.concurrentDownload, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.LINK, self.tr("追加 URL 参数"),+ self.tr("把输入链接上的 Query 参数追加到分片请求"),+ self.appendUrlParams, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.ALIGNMENT, self.tr("二进制合并"),+ self.tr("让 N_m3u8DL-RE 使用二进制方式合并分片"),+ self.binaryMerge, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.SEARCH, self.tr("校验分片数量"),+ self.tr("下载完成后检查实际分片数是否与预期一致"),+ self.checkSegmentsCount, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.SAVE, self.tr("直播保留原始分片"),+ self.tr("实时合并录制时仍保留下载的原始分片"),+ self.liveKeepSegments, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.CODE, self.tr("直播管道混流"),+ self.tr("录制时通过管道交给 ffmpeg 实时混流为封装容器"),+ self.livePipeMux, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.FONT, self.tr("直播校正 VTT 字幕"),+ self.tr("根据音频起始时间校正 VTT 字幕时间轴"),+ self.liveFixVtt, self.m3u8Group,+ ),+ SpinBoxSettingCard(+ FluentIcon.STOP_WATCH, self.tr("直播刷新等待时间"),+ self.tr("两次拉取直播清单之间的等待秒数,0 为自动"),+ " s", self.liveWaitTime, self.m3u8Group, 1,+ ),+ SpinBoxSettingCard(+ FluentIcon.DOWNLOAD, self.tr("直播每次取片数"),+ self.tr("每次刷新最多取走的分片数量,0 为自动"),+ "", self.liveTakeCount, self.m3u8Group, 1,+ ),+ ComboBoxSettingCard(+ self.decryptionEngine, FluentIcon.CERTIFICATE, self.tr("解密引擎"),+ self.tr("调用的第三方解密程序"),+ texts=["FFmpeg", "MP4Decrypt", "Shaka Packager"], parent=self.m3u8Group,+ ),+ SelectFileCard(+ self.decryptionBinaryPath, FluentIcon.COMMAND_PROMPT, self.tr("解密引擎二进制路径"),+ self.tr("MP4Decrypt / Shaka Packager 可执行文件路径,留空则使用 FFmpeg"),+ self.tr("选择解密引擎可执行文件"), self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.FINGERPRINT, self.tr("MP4 实时解密"),+ self.tr("下载 MP4 分片时实时解密"),+ self.mp4RealTimeDecryption, self.m3u8Group,+ ),+ SpinBoxSettingCard(+ FluentIcon.SPEED_HIGH, self.tr("限速"),+ self.tr("最大下载速度,-1 为不限速"),+ "", self.maxSpeed, self.m3u8Group, 1,+ ),+ ComboBoxSettingCard(+ self.speedUnit, FluentIcon.TAG, self.tr("限速单位"),+ self.tr("限速数值的单位"), texts=["Mbps", "Kbps"], parent=self.m3u8Group,+ ),+ LineEditSettingCard(+ FluentIcon.REMOVE, self.tr("广告过滤"),+ self.tr("匹配广告分片 URL 的正则表达式"),+ self.adKeyword, self.m3u8Group, placeholder=self.tr("正则表达式"),+ ),+ ComboBoxSettingCard(+ self.subtitleFormat, FluentIcon.DICTIONARY, self.tr("字幕格式"),+ self.tr("字幕输出格式"), texts=["SRT", "VTT"], parent=self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.DATE_TIME, self.tr("不写入日期信息"),+ self.tr("混流时不写入日期信息"), self.noDateInfo, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.PHOTO, self.tr("保留图形分片"),+ self.tr("把图形字幕转图片后保留原始分片"),+ self.keepImageSegments, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.DELETE, self.tr("完成后删除临时文件"),+ self.tr("下载完成后删除分片临时目录"), self.delAfterDone, self.m3u8Group,+ ),+ SwitchSettingCard(+ FluentIcon.MUSIC, self.tr("下载全部音轨与字幕"),+ self.tr("默认拉取全部音频与字幕轨道,而非仅最佳"),+ self.selectAllAudioSubtitle, self.m3u8Group,+ ),+ LineEditSettingCard(+ FluentIcon.VIDEO, self.tr("自定义混流参数"),+ self.tr("自定义 --mux-after-done,留空则按输出容器自动混流"),+ self.customMuxAfterDone, self.m3u8Group, placeholder="format=mp4",+ ),+ ]+ self.m3u8Group.addSettingCards(cards)+ self.installFolderCard.pathChanged.connect(lambda _: self.runtimeCard.refreshStatus())settingPage.addSettingGroup(self.m3u8Group)self.runtimeCard.refreshStatus()diff --git a/features/m3u8_pack/pack.py b/features/m3u8_pack/pack.pyindex d76a9084..649b42ea 100644--- a/features/m3u8_pack/pack.py+++ b/features/m3u8_pack/pack.py@@ -8,7 +8,10 @@ from typing import TYPE_CHECKING, Literalfrom urllib.parse import parse_qs, unquote, urlparsefrom urllib.request import url2pathname+import m3u8import niquests+from loguru import logger+from mpegdash.parser import MPEGDASHParserfrom app.bases.interfaces import FeaturePack, FileTypefrom app.bases.models import Task@@ -16,7 +19,7 @@ from app.supports import file_associationfrom app.supports.config import activeUserAgent, cfg, defaultHeadersfrom app.supports.utils import getProxies, splitCookies, toExecutable, toSafeFilenamefrom app.view.components.cards import UniversalTaskCard-from .cards import M3U8ResultCard, M3U8TaskCard+from .cards import M3U8LiveTaskCard, M3U8ResultCard, M3U8TaskCardfrom .config import m3u8Configfrom .task import M3U8Task, M3U8TaskStage@@ -106,6 +109,111 @@ def loadLocalManifest(source: str) -> Path | None:return path if path.suffix.lower() in _MANIFEST_SUFFIXES else None+def _toFrameRate(value) -> float | None:+ if not value:+ return None+ text = str(value)+ if "/" in text:+ num, den = text.split("/")+ return int(num) / int(den) if int(den) else None+ return float(text)+++def _isVideoRepresentation(adaptationSet, representation) -> bool:+ if (adaptationSet.content_type or "").lower() == "video":+ return True+ mimeType = (adaptationSet.mime_type or representation.mime_type or "").lower()+ if mimeType.startswith("video"):+ return True+ return bool(representation.id and "video" in representation.id)+++def _streamEntry(width: int, height: int, codecs: str | None, frameRate: float | None) -> dict:+ label = [f"{width}×{height}"]+ if codecs:+ label.append(codecs)+ if frameRate:+ label.append(f"{frameRate:.0f}fps")+ selectExpr = [f'res="{width}*"']+ if frameRate:+ selectExpr.append(f'frame="{int(frameRate)}*"')+ return {"label": " · ".join(label), "selectExpr": ":".join(selectExpr)}+++def _hlsStreams(body: str) -> list[dict]:+ playlist = m3u8.loads(body)+ streams = []+ for variant in playlist.playlists:+ resolution = variant.stream_info.resolution+ if not resolution:+ continue+ width, height = resolution+ streams.append(_streamEntry(width, height, variant.stream_info.codecs, variant.stream_info.frame_rate))+ return streams+++def _mpdStreams(body: str) -> list[dict]:+ mpd = MPEGDASHParser.parse(body)+ if not mpd.periods:+ return []+ streams = []+ for adaptationSet in mpd.periods[0].adaptation_sets:+ for representation in adaptationSet.representations:+ if not representation.width or not _isVideoRepresentation(adaptationSet, representation):+ continue+ streams.append(_streamEntry(+ representation.width,+ representation.height,+ representation.codecs,+ _toFrameRate(representation.frame_rate),+ ))+ return streams+++def resolveStreams(manifestType: str, body: str) -> list[dict]:+ # 枚举失败不该阻断下载——auto-select 仍能工作, 仅轨道下拉缺项+ try:+ return _mpdStreams(body) if manifestType == "mpd" else _hlsStreams(body)+ except Exception as e:+ logger.warning("枚举可选视频流失败: {}", repr(e))+ return []+++async def _resolveLive(manifestType: str, body: str, baseUrl: str, headers: dict, proxies) -> bool:+ if manifestType == "mpd":+ lowered = body.lower()+ return 'type="dynamic"' in lowered or "type='dynamic'" in lowered++ playlist = m3u8.loads(body, uri=baseUrl)+ if playlist.segments:+ return not playlist.is_endlist+ if not playlist.playlists:+ return "#ext-x-endlist" not in body.lower()++ # master playlist 本身无 ENDLIST, 真伪直播只能看其变体 media playlist+ variantUrl = playlist.playlists[0].absolute_uri or ""+ if not variantUrl.lower().startswith(("http://", "https://")):+ return False+ try:+ requestHeaders, requestCookies = splitCookies(headers)+ async with niquests.AsyncSession(timeout=30, happy_eyeballs=True) as client:+ client.trust_env = False+ response = await client.get(+ variantUrl,+ headers=requestHeaders,+ cookies=requestCookies,+ proxies=proxies,+ verify=cfg.SSLVerify.value,+ allow_redirects=True,+ )+ response.raise_for_status()+ variantBody = response.text+ return not m3u8.loads(variantBody, uri=variantUrl).is_endlist+ except Exception as e:+ logger.warning("取变体清单判活失败, 按点播处理: {}", repr(e))+ return False++class M3U8Pack(FeaturePack):packId = "m3u8"priority = 80@@ -140,6 +248,8 @@ class M3U8Pack(FeaturePack):from disk_pack.task import InstallTaskif isinstance(task, InstallTask):return UniversalTaskCard(task, parent)+ if getattr(task, "isLive", False):+ return M3U8LiveTaskCard(task, parent)return M3U8TaskCard(task, parent)def resultCard(self, task, parent=None):@@ -192,13 +302,11 @@ class M3U8Pack(FeaturePack):manifestUrl = response.urlmanifestType = _manifestType(manifestUrl, loweredHeaders, body)- loweredBody = body.lower()- if manifestType == "mpd":- isLive = 'type="dynamic"' in loweredBody or "type='dynamic'" in loweredBody- else:- isLive = "#ext-x-endlist" not in loweredBody- extension = "ts" if m3u8Config.liveRealTimeMerge.value else m3u8Config.outputFormat.value+ isLive = await _resolveLive(manifestType, body, manifestUrl, headers, proxies)+ # 直播恒走 real-time-merge 直出 .ts;点播按输出容器+ extension = "ts" if isLive else m3u8Config.outputFormat.valuetitle = _title(manifestUrl, loweredHeaders, extension)+ streams = resolveStreams(manifestType, body)task = M3U8Task(title=title,@@ -207,6 +315,7 @@ class M3U8Pack(FeaturePack):path=path,manifestType=manifestType,isLive=isLive,+ streams=streams,)stage = M3U8TaskStage(@@ -221,10 +330,24 @@ class M3U8Pack(FeaturePack):appendUrlParams=m3u8Config.appendUrlParams.value,binaryMerge=m3u8Config.binaryMerge.value,checkSegmentsCount=m3u8Config.checkSegmentsCount.value,+ delAfterDone=m3u8Config.delAfterDone.value,outputFormat=m3u8Config.outputFormat.value,- liveRealTimeMerge=m3u8Config.liveRealTimeMerge.value,+ customMuxAfterDone=m3u8Config.customMuxAfterDone.value,+ subtitleFormat=m3u8Config.subtitleFormat.value,+ selectAllAudioSubtitle=m3u8Config.selectAllAudioSubtitle.value,+ maxSpeed=m3u8Config.maxSpeed.value,+ speedUnit=m3u8Config.speedUnit.value,+ adKeyword=m3u8Config.adKeyword.value,+ noDateInfo=m3u8Config.noDateInfo.value,+ keepImageSegments=m3u8Config.keepImageSegments.value,+ decryptionEngine=m3u8Config.decryptionEngine.value,+ decryptionBinaryPath=m3u8Config.decryptionBinaryPath.value,+ mp4RealTimeDecryption=m3u8Config.mp4RealTimeDecryption.value,liveKeepSegments=m3u8Config.liveKeepSegments.value,livePipeMux=m3u8Config.livePipeMux.value,+ liveFixVtt=m3u8Config.liveFixVtt.value,+ liveWaitTime=m3u8Config.liveWaitTime.value,+ liveTakeCount=m3u8Config.liveTakeCount.value,)task.addStage(stage)return taskdiff --git a/features/m3u8_pack/task.py b/features/m3u8_pack/task.pyindex 203cc36d..b705faff 100644--- a/features/m3u8_pack/task.py+++ b/features/m3u8_pack/task.py@@ -1,4 +1,5 @@import asyncio+import osimport refrom contextlib import suppressfrom dataclasses import dataclass, field@@ -26,6 +27,11 @@ _LIVE_PROGRESS_PATTERN = re.compile(r"(\d{2}m\d{2}s)/(\d{2}m\d{2}s)\s+\d+/\d+\s+(Recording|Waiting)\s+(\d+)%\s+(-|(\d+\.\d+)(GBps|MBps|KBps|Bps))")_IGNORED_OUTPUT_SUFFIXES = {".json", ".txt", ".log", ".tmp", ".ghd"}+_DECRYPTION_ENGINES = {+ "FFmpeg": "FFMPEG",+ "MP4Decrypt": "MP4DECRYPT",+ "Shaka Packager": "SHAKA_PACKAGER",+}def _toBool(value: bool) -> str:@@ -35,10 +41,12 @@ def _toBool(value: bool) -> str:@dataclass(kw_only=True)class M3U8TaskStage(TaskStage):workerType: type = field(init=False, repr=False)- canPause: bool = field(init=False, default=True)actualExtension: str = ""lastMessage: str = ""+ liveStatus: str = ""+ liveElapsed: str = ""+ liveTotal: str = ""headers: dict[str, str] = field(default_factory=dict)proxies: dict[str, str] = field(default_factory=dict)@@ -51,11 +59,39 @@ class M3U8TaskStage(TaskStage):appendUrlParams: bool = FalsebinaryMerge: bool = FalsecheckSegmentsCount: bool = True+ delAfterDone: bool = TrueoutputFormat: str = "mp4"- liveRealTimeMerge: bool = False+ customMuxAfterDone: str = ""+ subtitleFormat: str = "SRT"+ selectVideo: str = ""+ selectAllAudioSubtitle: bool = True+ maxSpeed: int = -1+ speedUnit: str = "Mbps"+ adKeyword: str = ""+ noDateInfo: bool = False+ keepImageSegments: bool = False++ decryptionEngine: str = "FFmpeg"+ decryptionBinaryPath: str = ""+ mp4RealTimeDecryption: bool = True+ decryptionKeys: list[str] = field(default_factory=list)+ keyTextFile: str = ""++ muxImports: list[str] = field(default_factory=list)++ # 直播(real-time-merge 对直播恒开,不设字段)liveKeepSegments: bool = FalselivePipeMux: bool = False+ liveFixVtt: bool = False+ liveWaitTime: int = 0+ liveTakeCount: int = 0+ recordLimit: str = ""++ @property+ def canPause(self) -> bool:+ # 直播无暂停语义——只有「停止并定案」+ return not self.task.isLive@propertydef outputFile(self) -> str:@@ -80,6 +116,8 @@ class M3U8Task(Task):manifestType: Literal["m3u8", "mpd"] = "m3u8"isLive: bool = False+ # parse() 时枚举的可选视频流 [{"label","selectExpr"}];只服务于轨道下拉, 不持久化+ streams: list = field(default_factory=list, repr=False)@propertydef stage(self) -> "M3U8TaskStage":@@ -94,15 +132,43 @@ class M3U8Task(Task):return self.stage.proxiesdef editorCards(self, parent) -> list["ParseSettingCard"]:+ from qfluentwidgets import FluentIcon+from app.view.components.add_task_dialog import SelectFolderCardfrom app.view.components.edit_task_cards import HeadersEditCard, ProxiesEditCard- from qfluentwidgets import FluentIcon+ from .cards import (+ M3U8DecryptionEditCard,+ M3U8MuxImportEditCard,+ M3U8RecordLimitEditCard,+ M3U8TrackEditCard,+ )- return [+ cards: list["ParseSettingCard"] = [HeadersEditCard(FluentIcon.GLOBE, parent.tr("请求标头"), parent, initial=self.headers),ProxiesEditCard(FluentIcon.CERTIFICATE, parent.tr("代理服务器"), parent, initial=self.proxies),+ ]+ if len(self.streams) > 1:+ cards.append(M3U8TrackEditCard(+ FluentIcon.VIDEO, parent.tr("视频轨道"), parent,+ streams=self.streams, initial=self.stage.selectVideo,+ ))+ if self.isLive:+ cards.append(M3U8RecordLimitEditCard(+ FluentIcon.STOP_WATCH, parent.tr("录制时长上限"), parent,+ initial=self.stage.recordLimit,+ ))+ cards += [+ M3U8DecryptionEditCard(+ FluentIcon.VPN, parent.tr("解密密钥"), parent,+ keys=self.stage.decryptionKeys, keyTextFile=self.stage.keyTextFile,+ ),+ M3U8MuxImportEditCard(+ FluentIcon.MUSIC, parent.tr("导入音轨/字幕"), parent,+ initial=self.stage.muxImports,+ ),SelectFolderCard(FluentIcon.DOWNLOAD, parent.tr("下载到"), parent, initial=self.path),]+ return cardsdef applySettings(self, payload):super().applySettings(payload)@@ -110,6 +176,16 @@ class M3U8Task(Task):self.stage.headers = payload["headers"]if "proxies" in payload:self.stage.proxies = payload["proxies"]+ if "selectVideo" in payload:+ self.stage.selectVideo = payload["selectVideo"]+ if "recordLimit" in payload:+ self.stage.recordLimit = payload["recordLimit"]+ if "decryptionKeys" in payload:+ self.stage.decryptionKeys = payload["decryptionKeys"]+ if "keyTextFile" in payload:+ self.stage.keyTextFile = payload["keyTextFile"]+ if "muxImports" in payload:+ self.stage.muxImports = payload["muxImports"]def cleanup(self):super().cleanup()@@ -142,18 +218,36 @@ class M3U8Worker(Worker):f"--thread-count={stage.threadCount}",f"--download-retry-count={stage.retryCount}",f"--http-request-timeout={stage.requestTimeout}",- f"--auto-select={_toBool(stage.autoSelect)}",f"--concurrent-download={_toBool(stage.concurrentDownload)}",f"--append-url-params={_toBool(stage.appendUrlParams)}",f"--binary-merge={_toBool(stage.binaryMerge)}",f"--check-segments-count={_toBool(stage.checkSegmentsCount)}",- "--del-after-done=true",+ f"--del-after-done={_toBool(stage.delAfterDone)}",+ f"--sub-format={stage.subtitleFormat}","--write-meta-json=false","--no-log=true","--no-ansi-color=true","--disable-update-check=true",]+ # 拿全部音轨/字幕时需绕开 auto-select 对其的"仅最佳"——显式选视频(最佳或所选)+全部音字幕+ if stage.selectAllAudioSubtitle:+ args.append(f"--select-video={stage.selectVideo or 'best'}")+ args.append("--select-audio=all")+ args.append("--select-subtitle=all")+ elif stage.selectVideo:+ args.append(f"--select-video={stage.selectVideo}")+ args.append(f"--auto-select={_toBool(stage.autoSelect)}")+ else:+ args.append(f"--auto-select={_toBool(stage.autoSelect)}")++ if stage.maxSpeed > 0:+ args.append(f"--max-speed={stage.maxSpeed}{stage.speedUnit}")+ if stage.adKeyword:+ args.append(f"--ad-keyword={stage.adKeyword}")+ if stage.noDateInfo:+ args.append("--no-date-info=true")+proxyUrl = next((v for v in stage.proxies.values() if v), "")# N_m3u8DL-RE 的 .NET HttpClient 不识别 socks5h scheme,等价转为 socks5if proxyUrl.startswith("socks5h://"):@@ -166,16 +260,43 @@ class M3U8Worker(Worker):if ffmpegPath:args.append(f"--ffmpeg-binary-path={ffmpegPath}")- if stage.liveRealTimeMerge:+ args.append(f"--decryption-engine={_DECRYPTION_ENGINES.get(stage.decryptionEngine, 'FFMPEG')}")+ args.append(f"--mp4-real-time-decryption={_toBool(stage.mp4RealTimeDecryption)}")+ if stage.decryptionBinaryPath:+ args.append(f"--decryption-binary-path={toPosixPath(Path(stage.decryptionBinaryPath))}")+ for key in stage.decryptionKeys:+ text = key.strip()+ if text:+ args.append(f"--key={text}")+ if stage.keyTextFile:+ args.append(f"--key-text-file={toPosixPath(Path(stage.keyTextFile))}")++ if stage.task.isLive:+ # 直播恒开 real-time-merge:硬杀停止时文件已落盘可用args.append("--live-real-time-merge=true")args.append(f"--live-keep-segments={_toBool(stage.liveKeepSegments)}")args.append(f"--live-pipe-mux={_toBool(stage.livePipeMux)}")+ if stage.liveFixVtt:+ args.append("--live-fix-vtt-by-audio=true")+ if stage.liveWaitTime > 0:+ args.append(f"--live-wait-time={stage.liveWaitTime}")+ if stage.liveTakeCount > 0:+ args.append(f"--live-take-count={stage.liveTakeCount}")+ if stage.recordLimit:+ args.append(f"--live-record-limit={stage.recordLimit}")+ elif stage.customMuxAfterDone:+ args.append(f"--mux-after-done={stage.customMuxAfterDone}")else:muxOption = f"format={stage.outputFormat}:muxer=ffmpeg"if ffmpegPath:muxOption += f":bin_path={ffmpegPath}"args.append(f"--mux-after-done={muxOption}")+ for imp in stage.muxImports:+ text = imp.strip()+ if text:+ args.append(f"--mux-import={text}")+for name, value in stage.headers.items():text = value.strip()if not text:@@ -203,6 +324,9 @@ class M3U8Worker(Worker):liveMatch = _LIVE_PROGRESS_PATTERN.search(text)if liveMatch:+ self.stage.liveElapsed = liveMatch.group(1)+ self.stage.liveTotal = liveMatch.group(2)+ self.stage.liveStatus = liveMatch.group(3)self.stage.progress = float(liveMatch.group(4))self.stage.speed = 0 if liveMatch.group(5) == "-" else toBytes(liveMatch.group(6), liveMatch.group(7))@@ -224,6 +348,8 @@ class M3U8Worker(Worker):self._parseOutputLine(buffer)def _updateOutput(self):+ # 进程已结束, 占位旁标去重使命完成——清掉(暂停/失败不走这里, 旁标留作并发去重)+ Path(f"{self.stage.outputFile}.ghd").unlink(missing_ok=True)target = Path(self.stage.outputFile)if target.is_file() and target.stat().st_size > 0:self.stage.actualExtension = target.suffix.lstrip(".")@@ -235,7 +361,7 @@ class M3U8Worker(Worker):if not outputDir.is_dir():return- fallbackExtension = "ts" if self.stage.liveRealTimeMerge else self.stage.outputFormat+ fallbackExtension = "ts" if self.stage.task.isLive else self.stage.outputFormatexpectedSuffix = f".{self.stage.actualExtension or fallbackExtension}"prefix = self.stage.saveName.lower()@@ -268,8 +394,13 @@ class M3U8Worker(Worker):self.stage.task.path.mkdir(parents=True, exist_ok=True)Path(self.stage.tempDir).mkdir(parents=True, exist_ok=True)- # 占位以便后续同名任务被 deduplicateFilename 检测到——_updateOutput 会清掉这个 0 字节文件- Path(self.stage.outputFile).touch(exist_ok=True)+ # 用 .ghd 旁标占位, 让后续同名任务被 deduplicateFilename 检测到; 不占用产物名,+ # 否则 N_m3u8DL-RE 发现同名已存在会把产物写成 <name>.copy.<ext>+ Path(f"{self.stage.outputFile}.ghd").touch(exist_ok=True)++ env = None+ if self.stage.keepImageSegments:+ env = {**os.environ, "RE_KEEP_IMAGE_SEGMENTS": "1"}process = NonesupervisorTask = None@@ -279,6 +410,7 @@ class M3U8Worker(Worker):execPath,*args,cwd=Path(execPath).parent,+ env=env,stdin=asyncio.subprocess.DEVNULL,stdout=asyncio.subprocess.PIPE,stderr=asyncio.subprocess.STDOUT,@@ -295,7 +427,6 @@ class M3U8Worker(Worker):self._updateOutput()self.stage.setStatus(TaskStatus.COMPLETED)except asyncio.CancelledError:- self.stage.setStatus(TaskStatus.PAUSED)if process is not None and process.returncode is None:process.terminate()try:@@ -307,6 +438,12 @@ class M3U8Worker(Worker):supervisorTask.cancel()with suppress(asyncio.CancelledError):await supervisorTask+ if self.stage.task.isLive:+ # 直播无暂停语义:硬杀后 real-time-merge 的文件已落盘,收尾标完成+ self._updateOutput()+ self.stage.setStatus(TaskStatus.COMPLETED)+ else:+ self.stage.setStatus(TaskStatus.PAUSED)raiseexcept Exception as e:self.stage.setError(e)diff --git a/pyproject.toml b/pyproject.tomlindex 13b2143e..fbf40060 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -17,6 +17,8 @@ dependencies = ["pyobjc-framework-Cocoa>=10.0; sys_platform == 'darwin'","aioftp[socks]>=0.27.2","pyside6-fluent-widgets>=1.11.1",+ "m3u8>=6.0.0",+ "mpegdash>=0.4.1",][dependency-groups]diff --git a/requirements.txt b/requirements.txtindex 9b911f2d..6a9c6416 100644--- a/requirements.txt+++ b/requirements.txt@@ -10,4 +10,6 @@ libtorrent-windows-dll>=0.0.3; sys_platform == 'win32'winloop>=0.6.0; sys_platform == 'win32'uvloop>=0.22.1; sys_platform != 'win32'pyobjc-framework-Cocoa>=10.0; sys_platform == 'darwin'-aioftp[socks]>=0.27.2\ No newline at end of file+aioftp[socks]>=0.27.2+m3u8>=6.0.0+mpegdash>=0.4.1\ No newline at end of file