Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 3 additions & 14 deletions src/plugins/nicojk/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1309,25 +1309,14 @@ export default function App() {
return false;
}

const { startAt, duration } = getBaseTiming(playable);
const primarySource = data.replaySources[0];
if (
!Number.isFinite(startAt) ||
startAt <= 0 ||
!Number.isFinite(duration) ||
duration <= 0 ||
primarySource.endAt <= primarySource.startAt
) {
return false;
}

let mgr = kakologManagersRef.current.get(playerID);
if (!mgr) {
mgr = new KakologManager();
kakologManagersRef.current.set(playerID, mgr);
}
mgr.setSources(data.replaySources);
if (data.jkContext && data.replaySources[0]) {
const { startAt, duration } = getBaseTiming(playable);
data.jkContext = withKakologSourceStates(
buildJkContext(
data.replaySources[0],
Expand All @@ -1339,6 +1328,7 @@ export default function App() {
);
}

const { duration } = getBaseTiming(playable);
const currentPlayableId = playable.id;
data.isLoadingRecordedComments = true;
data.recordedSourcesPendingFetch = false;
Expand Down Expand Up @@ -1402,8 +1392,7 @@ export default function App() {
latest.comments = fetchedComments;
latest.recordedFetchProgress = null;
latest.isLoadingRecordedComments = false;
latest.recordedCommentsReady =
fetchedComments.length > 0 || mgr.isFullyCompleted();
latest.recordedCommentsReady = true;
latest.interruptedSources = mgr.getInterruptedSources();
if (latest.jkContext) {
latest.jkContext = withKakologSourceStates(latest.jkContext, mgr);
Expand Down
31 changes: 31 additions & 0 deletions src/plugins/nicojk/comment-buffer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import type { NiconicoComment } from "./comment-client";

/** Forget IDs evicted from the live buffer, including comments filtered out by NG settings. */
export function getPendingLiveComments(
comments: NiconicoComment[],
processedIds: Set<number>,
) {
const retainedIds = new Set(comments.map((comment) => comment.id));
for (const id of processedIds) {
if (!retainedIds.has(id)) processedIds.delete(id);
}
return comments.filter((comment) => !processedIds.has(comment.id));
}

export function getCommentRowKey(comment: NiconicoComment) {
return `${comment.no}-${comment.id}`;
}

/** TanStack Virtual keeps measured sizes after rows leave the list unless we remove them. */
export function pruneCommentMeasurementCache(
cache: Map<string | number | bigint, number>,
comments: NiconicoComment[],
) {
if (cache.size === 0) return;
const staleKeys = new Set(cache.keys());
for (const comment of comments) {
staleKeys.delete(getCommentRowKey(comment));
if (staleKeys.size === 0) return;
}
for (const key of staleKeys) cache.delete(key);
}
70 changes: 70 additions & 0 deletions src/plugins/nicojk/comment-renderer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import NiconiComments, {
type FormattedComment,
} from "@xpadev-net/niconicomments";

/** Owns a canvas for one renderer generation; destroyed WebGL contexts cannot be reused. */
export class CommentRenderer {
private canvas: HTMLCanvasElement;
private readonly renderer: NiconiComments;
private destroyed = false;

constructor(
container: HTMLElement,
comments: FormattedComment[],
format: "empty" | "formatted",
) {
this.canvas = container.ownerDocument.createElement("canvas");
this.canvas.width = 1920;
this.canvas.height = 1080;
this.canvas.style.width = "100%";
this.canvas.style.height = "100%";
this.canvas.style.display = "block";
container.append(this.canvas);
try {
this.renderer = new NiconiComments(this.canvas, comments, {
format,
lazy: true,
});
this.adoptRendererCanvas(container);
} catch (error) {
this.adoptRendererCanvas(container);
this.releaseCanvas();
throw error;
}
}

addComments(...comments: FormattedComment[]) {
this.renderer.addComments(...comments);
}

drawCanvas(vpos: number) {
this.renderer.drawCanvas(vpos);
}

destroy() {
if (this.destroyed) return;
this.destroyed = true;
try {
// clear() only erases pixels; destroy() releases listeners, timers and GL resources.
this.renderer.destroy();
} finally {
this.releaseCanvas();
}
}

private adoptRendererCanvas(container: HTMLElement) {
// niconicomments may replace the canvas when falling back from WebGL to 2D.
const canvas = container.querySelector("canvas");
if (canvas && canvas !== this.canvas) {
this.canvas.width = 0;
this.canvas.height = 0;
this.canvas = canvas;
}
}

private releaseCanvas() {
this.canvas.remove();
this.canvas.width = 0;
this.canvas.height = 0;
}
}
43 changes: 23 additions & 20 deletions src/plugins/nicojk/components/OverlayPage.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import NiconiComments, {
type FormattedComment,
} from "@xpadev-net/niconicomments";
import type { FormattedComment } from "@xpadev-net/niconicomments";
import { useEffect, useRef, useState } from "react";
import type { PlayerPlaybackState } from "../../../vendor/Plugin";
import { getPendingLiveComments } from "../comment-buffer";
import type { NiconicoComment } from "../comment-client";
import { isCommentNGBySettings } from "../comment-dedupe";
import { CommentRenderer } from "../comment-renderer";
import { getCommentSourceKeyForComment } from "../comment-source";
import type { NicoJKContext } from "../context";
import {
Expand Down Expand Up @@ -233,8 +233,8 @@ export default function OverlayPage({
playbackState,
jkContext,
}: Props) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const rendererRef = useRef<NiconiComments | null>(null);
const canvasContainerRef = useRef<HTMLDivElement>(null);
const rendererRef = useRef<CommentRenderer | null>(null);
const rendererMetaRef = useRef<{
mode: RendererMode;
playableId: string | null;
Expand Down Expand Up @@ -330,7 +330,7 @@ export default function OverlayPage({

useEffect(() => {
return () => {
rendererRef.current?.clear();
rendererRef.current?.destroy();
rendererRef.current = null;
rendererMetaRef.current = null;
renderedLiveCommentIdsRef.current.clear();
Expand All @@ -345,7 +345,7 @@ export default function OverlayPage({
}, [playableId]);

useEffect(() => {
if (!canvasRef.current) return;
if (!canvasContainerRef.current) return;

const recordedRendererPhase: RecordedRendererPhase = !recordedCommentsReady
? "none"
Expand All @@ -355,7 +355,7 @@ export default function OverlayPage({
const shouldCreateRenderer = hasDisplayCandidates && showComments;
if (!shouldCreateRenderer) {
if (rendererRef.current) {
rendererRef.current.clear();
rendererRef.current.destroy();
rendererRef.current = null;
rendererMetaRef.current = null;
renderedLiveCommentIdsRef.current.clear();
Expand All @@ -367,7 +367,9 @@ export default function OverlayPage({

const nextMode: RendererMode = isLive ? "live" : "recorded";
const commentTimingSignature = getCommentTimingSignature(jkContext);
const commentDataSignature = getCommentDataSignature(comments);
const commentDataSignature = isLive
? ""
: getCommentDataSignature(comments);
const shouldRecreate =
!rendererRef.current ||
rendererMetaRef.current?.mode !== nextMode ||
Expand All @@ -387,7 +389,8 @@ export default function OverlayPage({
return;
}

rendererRef.current?.clear();
rendererRef.current?.destroy();
rendererRef.current = null;
const currentSettings = getSettings();
const usesFormattedRenderer =
!isLive && (recordedRendererPhase !== "none" || comments.length > 0);
Expand All @@ -414,10 +417,11 @@ export default function OverlayPage({
currentSettings,
)
: [];
const renderer = new NiconiComments(canvasRef.current, initialComments, {
format: usesFormattedRenderer ? "formatted" : "empty",
lazy: true,
});
const renderer = new CommentRenderer(
canvasContainerRef.current,
initialComments,
usesFormattedRenderer ? "formatted" : "empty",
);
if (isLive && liveComments.length > 0) {
renderer.addComments(...liveComments);
}
Expand Down Expand Up @@ -507,8 +511,9 @@ export default function OverlayPage({
return;
}

const pendingComments = comments.filter(
(comment) => !renderedLiveCommentIdsRef.current.has(comment.id),
const pendingComments = getPendingLiveComments(
comments,
renderedLiveCommentIdsRef.current,
);
if (pendingComments.length === 0) {
return;
Expand Down Expand Up @@ -553,10 +558,8 @@ export default function OverlayPage({

return (
<div className="w-full h-full min-h-full flex flex-col items-center justify-center pointer-events-none bg-transparent overflow-hidden">
<canvas
ref={canvasRef}
width={1920}
height={1080}
<div
ref={canvasContainerRef}
style={{
width: targetW,
height: targetH,
Expand Down
13 changes: 12 additions & 1 deletion src/plugins/nicojk/components/PanelPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ import {
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { PlayerPlaybackState } from "../../../vendor/Plugin";
import { type ChapterPoint, detectChapterPoints } from "../chapter-comments";
import {
getCommentRowKey,
pruneCommentMeasurementCache,
} from "../comment-buffer";
import type { ConnectionStatus, NiconicoComment } from "../comment-client";
import { isCommentNGBySettings } from "../comment-dedupe";
import {
Expand Down Expand Up @@ -335,12 +339,19 @@ export default function PanelPage({
overscan: 10,
getItemKey: (index) => {
const item = displayComments[index];
return item ? `${item.no}-${item.id}` : index;
return item ? getCommentRowKey(item) : index;
},
paddingEnd: safeAreaInsetBottom,
scrollPaddingEnd: safeAreaInsetBottom + 4,
});

useEffect(() => {
pruneCommentMeasurementCache(
rowVirtualizer.itemSizeCache,
hasActivePlayer ? displayComments : [],
);
}, [displayComments, hasActivePlayer, rowVirtualizer]);

const findCommentIndexByVpos = useCallback(
(targetVpos: number) => {
let low = 0;
Expand Down
Loading
Loading