Skip to content

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

feat(Bilibili): 支持下载弹幕 #1018

XiaoYouChR1d09da9c3fb3
diff --git a/GLOSSARY.md b/GLOSSARY.md
index f7724798..1b86a8de 100644
--- a/GLOSSARY.md
+++ b/GLOSSARY.md
@@ -41,7 +41,7 @@ Task 加入时、Default Folder 被改为某文件夹时记入。
_Avoid_: 历史路径、memory folders
**Side File**:
-随成品一起产出、以成品 Name 为前缀的附属文件——字幕、封面、种子文件。
+随成品一起产出、以成品 Name 为前缀的附属文件——字幕、弹幕、封面、种子文件。
_Avoid_: side product、sidecar;与 Selectable File 混淆
**Part Path**:
diff --git a/features/bili_pack/android.py b/features/bili_pack/android.py
index ad5fe53d..56d3276b 100644
--- a/features/bili_pack/android.py
+++ b/features/bili_pack/android.py
@@ -64,7 +64,7 @@ def init(pack: BilibiliPack) -> dict[str, Signal]:
def taskFields(task: BilibiliTask) -> dict[str, str | bool]:
return {
"fileSelectKind": "videos" if task.hasManyVideos else "pages",
- "canSelectFiles": task.isVideoEnabled or task.isAudioEnabled,
+ "canSelectFiles": task.canSelectFiles,
}
@@ -101,12 +101,24 @@ def toDraftOptions(pairs: list[tuple[str, str]]) -> list[dict[str, str]]:
return [{"key": key, "label": label} for key, label in pairs]
+def activeTracks(task: BilibiliTask) -> set[str]:
+ return {
+ name for name, on in (
+ ("video", task.isVideoEnabled),
+ ("audio", task.isAudioEnabled),
+ ("danmaku", bool(task.danmakuFormat)),
+ ("cover", task.isCoverEnabled),
+ ) if on
+ }
+
+
def draftFields(task: BilibiliTask) -> dict[str, Any]:
from .task import (
- audioTiers, currentAudioTier, currentVideoTier, subtitleChoices, videoTiers,
+ DANMAKU_OPTIONS, audioTiers, currentAudioTier, currentVideoTier, subtitleChoices, videoTiers,
)
- page = task.files[0] if task.files and len(task.files) == 1 else None
+ tracks = activeTracks(task)
+ page = task.files[0] if task.canSelectFiles and task.files and len(task.files) == 1 else None
return {
"controls": [
{
@@ -114,19 +126,26 @@ def draftFields(task: BilibiliTask) -> dict[str, Any]:
"title": "视频",
"value": currentVideoTier(task) if task.isVideoEnabled else "",
"options": toDraftOptions(videoTiers(task)),
- "isOptional": task.isAudioEnabled,
+ "isOptional": bool(tracks - {"video"}),
},
{
"id": "audio",
"title": "音频",
"value": currentAudioTier(task) if task.isAudioEnabled else "",
"options": toDraftOptions(audioTiers(task)),
- "isOptional": task.isVideoEnabled,
+ "isOptional": bool(tracks - {"audio"}),
+ },
+ {
+ "id": "danmaku",
+ "title": "弹幕",
+ "value": task.danmakuFormat,
+ "options": toDraftOptions(DANMAKU_OPTIONS),
+ "isOptional": bool(tracks - {"danmaku"}),
},
],
"isCoverEnabled": task.isCoverEnabled,
"hasCover": bool(task.coverUrl),
- "subtitles": toDraftOptions(subtitleChoices(task)),
+ "subtitles": toDraftOptions(subtitleChoices(task)) if task.hasMedia else [],
"subtitleLanguages": list(task.subtitleLanguages),
"duration": page._duration if page else 0,
"startTime": page.startTime if page else 0,
@@ -136,18 +155,25 @@ def draftFields(task: BilibiliTask) -> dict[str, Any]:
def setControl(task: BilibiliTask, controlId: str, value: str) -> None:
+ if controlId not in {"video", "audio", "danmaku", "cover"}:
+ raise ValueError(f"Unknown control: {controlId}")
+ if not value and not (activeTracks(task) - {controlId}):
+ return
if controlId == "video":
task.isVideoEnabled = bool(value)
if value:
task.setVideoQuality(*map(int, value.split("-")))
+ return
elif controlId == "audio":
task.isAudioEnabled = bool(value)
if value:
task.setAudioQuality(int(value))
+ return
+ elif controlId == "danmaku":
+ task.setDanmakuFormat(value)
+ return
elif controlId == "cover":
task.isCoverEnabled = bool(value)
- else:
- raise ValueError(f"Unknown control: {controlId}")
task.update()
diff --git a/features/bili_pack/cards.py b/features/bili_pack/cards.py
index 644dd673..c57690be 100644
--- a/features/bili_pack/cards.py
+++ b/features/bili_pack/cards.py
@@ -17,11 +17,11 @@ from app.models.task import TaskStatus
from app.view.cards.draft_cards import MultiFileDraftCard
from app.view.cards.task_cards import MultiFileTaskCard
from app.view.components.range_slider import RangeSlider
-from app.view.components.track_bar import TrackBar, TrackButton
+from app.view.components.track_bar import MenuTrackButton, TrackBar, TrackButton
from app.view.components.tree_view import AutoSizingTreeView
from app.view.dialogs.subtitle_select import SubtitleSelectDialog
from .task import (
- BiliPage, BilibiliTask, audioTiers, currentAudioTier, currentVideoTier,
+ BiliPage, BilibiliTask, DANMAKU_OPTIONS, audioTiers, currentAudioTier, currentVideoTier,
setEpisodeTitle, setPagePart, setTimeRanges, subtitleChoices, videoTiers,
)
@@ -466,6 +466,13 @@ class BilibiliDraftCard(MultiFileDraftCard):
self._trackBar.subtitleButton.setTrackEnabled(bool(self._subtitleChoices))
self._trackBar.coverButton.setTrackEnabled(bool(self._task.coverUrl))
+ self._danmakuButton = MenuTrackButton(FluentIcon.CHAT, self._trackBar)
+ self._danmakuButton.setToolTip(self.tr("弹幕"))
+ self._danmakuButton.setChecked(bool(task.danmakuFormat))
+ self._danmakuButton.setOptions(DANMAKU_OPTIONS, selected=task.danmakuFormat or None)
+ barLayout = self._trackBar.layout()
+ barLayout.insertWidget(barLayout.indexOf(self._trackBar.coverButton), self._danmakuButton)
+
self._trimButton = TrackButton(FluentIcon.CUT, self)
self._trimButton.setToolTip(self.tr("截取片段"))
self._trimButton.setChecked(False)
@@ -498,10 +505,19 @@ class BilibiliDraftCard(MultiFileDraftCard):
def _bind(self) -> None:
super()._bind()
+ for button in (
+ self._trackBar.videoButton,
+ self._trackBar.audioButton,
+ self._trackBar.subtitleButton,
+ self._trackBar.coverButton,
+ ):
+ button.toggled.disconnect(self._trackBar._preventAllOff)
self._trackBar.videoButton.optionPicked.connect(self._onVideoQualityPicked)
self._trackBar.videoButton.toggled.connect(self._onTrackToggled)
self._trackBar.audioButton.optionPicked.connect(self._onAudioQualityPicked)
self._trackBar.audioButton.toggled.connect(self._onTrackToggled)
+ self._danmakuButton.optionPicked.connect(self._onTrackToggled)
+ self._danmakuButton.toggled.connect(self._onTrackToggled)
self._trackBar.subtitleButton.clicked.connect(self._onSubtitleClicked)
self._trackBar.coverButton.clicked.connect(
lambda: self._trackBar.coverButton.setChecked(not self._trackBar.coverButton.isChecked())
@@ -523,22 +539,38 @@ class BilibiliDraftCard(MultiFileDraftCard):
self._isSizeEstimated = True
self._refreshSummary()
- def _onTrackToggled(self) -> None:
+ def _onTrackToggled(self, checked: object = True) -> None:
+ primary = (
+ self._trackBar.videoButton,
+ self._trackBar.audioButton,
+ self._danmakuButton,
+ self._trackBar.coverButton,
+ )
+ if checked is False and not any(b.isChecked() for b in primary):
+ sender = self.sender()
+ if isinstance(sender, TrackButton) and sender.isEnabled():
+ sender.setChecked(True)
+ return
+
task: BilibiliTask = self._task
isVideo = self._trackBar.videoButton.isChecked()
isAudio = self._trackBar.audioButton.isChecked()
isCover = self._trackBar.coverButton.isChecked()
+ danmaku = (self._danmakuButton.selectedValue() or "ass") if self._danmakuButton.isChecked() else ""
changed = (task.isVideoEnabled != isVideo
or task.isAudioEnabled != isAudio
- or task.isCoverEnabled != isCover)
+ or task.isCoverEnabled != isCover
+ or task.danmakuFormat != danmaku)
if changed:
task.isVideoEnabled = isVideo
task.isAudioEnabled = isAudio
task.isCoverEnabled = isCover
+ task.danmakuFormat = danmaku
task.update()
- self._refreshSummary()
self._refreshButtonVisibility()
+ self._refreshSummary()
+ self._refreshConflictIcon()
def _onTrimToggled(self) -> None:
checked = not self._trimButton.isChecked()
@@ -704,10 +736,14 @@ class BilibiliDraftCard(MultiFileDraftCard):
self._refreshFileIcon()
def _refreshButtonVisibility(self) -> None:
- hasMedia = self._task.isVideoEnabled or self._task.isAudioEnabled
+ files = self._task.files or []
if self._selectFilesButton is not None:
- self._selectFilesButton.setVisible(hasMedia and len(self._task.files or []) > 1)
- subtitleEnabled = hasMedia and bool(self._subtitleChoices)
+ self._selectFilesButton.setVisible(self._task.canSelectFiles and len(files) > 1)
+ canTrim = self._task.canSelectFiles and len(files) == 1 and files[0]._duration > 0
+ self._trimButton.setVisible(canTrim)
+ if not canTrim and self._trimButton.isChecked():
+ self._onTrimToggled()
+ subtitleEnabled = self._task.hasMedia and bool(self._subtitleChoices)
self._trackBar.subtitleButton.setTrackEnabled(subtitleEnabled)
if subtitleEnabled:
self._trackBar.subtitleButton.setChecked(bool(self._task.subtitleLanguages))
diff --git a/features/bili_pack/config.py b/features/bili_pack/config.py
index 69c7bf9c..da062071 100644
--- a/features/bili_pack/config.py
+++ b/features/bili_pack/config.py
@@ -28,6 +28,9 @@ class BilibiliConfig(PackConfig):
defaultAudioQuality = OptionsConfigItem(
"Bilibili", "DefaultAudioQuality", 30280, OptionsValidator(AUDIO_QUALITY_VALUES),
)
+ defaultDanmaku = OptionsConfigItem(
+ "Bilibili", "DefaultDanmaku", "none", OptionsValidator(["none", "ass", "xml"]),
+ )
alternativeQuality = OptionsConfigItem(
"Bilibili", "AlternativeQuality", "max", OptionsValidator(["max", "min"]),
)
@@ -46,6 +49,9 @@ class BilibiliConfig(PackConfig):
ComboBoxSettingCard(self.defaultAudioQuality, FluentIcon.MUSIC, self.tr("默认音质"),
self.tr("选择偏好的音质"),
texts=AUDIO_QUALITY_LABELS, parent=group),
+ ComboBoxSettingCard(self.defaultDanmaku, FluentIcon.CHAT, self.tr("默认弹幕"),
+ self.tr("选择默认下载的弹幕格式"),
+ texts=[self.tr("不下载"), "ASS", "XML"], parent=group),
ComboBoxSettingCard(self.alternativeQuality, FluentIcon.SPEED_HIGH, self.tr("画质或音质不可用时"),
self.tr("当选择的画质或音质不可用时的替代策略"),
texts=[self.tr("选择最高"), self.tr("选择最低")],
diff --git a/features/bili_pack/danmaku.py b/features/bili_pack/danmaku.py
new file mode 100644
index 00000000..fd4facab
--- /dev/null
+++ b/features/bili_pack/danmaku.py
@@ -0,0 +1,462 @@
+from __future__ import annotations
+
+import asyncio
+import html
+import math
+import re
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Sequence
+from dataclasses import dataclass, replace
+from typing import TYPE_CHECKING, Any
+
+from app.client import buildClient
+from app.models.task import TaskError
+
+if TYPE_CHECKING:
+ import wreq
+
+DANMAKU_SEG_API = "https://api.bilibili.com/x/v2/dm/wbi/web/seg.so"
+SEGMENT_SECONDS = 360
+MAX_CONCURRENCY = 3
+MAX_PROBE_SEGMENTS = 200
+SCROLL_DURATION = 12.0
+FIXED_DURATION = 5.0
+BASE_FONT_SIZE = 38
+TRACK_SLOT_HEIGHT = 44
+TRACK_MARGIN_Y = 10
+XML_INVALID_RE = re.compile(r"[\x00-\x08\x0b\x0c\x0e-\x1f]")
+ASS_CONTROL_RE = re.compile(r"[\x00-\x09\x0b-\x1f]")
+
+
+@dataclass(frozen=True, slots=True)
+class DanmakuItem:
+ id: int
+ progressMs: int
+ mode: int = 1
+ fontsize: int = 25
+ color: int = 0xFFFFFF
+ midHash: str = ""
+ content: str = ""
+ ctime: int = 0
+ weight: int = 0
+ pool: int = 0
+ idStr: str = ""
+
+
+def parseVarint(buf: bytes, pos: int) -> tuple[int, int]:
+ value = 0
+ shift = 0
+ length = len(buf)
+ while pos < length:
+ byte = buf[pos]
+ pos += 1
+ value |= (byte & 0x7F) << shift
+ if not (byte & 0x80):
+ return value, pos
+ shift += 7
+ if shift > 63:
+ raise ValueError("varint 长度超出 64 位上限")
+ raise ValueError("varint 数据被截断")
+
+
+def parseFields(buf: bytes) -> Iterator[tuple[int, int | bytes]]:
+ pos = 0
+ length = len(buf)
+ try:
+ while pos < length:
+ tag, pos = parseVarint(buf, pos)
+ fieldNum = tag >> 3
+ wireType = tag & 7
+ if wireType == 0:
+ val, pos = parseVarint(buf, pos)
+ yield fieldNum, val
+ elif wireType == 2:
+ size, pos = parseVarint(buf, pos)
+ end = pos + size
+ if end > length:
+ return
+ yield fieldNum, buf[pos:end]
+ pos = end
+ elif wireType in {1, 5}:
+ end = pos + (8 if wireType == 1 else 4)
+ if end > length:
+ return
+ pos = end
+ else:
+ return
+ except ValueError:
+ return
+
+
+def parseElem(buf: bytes) -> DanmakuItem | None:
+ ints: dict[int, int] = {}
+ strs: dict[int, str] = {}
+ for fieldNum, value in parseFields(buf):
+ if isinstance(value, int):
+ ints[fieldNum] = value
+ elif fieldNum in {6, 7, 12}:
+ strs[fieldNum] = value.decode("utf-8", errors="replace")
+
+ content = strs.get(7, "")
+ if not content:
+ return None
+
+ rawProgress = ints.get(2, 0) & 0xFFFFFFFF
+ progressMs = rawProgress - 0x100000000 if rawProgress >= 0x80000000 else rawProgress
+ elemId = ints.get(1, 0)
+ return DanmakuItem(
+ id=elemId,
+ progressMs=max(0, progressMs),
+ mode=ints.get(3) or 1,
+ fontsize=ints.get(4) or 25,
+ # proto3 会省略默认标量 0,黑色 #000000 不会出现在线缆上
+ color=ints.get(5, 0),
+ midHash=strs.get(6, ""),
+ content=content,
+ ctime=ints.get(8, 0),
+ weight=ints.get(9, 0),
+ pool=ints.get(11, 0),
+ idStr=strs.get(12) or (str(elemId) if elemId else ""),
+ )
+
+
+def parseSegment(buf: bytes) -> tuple[list[DanmakuItem], bool]:
+ items: list[DanmakuItem] = []
+ isClosed = False
+ for fieldNum, value in parseFields(buf):
+ if fieldNum == 1 and isinstance(value, bytes):
+ item = parseElem(value)
+ if item is not None:
+ items.append(item)
+ elif fieldNum == 2 and value == 1:
+ isClosed = True
+ return items, isClosed
+
+
+async def fetchSegment(
+ client: wreq.Client,
+ *,
+ cid: int,
+ aid: int,
+ segmentIndex: int,
+ signParams: Callable[[dict[str, Any]], dict[str, Any]] | None,
+) -> tuple[list[DanmakuItem], bool, int]:
+ params: dict[str, Any] = {
+ "type": 1,
+ "oid": cid,
+ "segment_index": segmentIndex,
+ }
+ if aid > 0:
+ params["pid"] = aid
+ if signParams is not None:
+ params = signParams(params)
+ url = f"{DANMAKU_SEG_API}?{urllib.parse.urlencode(params)}"
+
+ response = await client.get(url)
+ try:
+ status = response.status.as_int()
+ if status == 412:
+ raise TaskError("Bilibili 拦截了弹幕请求(412 风控),请稍后再试")
+ # 越界分段会直接返回空体 304,属于正常结尾而非异常
+ if status == 304:
+ return [], False, 0
+ response.raise_for_status()
+
+ contentType = bytes(response.headers.get("content-type") or b"").lower()
+ if b"application/json" in contentType:
+ payload = await response.json()
+ if payload.get("code") not in {None, 0}:
+ raise ValueError(payload.get("message") or "获取弹幕失败")
+ return [], False, 0
+
+ raw = bytes(await response.bytes())
+ finally:
+ response.close()
+
+ if not raw:
+ return [], False, 0
+ items, isClosed = parseSegment(raw)
+ return items, isClosed, len(raw)
+
+
+def buildFilteredItems(
+ items: Iterable[DanmakuItem],
+ *,
+ startTime: int = 0,
+ endTime: int = 0,
+) -> list[DanmakuItem]:
+ deduped: list[DanmakuItem] = []
+ seenIds: set[int] = set()
+ startMs = max(0, startTime) * 1000
+ endMs = endTime * 1000
+
+ for item in items:
+ if item.id:
+ if item.id in seenIds:
+ continue
+ seenIds.add(item.id)
+ if item.progressMs < startMs or (endMs > 0 and item.progressMs > endMs):
+ continue
+ if startMs > 0:
+ item = replace(item, progressMs=item.progressMs - startMs)
+ deduped.append(item)
+
+ deduped.sort(key=lambda d: (d.progressMs, d.id))
+ return deduped
+
+
+async def fetchDanmaku(
+ cid: int,
+ *,
+ aid: int = 0,
+ duration: int = 0,
+ startTime: int = 0,
+ endTime: int = 0,
+ headers: dict[str, str] | None = None,
+ signParams: Callable[[dict[str, Any]], dict[str, Any]] | None = None,
+ onProgress: Callable[[int, int, int], None] | None = None,
+) -> list[DanmakuItem]:
+ pageHeaders = headers or {}
+ reqHeaders = {"referer": pageHeaders.get("referer") or pageHeaders.get("Referer") or "https://www.bilibili.com"}
+ cookie = pageHeaders.get("cookie") or pageHeaders.get("Cookie") or ""
+ if cookie:
+ reqHeaders["cookie"] = cookie
+
+ client = buildClient(emulation=None, headers=reqHeaders)
+ try:
+ if signParams is None:
+ from .account import fetchWbiMixinKey, signWbiParams
+ try:
+ mixinKey = await fetchWbiMixinKey()
+ except Exception:
+ mixinKey = ""
+ signParams = (lambda params: signWbiParams(params, mixinKey)) if mixinKey else None
+
+ first = max(0, startTime) // SEGMENT_SECONDS + 1
+ effectiveEnd = endTime if endTime > 0 else duration
+ if effectiveEnd > 0:
+ last = max(first, (effectiveEnd - 1) // SEGMENT_SECONDS + 1)
+ segments = range(first, last + 1)
+ total = len(segments)
+ semaphore = asyncio.Semaphore(MAX_CONCURRENCY)
+ doneCount = 0
+ isClosed = False
+
+ async def fetchOne(segIdx: int) -> list[DanmakuItem]:
+ nonlocal doneCount, isClosed
+ if isClosed:
+ return []
+ async with semaphore:
+ if isClosed:
+ return []
+ items, segClosed, byteCount = await fetchSegment(
+ client,
+ cid=cid,
+ aid=aid,
+ segmentIndex=segIdx,
+ signParams=signParams,
+ )
+ if segClosed:
+ isClosed = True
+ doneCount += 1
+ if onProgress is not None:
+ onProgress(doneCount, total, byteCount)
+ return [] if segClosed else items
+
+ batches = await asyncio.gather(*(fetchOne(idx) for idx in segments))
+ if isClosed:
+ return []
+ rawItems = [item for batch in batches for item in batch]
+ else:
+ rawItems = []
+ for offset in range(MAX_PROBE_SEGMENTS):
+ items, segClosed, byteCount = await fetchSegment(
+ client,
+ cid=cid,
+ aid=aid,
+ segmentIndex=first + offset,
+ signParams=signParams,
+ )
+ if onProgress is not None:
+ onProgress(offset + 1, 0, byteCount)
+ if segClosed:
+ return []
+ if byteCount == 0:
+ break
+ rawItems.extend(items)
+ finally:
+ client.close()
+
+ return buildFilteredItems(rawItems, startTime=startTime, endTime=endTime)
+
+
+def toXmlText(text: str) -> str:
+ return html.escape(XML_INVALID_RE.sub("", text), quote=True)
+
+
+def toXml(items: Sequence[DanmakuItem], *, cid: int) -> str:
+ lines = [
+ '<?xml version="1.0" encoding="UTF-8"?>',
+ "<i>",
+ " <chatserver>chat.bilibili.com</chatserver>",
+ f" <chatid>{cid}</chatid>",
+ " <mission>0</mission>",
+ f" <maxlimit>{max(len(items), 1500)}</maxlimit>",
+ f" <state>{0 if items else 1}</state>",
+ " <real_name>0</real_name>",
+ " <source>k-v</source>",
+ ]
+ for item in items:
+ idText = item.idStr or (str(item.id) if item.id else "0")
+ pAttr = (
+ f"{item.progressMs / 1000:.5f},{item.mode},{item.fontsize},"
+ f"{item.color},{item.ctime},{item.pool},"
+ f"{toXmlText(item.midHash)},{toXmlText(idText)},{item.weight}"
+ )
+ lines.append(f' <d p="{pAttr}">{toXmlText(item.content)}</d>')
+ lines.append("</i>")
+ return "\n".join(lines) + "\n"
+
+
+def toAssTime(ms: int) -> str:
+ totalCs = max(0, ms // 10)
+ cs = totalCs % 100
+ totalSec = totalCs // 100
+ seconds = totalSec % 60
+ minutes = (totalSec // 60) % 60
+ hours = totalSec // 3600
+ return f"{hours}:{minutes:02d}:{seconds:02d}.{cs:02d}"
+
+
+def toAssText(text: str) -> str:
+ cleaned = ASS_CONTROL_RE.sub("", text).replace("\r\n", "\n").replace("\r", "\n")
+ return (
+ cleaned.replace("\\", "\\\\")
+ .replace("{", "\\{")
+ .replace("}", "\\}")
+ .replace("\n", "\\N")
+ )
+
+
+def toTextWidth(text: str, fontPx: int) -> int:
+ maxUnits = 0.0
+ for line in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
+ units = sum(0.55 if ord(ch) < 128 else 1.0 for ch in line)
+ if units > maxUnits:
+ maxUnits = units
+ return max(fontPx, math.ceil(maxUnits * fontPx) + 4)
+
+
+def pickTrack(readyAt: Sequence[float], startSec: float, span: int) -> int:
+ span = max(1, min(span, len(readyAt)))
+ bestSlot = 0
+ bestReady = math.inf
+ for slot in range(len(readyAt) - span + 1):
+ slotReady = max(readyAt[slot:slot + span])
+ if startSec >= slotReady:
+ return slot
+ if slotReady < bestReady:
+ bestReady = slotReady
+ bestSlot = slot
+ return bestSlot
+
+
+def buildStyleOverrides(color: int, fontPx: int) -> str:
+ tags: list[str] = []
+ if fontPx != BASE_FONT_SIZE:
+ tags.append(f"\\fs{fontPx}")
+ rgb = color & 0xFFFFFF
+ if rgb != 0xFFFFFF:
+ r = (rgb >> 16) & 0xFF
+ g = (rgb >> 8) & 0xFF
+ b = rgb & 0xFF
+ tags.append(f"\\c&H{b:02X}{g:02X}{r:02X}&")
+ if 0.299 * r + 0.587 * g + 0.114 * b < 32:
+ tags.append("\\3c&HFFFFFF&")
+ return "".join(tags)
+
+
+def toAss(
+ items: Sequence[DanmakuItem],
+ *,
+ width: int = 1920,
+ height: int = 1080,
+ rotate: int = 0,
+ title: str = "",
+) -> str:
+ if rotate in {1, 3}:
+ width, height = height, width
+ if width <= 0 or height <= 0:
+ playResX, playResY = 1920, 1080
+ elif width >= height:
+ playResX, playResY = max(1, round(width * 1080 / height)), 1080
+ else:
+ playResX, playResY = 1080, max(1, round(height * 1080 / width))
+
+ safeTitle = ASS_CONTROL_RE.sub("", title).replace("\r", " ").replace("\n", " ").strip() or "Danmaku"
+ lines = [
+ "[Script Info]",
+ f"Title: {safeTitle}",
+ "ScriptType: v4.00+",
+ f"PlayResX: {playResX}",
+ f"PlayResY: {playResY}",
+ "WrapStyle: 2",
+ "ScaledBorderAndShadow: yes",
+ "",
+ "[V4+ Styles]",
+ "Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline, Shadow, Alignment, MarginL, MarginR, MarginV, Encoding",
+ f"Style: Danmaku,Microsoft YaHei,{BASE_FONT_SIZE},&H33FFFFFF,&H33FFFFFF,&H33000000,&H33000000,1,0,0,0,100,100,0,0,1,1.5,0,7,0,0,0,1",
+ "",
+ "[Events]",
+ "Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text",
+ ]
+
+ numSlots = max(1, (int(playResY * 0.75) - TRACK_MARGIN_Y) // TRACK_SLOT_HEIGHT)
+ rtlTracks: list[tuple[float, float]] = [(0.0, 0.0)] * numSlots
+ ltrTracks: list[tuple[float, float]] = [(0.0, 0.0)] * numSlots
+ topTracks: list[float] = [0.0] * numSlots
+ bottomTracks: list[float] = [0.0] * numSlots
+
+ for item in items:
+ if item.mode not in {1, 2, 3, 4, 5, 6}:
+ continue
+ fontPx = max(18, round((item.fontsize or 25) * 1.5))
+ span = max(1, min(numSlots, (fontPx + 6 + TRACK_SLOT_HEIGHT - 1) // TRACK_SLOT_HEIGHT))
+ textWidth = toTextWidth(item.content, fontPx)
+ startSec = item.progressMs / 1000.0
+ styleTags = buildStyleOverrides(item.color, fontPx)
+ escapedText = toAssText(item.content)
+
+ if item.mode in {1, 2, 3, 6}:
+ endSec = startSec + SCROLL_DURATION
+ tracks = ltrTracks if item.mode == 6 else rtlTracks
+ leadTime = playResX * SCROLL_DURATION / (playResX + textWidth)
+ readyAt = [max(0.0, tc, end - leadTime) for tc, end in tracks]
+ slot = pickTrack(readyAt, startSec, span)
+ tailClear = startSec + textWidth * SCROLL_DURATION / (playResX + textWidth)
+ tracks[slot:slot + span] = [(tailClear, endSec)] * span
+ y = TRACK_MARGIN_Y + slot * TRACK_SLOT_HEIGHT
+ x1, x2 = (-textWidth, playResX) if item.mode == 6 else (playResX, -textWidth)
+ motionTag = f"\\move({x1},{y},{x2},{y})"
+ layer = 0
+ else:
+ endSec = startSec + FIXED_DURATION
+ fixedTracks = topTracks if item.mode == 5 else bottomTracks
+ slot = pickTrack(fixedTracks, startSec, span)
+ fixedTracks[slot:slot + span] = [endSec] * span
+ if item.mode == 5:
+ y = TRACK_MARGIN_Y + slot * TRACK_SLOT_HEIGHT
+ align = 8
+ else:
+ y = playResY - TRACK_MARGIN_Y - slot * TRACK_SLOT_HEIGHT
+ align = 2
+ motionTag = f"\\an{align}\\pos({playResX // 2},{y})"
+ layer = 1
+
+ startText = toAssTime(item.progressMs)
+ endText = toAssTime(round(endSec * 1000))
+ lines.append(
+ f"Dialogue: {layer},{startText},{endText},Danmaku,,0,0,0,,{{{motionTag}{styleTags}}}{escapedText}"
+ )
+
+ return "\n".join(lines) + "\n"
diff --git a/features/bili_pack/i18n.py b/features/bili_pack/i18n.py
index 8f5ca770..1d3db387 100644
--- a/features/bili_pack/i18n.py
+++ b/features/bili_pack/i18n.py
@@ -11,3 +11,5 @@ N("TaskErrors", "登录失败")
N("TaskErrors", "未获取到视频流地址")
N("TaskErrors", "字幕下载失败")
+N("TaskErrors", "弹幕下载失败")
+N("TaskErrors", "Bilibili 拦截了弹幕请求(412 风控),请稍后再试")
diff --git a/features/bili_pack/pack.py b/features/bili_pack/pack.py
index 3243fee3..29e08f69 100644
--- a/features/bili_pack/pack.py
+++ b/features/bili_pack/pack.py
@@ -84,6 +84,8 @@ class BilibiliParser(TaskParser):
requestedQuality = bilibiliConfig.defaultQuality.value
requestedAudioQuality = bilibiliConfig.defaultAudioQuality.value
+ defaultDanmaku = bilibiliConfig.defaultDanmaku.value
+ danmakuFormat = "" if defaultDanmaku == "none" else defaultDanmaku
baseName = toSafeFilename(title, fallback="bilibili_video")
for page in parsedPages:
page.headers = dict(downloadHeaders)
@@ -129,6 +131,7 @@ class BilibiliParser(TaskParser):
coverUrl=coverUrl,
coverSize=coverSize,
files=parsedPages,
+ danmakuFormat=danmakuFormat,
requestedQn=requestedQuality,
requestedAudioQn=requestedAudioQuality,
_baseName=baseName,
diff --git a/features/bili_pack/parse.py b/features/bili_pack/parse.py
index adbe9a1e..817bcc33 100644
--- a/features/bili_pack/parse.py
+++ b/features/bili_pack/parse.py
@@ -64,7 +64,8 @@ def buildPages(viewData: dict, biliUrl: BiliUrl) -> tuple[list[BiliPage], str, s
title = str(viewData.get("title", "")).strip() or "bilibili_video"
coverUrl = toHttps(viewData.get("pic") or "")
bvid = str(viewData.get("bvid") or biliUrl.videoId)
- pages = [buildPage(index, raw, bvid=bvid) for index, raw in enumerate(viewData.get("pages") or [])]
+ aid = int(viewData.get("aid") or 0)
+ pages = [buildPage(index, raw, bvid=bvid, aid=aid) for index, raw in enumerate(viewData.get("pages") or [])]
setVideoSelection(pages, biliUrl.selectedPages)
return pages, title, coverUrl
@@ -80,6 +81,7 @@ def buildFavoritePages(medias: list[dict], pageLists: dict[str, list[dict]]) ->
if not matchFavoriteVideo(media):
continue
bvid = str(media["bvid"])
+ aid = int(media.get("id") or 0)
title = str(media.get("title") or "").strip()
rawPages = pageLists.get(bvid) or [{
"cid": (media.get("ugc") or {})["first_cid"],
@@ -89,7 +91,7 @@ def buildFavoritePages(medias: list[dict], pageLists: dict[str, list[dict]]) ->
}]
coverUrl = toHttps(media.get("cover") or "")
for raw in rawPages:
- pages.append(buildPage(len(pages), raw, bvid=bvid, episodeTitle=title, coverUrl=coverUrl))
+ pages.append(buildPage(len(pages), raw, bvid=bvid, aid=aid, episodeTitle=title, coverUrl=coverUrl))
return pages
@@ -108,6 +110,7 @@ def buildSeasonPages(season: dict) -> list[BiliPage]:
sectionTitle = str(section.get("title") or "").strip() if hasManySections else ""
for episode in section.get("episodes") or []:
bvid = str(episode.get("bvid") or "")
+ aid = int(episode.get("aid") or 0)
episodeTitle = str(episode.get("title") or "").strip()
rawPages = list(episode.get("pages") or [])
if not rawPages and episode.get("page"):
@@ -115,7 +118,7 @@ def buildSeasonPages(season: dict) -> list[BiliPage]:
coverUrl = episodeCover(episode)
for raw in rawPages:
pages.append(buildPage(
- len(pages), raw, bvid=bvid,
+ len(pages), raw, bvid=bvid, aid=aid,
episodeTitle=episodeTitle, sectionTitle=sectionTitle,
coverUrl=coverUrl,
))
@@ -151,20 +154,25 @@ def episodeCover(episode: dict) -> str:
def buildPage(
- index: int, raw: dict, *, bvid: str, episodeTitle: str = "",
+ index: int, raw: dict, *, bvid: str, aid: int = 0, episodeTitle: str = "",
sectionTitle: str = "", coverUrl: str = "",
) -> BiliPage:
pageNumber = int(raw.get("page") or index + 1)
+ dimension = raw.get("dimension") or {}
return BiliPage(
index=index,
relativePath="",
cid=int(raw["cid"]),
+ aid=aid,
pagePart=str(raw.get("part", "")).strip(),
pageNumber=pageNumber,
bvid=bvid,
episodeTitle=episodeTitle,
sectionTitle=sectionTitle,
coverUrl=coverUrl,
+ width=int(dimension.get("width") or 0),
+ height=int(dimension.get("height") or 0),
+ rotate=int(dimension.get("rotate") or 0),
_duration=int(raw.get("duration") or 0),
)
diff --git a/features/bili_pack/task.py b/features/bili_pack/task.py
index 27296d58..cf5abbd2 100644
--- a/features/bili_pack/task.py
+++ b/features/bili_pack/task.py
@@ -16,6 +16,7 @@ from .config import AUDIO_QUALITY_LABELS, AUDIO_QUALITY_VALUES
from .stream import buildSize, fetchPlayurl, probeSize, toStreamUrl
CODEC_NAMES = {7: "H.264", 12: "H.265", 13: "AV1"}
+DANMAKU_OPTIONS: list[tuple[str, str]] = [("ass", "ASS"), ("xml", "XML")]
def streamPage(task: BilibiliTask) -> BiliPage | None:
@@ -140,12 +141,16 @@ def setFileName(task: BilibiliTask, index: int, name: str) -> None:
@dataclass(kw_only=True)
class BiliPage(TaskFile):
cid: int = 0
+ aid: int = 0
pagePart: str = ""
pageNumber: int = 1
bvid: str = ""
episodeTitle: str = ""
sectionTitle: str = ""
coverUrl: str = ""
+ width: int = 0
+ height: int = 0
+ rotate: int = 0
videoUrl: str = ""
audioUrl: str = ""
videoSize: int = 0
@@ -172,6 +177,7 @@ class BilibiliTask(Task):
isAudioEnabled: bool = True
isCoverEnabled: bool = False
subtitleLanguages: list[str] = field(default_factory=list)
+ danmakuFormat: str = ""
requestedQn: int = 0
requestedCodecid: int = 0
requestedAudioQn: int = 0
@@ -181,7 +187,7 @@ class BilibiliTask(Task):
def __post_init__(self) -> None:
super().__post_init__()
- if any(not f.relativePath.endswith((".mp4", ".m4a")) for f in self.files or []):
+ if any(not f.relativePath.endswith((".mp4", ".m4a", ".ass", ".xml")) for f in self.files or []):
self._baseName = self._baseName or Path(self.name).stem
if self.status == TaskStatus.COMPLETED:
self.updateNames()
@@ -214,6 +220,14 @@ class BilibiliTask(Task):
def hasAudio(self) -> bool:
return any(f.audioUrl or f._audioStreams for f in self.files or [])
+ @property
+ def hasMedia(self) -> bool:
+ return self.isVideoEnabled or self.isAudioEnabled
+
+ @property
+ def canSelectFiles(self) -> bool:
+ return self.hasMedia or bool(self.danmakuFormat)
+
def videoCounts(self) -> tuple[int, int]:
groups = self.videoGroups()
selected = sum(1 for g in groups if any(p.selected for p in g))
@@ -237,7 +251,14 @@ class BilibiliTask(Task):
return toSafeFilename(file.episodeTitle if isEpisode else file.pagePart, fallback=f"P{file.pageNumber}")
def updateNames(self) -> None:
- extension = "mp4" if self.isVideoEnabled else "m4a"
+ if self.isVideoEnabled:
+ extension = "mp4"
+ elif self.isAudioEnabled:
+ extension = "m4a"
+ elif self.danmakuFormat:
+ extension = self.danmakuFormat
+ else:
+ extension = "m4a"
for page in self.files or []:
stem = f"{Path(self.name).stem}{self._pageSuffix(page)}"
page.relativePath = toSafeFilename(f"{stem}.{extension}", fallback=f"P{page.pageNumber}.{extension}")
@@ -245,6 +266,7 @@ class BilibiliTask(Task):
def setName(self, name: str) -> None:
super().setName(name)
self._baseName = Path(self.name).stem
+ self.updateNames()
def setVideoQuality(self, qn: int, codecid: int) -> None:
self.requestedQn = qn
@@ -283,6 +305,10 @@ class BilibiliTask(Task):
self.subtitleLanguages = languages
self.update()
+ def setDanmakuFormat(self, fmt: str) -> None:
+ self.danmakuFormat = fmt if fmt in {"ass", "xml"} else ""
+ self.update()
+
def update(self) -> None:
self.steps.clear()
files: list[BiliPage] = self.files or []
@@ -295,6 +321,11 @@ class BilibiliTask(Task):
self.name = toSafeFilename(f"{self._baseName}{timeSuffix}.mp4", fallback="video.mp4")
elif self.isAudioEnabled:
self.name = toSafeFilename(f"{self._baseName}{timeSuffix}.m4a", fallback="audio.m4a")
+ elif self.danmakuFormat:
+ self.name = toSafeFilename(
+ f"{self._baseName}{timeSuffix}.{self.danmakuFormat}",
+ fallback=f"danmaku.{self.danmakuFormat}",
+ )
elif self.isCoverEnabled:
self.name = toSafeFilename(f"{self._baseName}.jpg", fallback="cover.jpg")
else:
@@ -389,7 +420,7 @@ class BilibiliTask(Task):
fileIndex=file.index,
))
self.steps[-1]._bindTask(self)
- if self.isVideoEnabled or self.isAudioEnabled:
+ if self.hasMedia:
for language in self.subtitleLanguages:
stepIndex += 1
self.steps.append(BilibiliSubtitleStep(
@@ -398,6 +429,14 @@ class BilibiliTask(Task):
language=language,
))
self.steps[-1]._bindTask(self)
+ if self.danmakuFormat:
+ stepIndex += 1
+ self.steps.append(BilibiliDanmakuStep(
+ stepIndex=stepIndex,
+ fileIndex=file.index,
+ format=self.danmakuFormat,
+ ))
+ self.steps[-1]._bindTask(self)
return stepIndex
def _pageSuffix(self, page: BiliPage) -> str:
@@ -653,3 +692,76 @@ class BilibiliSubtitleStep(TaskStep):
lines.append("")
if seq:
Path(self.outputPath).write_text("\n".join(lines), encoding="utf-8")
+
+
+@dataclass(kw_only=True)
+class BilibiliDanmakuStep(TaskStep):
+ _task: BilibiliTask = field(repr=False, init=False)
+ canPause = False
+ fileIndex: int = 0
+ format: str = "ass"
+
+ @property
+ def task(self) -> BilibiliTask:
+ return self._task
+
+ @property
+ def outputPath(self) -> str:
+ return str(self.task.toSidePath(self.fileIndex, self.format))
+
+ async def run(
+ self,
+ reportSpeed: Callable[[int], None],
+ waitForSpeedLimit: Callable[[int], Awaitable[None]],
+ ) -> None:
+ from .danmaku import fetchDanmaku, toAss, toXml
+
+ page = pageByIndex(self.task, self.fileIndex)
+ if page is None or not page.cid:
+ if self.task.hasMedia:
+ deletePlaceholder(Path(self.outputPath))
+ return
+ raise TaskError("弹幕下载失败")
+
+ self.receivedBytes = 0
+
+ def onProgress(done: int, total: int, byteCount: int) -> None:
+ if byteCount > 0:
+ self.receivedBytes += byteCount
+ reportSpeed(byteCount)
+ if total > 0:
+ self.progress = done / total * 100
+
+ try:
+ items = await fetchDanmaku(
+ page.cid,
+ aid=page.aid,
+ duration=page._duration,
+ startTime=page.startTime,
+ endTime=page.endTime,
+ headers=page.headers,
+ onProgress=onProgress,
+ )
+ except TaskError:
+ raise
+ except Exception as e:
+ raise TaskError("弹幕下载失败") from e
+
+ # 仅在作为 Side File 伴随下载时清理空占位符,避免独立下载完成后立刻变成 Missing
+ if not items and self.task.hasMedia:
+ deletePlaceholder(Path(self.outputPath))
+ return
+
+ outputPath = Path(self.outputPath)
+ outputPath.parent.mkdir(parents=True, exist_ok=True)
+ if self.format == "xml":
+ text = toXml(items, cid=page.cid)
+ else:
+ text = toAss(
+ items,
+ width=page.width,
+ height=page.height,
+ rotate=page.rotate,
+ title=outputPath.stem,
+ )
+ outputPath.write_text(text, encoding="utf-8")
diff --git a/tests/bili_pack/test_danmaku.py b/tests/bili_pack/test_danmaku.py
new file mode 100644
index 00000000..a25d6d4e
--- /dev/null
+++ b/tests/bili_pack/test_danmaku.py
@@ -0,0 +1,300 @@
+from __future__ import annotations
+
+import json
+import xml.etree.ElementTree as ET
+
+import pytest
+from aiohttp import web
+
+import bili_pack.danmaku as danmaku
+from app.models.task import TaskError
+from bili_pack.danmaku import (
+ DanmakuItem,
+ fetchDanmaku,
+ parseSegment,
+ toAss,
+ toXml,
+)
+
+
+def encodeVarint(value: int) -> bytes:
+ if value < 0:
+ value &= 0xFFFFFFFFFFFFFFFF
+ out = bytearray()
+ while True:
+ byte = value & 0x7F
+ value >>= 7
+ if value:
+ out.append(byte | 0x80)
+ else:
+ out.append(byte)
+ break
+ return bytes(out)
+
+
+def encodeVarintField(fieldNum: int, value: int) -> bytes:
+ return encodeVarint((fieldNum << 3) | 0) + encodeVarint(value)
+
+
+def encodeBytesField(fieldNum: int, data: bytes) -> bytes:
+ return encodeVarint((fieldNum << 3) | 2) + encodeVarint(len(data)) + data
+
+
+def encodeElem(
+ *,
+ elemId: int = 0,
+ progressMs: int = 0,
+ mode: int = 1,
+ fontsize: int = 25,
+ color: int = 0xFFFFFF,
+ midHash: str = "",
+ content: str = "",
+ ctime: int = 0,
+ weight: int = 0,
+ pool: int = 0,
+ idStr: str = "",
+) -> bytes:
+ buf = bytearray()
+ if elemId:
+ buf.extend(encodeVarintField(1, elemId))
+ if progressMs:
+ buf.extend(encodeVarintField(2, progressMs))
+ if mode:
+ buf.extend(encodeVarintField(3, mode))
+ if fontsize:
+ buf.extend(encodeVarintField(4, fontsize))
+ if color:
+ buf.extend(encodeVarintField(5, color))
+ if midHash:
+ buf.extend(encodeBytesField(6, midHash.encode("utf-8")))
+ if content:
+ buf.extend(encodeBytesField(7, content.encode("utf-8")))
+ if ctime:
+ buf.extend(encodeVarintField(8, ctime))
+ if weight:
+ buf.extend(encodeVarintField(9, weight))
+ if pool:
+ buf.extend(encodeVarintField(11, pool))
+ if idStr:
+ buf.extend(encodeBytesField(12, idStr.encode("utf-8")))
+ return bytes(buf)
+
+
+def encodeSegment(elems: list[bytes], *, state: int = 0) -> bytes:
+ buf = bytearray()
+ for elem in elems:
+ buf.extend(encodeBytesField(1, elem))
+ if state:
+ buf.extend(encodeVarintField(2, state))
+ return bytes(buf)
+
+
+def test_parse_segment_decodes_fields_and_black_default():
+ raw = encodeSegment([
+ encodeElem(
+ elemId=101,
+ progressMs=12345,
+ mode=5,
+ fontsize=36,
+ color=0,
+ midHash="abcd1234",
+ content="黑色顶部弹幕",
+ ctime=1700000000,
+ weight=7,
+ pool=1,
+ idStr="101",
+ ),
+ encodeElem(
+ elemId=102,
+ progressMs=-500,
+ color=0xFFFFFF,
+ content="负时间白色",
+ ),
+ encodeElem(elemId=103, progressMs=100, content=""),
+ ])
+
+ items, isClosed = parseSegment(raw)
+
+ assert isClosed is False
+ assert len(items) == 2
+ assert items[0] == DanmakuItem(
+ id=101,
+ progressMs=12345,
+ mode=5,
+ fontsize=36,
+ color=0,
+ midHash="abcd1234",
+ content="黑色顶部弹幕",
+ ctime=1700000000,
+ weight=7,
+ pool=1,
+ idStr="101",
+ )
+ assert items[1].progressMs == 0
+ assert items[1].color == 0xFFFFFF
+ assert items[1].idStr == "102"
+
+
+def test_parse_segment_handles_closed_and_truncated_bytes():
+ closedRaw = encodeSegment([encodeElem(elemId=1, content="hello")], state=1)
+ items, isClosed = parseSegment(closedRaw)
+ assert isClosed is True
+ assert len(items) == 1
+
+ valid = encodeSegment([encodeElem(elemId=2, progressMs=1000, content="完整")])
+ truncated = valid + encodeBytesField(1, encodeElem(elemId=3, content="截断"))[:-3]
+ parsed, closedFlag = parseSegment(truncated)
+ assert closedFlag is False
+ assert [x.content for x in parsed] == ["完整"]
+
+
+async def test_fetch_danmaku_dedupes_trims_and_skips_304(startServer, monkeypatch):
+ seenSegments: list[int] = []
+
+ async def handler(request: web.Request) -> web.Response:
+ seg = int(request.query["segment_index"])
+ seenSegments.append(seg)
+ if seg == 1:
+ return web.Response(body=encodeSegment([
+ encodeElem(elemId=1, progressMs=10000, content="区间前"),
+ ]))
+ if seg == 2:
+ return web.Response(body=encodeSegment([
+ encodeElem(elemId=2, progressMs=360000, content="边界前"),
+ encodeElem(elemId=3, progressMs=400000, content="中段A"),
+ encodeElem(elemId=4, progressMs=500000, content="中段B"),
+ ]))
+ if seg == 3:
+ return web.Response(body=encodeSegment([
+ encodeElem(elemId=4, progressMs=500000, content="中段B重复"),
+ encodeElem(elemId=5, progressMs=730000, content="区间后"),
+ ]))
+ return web.Response(status=304)
+
+ baseUrl = await startServer(handler)
+ monkeypatch.setattr(danmaku, "DANMAKU_SEG_API", baseUrl)
+
+ items = await fetchDanmaku(
+ cid=100,
+ aid=200,
+ duration=1200,
+ startTime=390,
+ endTime=725,
+ signParams=lambda p: p,
+ )
+ assert sorted(seenSegments) == [2, 3]
+ assert [(x.id, x.progressMs, x.content) for x in items] == [
+ (3, 10000, "中段A"),
+ (4, 110000, "中段B"),
+ ]
+
+ seenSegments.clear()
+ probed = await fetchDanmaku(cid=100, duration=0, signParams=lambda p: p)
+ assert seenSegments == [1, 2, 3, 4]
+ assert [x.id for x in probed] == [1, 2, 3, 4, 5]
+
+
+async def test_fetch_danmaku_raises_on_412_and_api_error(startServer, monkeypatch):
+ mode = "412"
+
+ async def handler(request: web.Request) -> web.Response:
+ if mode == "412":
+ return web.Response(status=412, text="blocked")
+ return web.Response(
+ text=json.dumps({"code": -400, "message": "参数错误"}),
+ content_type="application/json",
+ )
+
+ baseUrl = await startServer(handler)
+ monkeypatch.setattr(danmaku, "DANMAKU_SEG_API", baseUrl)
+
+ with pytest.raises(TaskError, match="412"):
+ await fetchDanmaku(cid=100, duration=60, signParams=lambda p: p)
+
+ mode = "json_error"
+ with pytest.raises(ValueError, match="参数错误"):
+ await fetchDanmaku(cid=100, duration=60, signParams=lambda p: p)
+
+
+def test_to_xml_escapes_and_handles_empty():
+ items = [
+ DanmakuItem(
+ id=99,
+ progressMs=1234,
+ mode=1,
+ fontsize=25,
+ color=16777215,
+ midHash="a1b2c3d4",
+ content="A < B & C \"D\"\x00\x0b",
+ ctime=1700000000,
+ weight=6,
+ pool=0,
+ idStr="99",
+ )
+ ]
+ xmlText = toXml(items, cid=12345)
+ root = ET.fromstring(xmlText)
+ assert root.tag == "i"
+ assert root.findtext("chatid") == "12345"
+ assert root.findtext("state") == "0"
+ dNodes = root.findall("d")
+ assert len(dNodes) == 1
+ assert dNodes[0].attrib["p"] == "1.23400,1,25,16777215,1700000000,0,a1b2c3d4,99,6"
+ assert dNodes[0].text == 'A < B & C "D"'
+
+ emptyRoot = ET.fromstring(toXml([], cid=12345))
+ assert emptyRoot.findtext("state") == "1"
+ assert emptyRoot.findall("d") == []
+
+
+def test_to_ass_normalizes_landscape_portrait_and_rotation():
+ uhd = toAss([], width=3840, height=2160)
+ assert "PlayResX: 1920\n" in uhd and "PlayResY: 1080\n" in uhd
+
+ portrait = toAss([], width=1080, height=1920)
+ assert "PlayResX: 1080\n" in portrait and "PlayResY: 1920\n" in portrait
+
+ rotated = toAss([], width=1920, height=1080, rotate=1)
+ assert "PlayResX: 1080\n" in rotated and "PlayResY: 1920\n" in rotated
+
+ fallback = toAss([], width=0, height=0)
+ assert "PlayResX: 1920\n" in fallback and "PlayResY: 1080\n" in fallback
+
+
+def test_to_ass_formats_modes_colors_collisions_and_empty():
+ items = [
+ DanmakuItem(id=1, progressMs=1000, mode=1, fontsize=25, color=0xFFFFFF, content="第一条滚动"),
+ DanmakuItem(id=2, progressMs=1000, mode=1, fontsize=25, color=0xFF0000, content="第二条滚动{含花括号}\n换行\\斜杠"),
+ DanmakuItem(id=3, progressMs=1000, mode=5, fontsize=36, color=0x000000, content="黑色顶部"),
+ DanmakuItem(id=4, progressMs=1000, mode=4, fontsize=25, color=0x00FF00, content="绿色底部"),
+ DanmakuItem(id=5, progressMs=1000, mode=6, fontsize=25, color=0xFFFFFF, content="逆向弹幕"),
+ DanmakuItem(id=6, progressMs=1000, mode=7, fontsize=25, color=0xFFFFFF, content="高级忽略"),
+ DanmakuItem(id=7, progressMs=1000, mode=8, fontsize=25, color=0xFFFFFF, content="代码忽略"),
+ ]
+ assText = toAss(items, width=1920, height=1080, title="测试标题\n第二行")
+
+ assert "Title: 测试标题 第二行\n" in assText
+ assert "PlayResX: 1920\n" in assText
+ assert "PlayResY: 1080\n" in assText
+
+ dialogues = [line for line in assText.splitlines() if line.startswith("Dialogue: ")]
+ assert len(dialogues) == 5
+ assert "高级忽略" not in assText
+ assert "代码忽略" not in assText
+
+ # 同时间两条滚动弹幕应分配到不同 Y 轨道
+ assert "\\move(1920,10," in dialogues[0]
+ assert "\\move(1920,54," in dialogues[1]
+ assert "\\c&H0000FF&" in dialogues[1]
+ assert "\\{含花括号\\}\\N换行\\\\斜杠" in dialogues[1]
+
+ # 黑色大字顶部弹幕附带白色描边
+ assert "\\an8\\pos(960,10)\\fs54\\c&H000000&\\3c&HFFFFFF&" in dialogues[2]
+ assert "\\an2\\pos(960,1070)\\c&H00FF00&" in dialogues[3]
+ assert "\\move(-" in dialogues[4]
+
+ portraitAss = toAss([], width=1920, height=1080, rotate=1, title="竖屏")
+ assert "PlayResX: 1080\n" in portraitAss
+ assert "PlayResY: 1920\n" in portraitAss
+ assert "[Events]" in portraitAss
+ assert "Dialogue:" not in portraitAss
diff --git a/tests/bili_pack/test_task.py b/tests/bili_pack/test_task.py
index f486bf8b..019a0a19 100644
--- a/tests/bili_pack/test_task.py
+++ b/tests/bili_pack/test_task.py
@@ -2,6 +2,9 @@ from __future__ import annotations
from pathlib import Path
+import pytest
+
+from app.models.task import TaskError
from tests.helpers import buildFileContent, buildRangeHandler, runStep
@@ -210,3 +213,237 @@ def test_set_time_range_changes_listed_pages_only():
assert (pages[0].startTime, pages[0].endTime) == (10, 20)
assert (pages[1].startTime, pages[1].endTime) == (0, 0)
assert (pages[2].startTime, pages[2].endTime) == (5, 6)
+
+
+def buildSegmentBytes(content: str) -> bytes:
+ contentBytes = content.encode("utf-8")
+ elem = b"\x08\x01\x10\xe8\x07\x3a" + bytes([len(contentBytes)]) + contentBytes
+ return b"\x0a" + bytes([len(elem)]) + elem
+
+
+async def test_run_danmaku_side_file_and_empty_placeholder_cleanup(tmp_path, startServer, monkeypatch):
+ from aiohttp import web
+ from app.models.task import TaskStatus
+ import bili_pack.account as account
+ import bili_pack.danmaku as danmaku
+ from bili_pack.task import BiliPage, BilibiliDanmakuStep, BilibiliTask
+
+ body = buildSegmentBytes("测试弹幕")
+
+ async def handler(request: web.Request) -> web.Response:
+ return web.Response(body=body)
+
+ async def fakeMixinKey() -> str:
+ return ""
+
+ url = await startServer(handler)
+ monkeypatch.setattr(danmaku, "DANMAKU_SEG_API", url)
+ monkeypatch.setattr(account, "fetchWbiMixinKey", fakeMixinKey)
+
+ page = BiliPage(index=0, relativePath="v.mp4", cid=123, aid=456, width=1920, height=1080, _duration=10)
+ task = BilibiliTask(
+ name="演示.mp4",
+ url="https://www.bilibili.com/video/BV1",
+ outputFolder=tmp_path,
+ files=[page],
+ danmakuFormat="ass",
+ _baseName="演示",
+ )
+ task.update()
+ dmStep = next(s for s in task.steps if isinstance(s, BilibiliDanmakuStep))
+ assert dmStep.outputPath == str(tmp_path / "演示.ass")
+ for step in task.steps:
+ if step is not dmStep:
+ step.setStatus(TaskStatus.COMPLETED)
+
+ await runStep(dmStep)
+ assContent = Path(dmStep.outputPath).read_text(encoding="utf-8")
+ assert "测试弹幕" in assContent
+
+ # 作为 Side File 遇到空弹幕时清理空占位符
+ body = b""
+ taskEmpty = BilibiliTask(
+ name="空弹幕.mp4",
+ url="https://www.bilibili.com/video/BV2",
+ outputFolder=tmp_path,
+ files=[BiliPage(index=0, relativePath="v.mp4", cid=124, _duration=10)],
+ danmakuFormat="xml",
+ _baseName="空弹幕",
+ )
+ taskEmpty.update()
+ dmEmptyStep = next(s for s in taskEmpty.steps if isinstance(s, BilibiliDanmakuStep))
+ for step in taskEmpty.steps:
+ if step is not dmEmptyStep:
+ step.setStatus(TaskStatus.COMPLETED)
+ Path(dmEmptyStep.outputPath).touch()
+ await runStep(dmEmptyStep)
+ assert not Path(dmEmptyStep.outputPath).exists()
+
+
+async def test_run_standalone_danmaku_single_and_multi_page(tmp_path, startServer, monkeypatch):
+ from aiohttp import web
+ from app.models.task import Task
+ import bili_pack.account as account
+ import bili_pack.danmaku as danmaku
+ from bili_pack.task import BiliPage, BilibiliDanmakuStep, BilibiliTask
+
+ mode = "empty"
+
+ async def handler(request: web.Request) -> web.Response:
+ if mode == "412":
+ return web.Response(status=412, text="blocked")
+ if mode == "empty":
+ return web.Response(body=b"")
+ return web.Response(body=buildSegmentBytes("独立弹幕"))
+
+ async def fakeMixinKey() -> str:
+ return ""
+
+ url = await startServer(handler)
+ monkeypatch.setattr(danmaku, "DANMAKU_SEG_API", url)
+ monkeypatch.setattr(account, "fetchWbiMixinKey", fakeMixinKey)
+
+ single = BilibiliTask(
+ name="占位.mp4",
+ url="https://www.bilibili.com/video/BV1",
+ outputFolder=tmp_path,
+ files=[BiliPage(index=0, relativePath="", cid=200, _duration=10)],
+ isVideoEnabled=False,
+ isAudioEnabled=False,
+ danmakuFormat="ass",
+ _baseName="单P",
+ )
+ single.update()
+ assert single.name == "单P.ass"
+ assert single.placeholderPaths == [tmp_path / "单P.ass"]
+ dmSingle = single.steps[0]
+ assert isinstance(dmSingle, BilibiliDanmakuStep)
+
+ # 独立下载空弹幕应保留合法空头,避免任务完成后变成 Missing
+ await runStep(dmSingle)
+ assert Path(dmSingle.outputPath).is_file()
+ assert "[Events]" in Path(dmSingle.outputPath).read_text(encoding="utf-8")
+
+ # 多 P 独立下载与持久化往返、选集同步及 412 错误边界
+ mode = "text"
+ multi = BilibiliTask(
+ name="占位.mp4",
+ url="https://www.bilibili.com/video/BV2",
+ outputFolder=tmp_path,
+ files=[
+ BiliPage(index=0, relativePath="", cid=201, pageNumber=1, pagePart="上", selected=True, _duration=10),
+ BiliPage(index=1, relativePath="", cid=202, pageNumber=2, pagePart="下", selected=False, _duration=10),
+ ],
+ isVideoEnabled=False,
+ isAudioEnabled=False,
+ danmakuFormat="xml",
+ _baseName="合集",
+ )
+ multi.update()
+ assert multi.name == "合集.xml"
+ assert multi.outputPath == str(tmp_path / "合集")
+ assert [p.relativePath for p in multi.files] == ["合集 - P1 上.xml", "合集 - P2 下.xml"]
+
+ restored = Task.fromDict(multi.toDict())
+ assert isinstance(restored, BilibiliTask)
+ assert restored.danmakuFormat == "xml"
+ assert [type(s) for s in restored.steps] == [BilibiliDanmakuStep]
+
+ dmMulti = restored.steps[0]
+ await runStep(dmMulti)
+ assert "独立弹幕" in Path(dmMulti.outputPath).read_text(encoding="utf-8")
+
+ mode = "412"
+ restored.setSelection({0, 1})
+ assert [s.fileIndex for s in restored.steps if isinstance(s, BilibiliDanmakuStep)] == [0, 1]
+
+ dmSecond = next(s for s in restored.steps if isinstance(s, BilibiliDanmakuStep) and s.fileIndex == 1)
+ with pytest.raises(TaskError, match="412"):
+ await runStep(dmSecond)
+
+
+def test_android_adapter_danmaku_controls():
+ from bili_pack.android import draftFields, setControl, taskFields
+ from bili_pack.task import BiliPage, BilibiliTask
+
+ task = BilibiliTask(
+ name="v.mp4",
+ url="u",
+ outputFolder=Path("."),
+ files=[BiliPage(index=0, relativePath="v.mp4", cid=1, _duration=10)],
+ coverUrl="https://i0.hdslb.com/bfs/c.jpg",
+ _baseName="v",
+ )
+ task.update()
+
+ fields = draftFields(task)
+ controls = {c["id"]: c for c in fields["controls"]}
+ assert controls["danmaku"]["value"] == ""
+ assert [o["key"] for o in controls["danmaku"]["options"]] == ["ass", "xml"]
+ assert controls["danmaku"]["isOptional"] is True
+
+ setControl(task, "danmaku", "ass")
+ assert task.danmakuFormat == "ass"
+
+ setControl(task, "video", "")
+ setControl(task, "audio", "")
+ assert task.name == "v.ass"
+ assert taskFields(task)["canSelectFiles"] is True
+
+ fieldsOnlyDm = draftFields(task)
+ controlsOnlyDm = {c["id"]: c for c in fieldsOnlyDm["controls"]}
+ assert controlsOnlyDm["danmaku"]["isOptional"] is False
+ assert fieldsOnlyDm["subtitles"] == []
+ assert fieldsOnlyDm["duration"] == 10
+
+ # 不能关掉最后一个激活轨道
+ setControl(task, "danmaku", "")
+ assert task.danmakuFormat == "ass"
+
+ setControl(task, "cover", "1")
+ setControl(task, "danmaku", "")
+ assert task.danmakuFormat == ""
+ assert task.isCoverEnabled is True
+ setControl(task, "cover", "")
+ assert task.isCoverEnabled is True
+
+
+def test_bilibili_draft_card_danmaku_controls(qtbot, engine):
+ from app.config.cfg import cfg
+ from bili_pack.cards import BilibiliDraftCard
+ from bili_pack.task import BiliPage, BilibiliTask
+
+ task = BilibiliTask(
+ name="演示.mp4",
+ url="https://www.bilibili.com/video/BV1",
+ outputFolder=Path("."),
+ files=[BiliPage(index=0, relativePath="演示.mp4", cid=1, _duration=120)],
+ coverUrl="https://i0.hdslb.com/bfs/c.jpg",
+ _baseName="演示",
+ )
+ task.update()
+ card = BilibiliDraftCard(task, engine.categoryService, engine.coroutineRunner, lambda _: None)
+ qtbot.addWidget(card)
+ try:
+ card._danmakuButton._onOptionPicked("ass")
+ assert task.danmakuFormat == "ass"
+ assert card._danmakuButton.isChecked() is True
+
+ card._trackBar.videoButton.setChecked(False)
+ card._trackBar.audioButton.setChecked(False)
+ assert task.name == "演示.ass"
+ assert card.nameLabel.text() == "演示.ass"
+ assert not card._trimButton.isHidden()
+
+ card._danmakuButton._onTrackDeselected()
+ assert task.danmakuFormat == "ass"
+ assert card._danmakuButton.isChecked() is True
+
+ card._trackBar.coverButton.setChecked(True)
+ card._danmakuButton._onTrackDeselected()
+ assert task.danmakuFormat == ""
+ assert task.name == "演示.jpg"
+ assert card._trimButton.isHidden()
+ finally:
+ cfg.isCategoryEnabled.valueChanged.disconnect(card._refreshCategoryButton)
+
diff --git a/tests/bili_pack/test_task_parser.py b/tests/bili_pack/test_task_parser.py
index 8bbb7d53..04af8977 100644
--- a/tests/bili_pack/test_task_parser.py
+++ b/tests/bili_pack/test_task_parser.py
@@ -41,6 +41,7 @@ def test_build_favorite_pages_skips_invalid_and_expands_pages():
pages = buildFavoritePages(sample["medias"], sample["pageLists"])
assert [p.bvid for p in pages] == ["BV1p3ivB8EZA", "BV1PW4y1G7WG"] + ["BV1sx411N7ms"] * 14
assert pages[0].cid == 35163146510
+ assert pages[0].aid == sample["medias"][0]["id"]
assert pages[0].episodeTitle == "【中配】为什么Rust教程总喜欢自我吹嘘? Tsoding - Tsoding Highlights"
assert [p.pagePart for p in pages[2:5]] == ["至少还有你", "好久不见", "隐形的翅膀"]
assert all(p.selected for p in pages)
@@ -117,12 +118,13 @@ def buildSeasonView(currentBvid: str, extraSection: bool = False) -> dict:
def test_parse_video_selects_every_page():
viewData = {
+ "aid": 80433022,
"title": "三P稿件",
"pic": "http://i0.hdslb.com/bfs/cover.jpg",
"bvid": "BV1xxx",
"pages": [
- buildPage(11, 1, "开场"),
- buildPage(12, 2, "正片"),
+ {**buildPage(11, 1, "开场"), "dimension": {"width": 1920, "height": 1080, "rotate": 0}},
+ {**buildPage(12, 2, "正片"), "dimension": {"width": 1920, "height": 1080, "rotate": 1}},
buildPage(13, 3, "彩蛋"),
],
}
@@ -131,6 +133,10 @@ def test_parse_video_selects_every_page():
assert coverUrl == "https://i0.hdslb.com/bfs/cover.jpg"
assert [p.pageNumber for p in pages] == [1, 2, 3]
assert [p.cid for p in pages] == [11, 12, 13]
+ assert [p.aid for p in pages] == [80433022, 80433022, 80433022]
+ assert (pages[0].width, pages[0].height, pages[0].rotate) == (1920, 1080, 0)
+ assert (pages[1].width, pages[1].height, pages[1].rotate) == (1920, 1080, 1)
+ assert (pages[2].width, pages[2].height, pages[2].rotate) == (0, 0, 0)
assert [p.pagePart for p in pages] == ["开场", "正片", "彩蛋"]
assert [p.index for p in pages] == [0, 1, 2]
assert all(p.selected for p in pages)