import React, { useState, useRef, useEffect, useCallback } from "react"; import { formatDuration } from "../utils/format"; import { View, StyleSheet, TouchableOpacity, TouchableWithoutFeedback, Text, Modal, Image, PanResponder, useWindowDimensions, } from "react-native"; import Video, { VideoRef } from "react-native-video"; import { LinearGradient } from "expo-linear-gradient"; import { Ionicons } from "@expo/vector-icons"; import type { PlayUrlResponse, VideoShotData, DanmakuItem, } from "../services/types"; import { buildDashMpdUri } from "../utils/dash"; import { getVideoShot } from "../services/bilibili"; import DanmakuOverlay from "./DanmakuOverlay"; const BAR_H = 3; // 进度球尺寸 const BALL = 12; // 活跃状态下的拖动球增大尺寸,提升触控体验 const BALL_ACTIVE = 16; const HIDE_DELAY = 3000; const HEADERS = { Referer: "https://www.bilibili.com", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36", }; function clamp(v: number, lo: number, hi: number) { return Math.max(lo, Math.min(hi, v)); } // index[i] = timestamp (seconds) for frame i. Returns frame number (position i), not index value. function findFrameByTime(index: number[], seekTime: number): number { let lo = 0, hi = index.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (index[mid] <= seekTime) lo = mid; else hi = mid - 1; } return lo; } interface Props { playData: PlayUrlResponse | null; qualities: { qn: number; desc: string }[]; currentQn: number; onQualityChange: (qn: number) => void; onFullscreen: () => void; onMiniPlayer?: () => void; style?: object; bvid?: string; cid?: number; danmakus?: DanmakuItem[]; isFullscreen?: boolean; onTimeUpdate?: (t: number) => void; initialTime?: number; } export function NativeVideoPlayer({ playData, qualities, currentQn, onQualityChange, onFullscreen, onMiniPlayer, style, bvid, cid, danmakus, isFullscreen, onTimeUpdate, initialTime, }: Props) { const { width: SCREEN_W, height: SCREEN_H } = useWindowDimensions(); const VIDEO_H = SCREEN_W * 0.5625; const [resolvedUrl, setResolvedUrl] = useState(); const isDash = !!playData?.dash; const [showControls, setShowControls] = useState(true); const hideTimer = useRef | null>(null); const [paused, setPaused] = useState(false); const [currentTime, setCurrentTime] = useState(0); const [duration, setDuration] = useState(0); const durationRef = useRef(0); const [showQuality, setShowQuality] = useState(false); const [buffered, setBuffered] = useState(0); const [isSeeking, setIsSeeking] = useState(false); const isSeekingRef = useRef(false); const [touchX, setTouchX] = useState(null); const touchXRef = useRef(null); const rafRef = useRef(null); const barOffsetX = useRef(0); const barWidthRef = useRef(300); const trackRef = useRef(null); const [shots, setShots] = useState(null); const [showDanmaku, setShowDanmaku] = useState(true); const videoRef = useRef(null); const currentDesc = qualities.find((q) => q.qn === currentQn)?.desc ?? String(currentQn || "HD"); // URL resolution useEffect(() => { if (!playData) { setResolvedUrl(undefined); return; } if (isDash) { buildDashMpdUri(playData, currentQn) .then(setResolvedUrl) .catch(() => setResolvedUrl(playData.dash!.video[0]?.baseUrl)); } else { setResolvedUrl(playData.durl?.[0]?.url); } }, [playData, currentQn]); // Video shots (thumbnails for seek preview) useEffect(() => { if (!bvid || !cid) return; let cancelled = false; getVideoShot(bvid, cid).then((shotData) => { if (cancelled) return; if (shotData?.image?.length) { setShots(shotData); console.log(shotData.index,shotData.image,'缩略图长度') } }); return () => { cancelled = true; }; }, [bvid, cid]); useEffect(() => { durationRef.current = duration; }, [duration]); const resetHideTimer = useCallback(() => { if (hideTimer.current) clearTimeout(hideTimer.current); if (!isSeekingRef.current) { hideTimer.current = setTimeout(() => setShowControls(false), HIDE_DELAY); } }, []); const showAndReset = useCallback(() => { setShowControls(true); resetHideTimer(); }, [resetHideTimer]); const handleTap = useCallback(() => { setShowControls((prev) => { if (!prev) { resetHideTimer(); return true; } if (hideTimer.current) clearTimeout(hideTimer.current); return false; }); }, [resetHideTimer]); // Start hide timer on mount useEffect(() => { resetHideTimer(); return () => { if (hideTimer.current) clearTimeout(hideTimer.current); }; }, []); const measureTrack = useCallback(() => { trackRef.current?.measureInWindow((x, _y, w) => { if (w > 0) { barOffsetX.current = x; barWidthRef.current = w; } }); }, []); const panResponder = useRef( PanResponder.create({ onStartShouldSetPanResponder: () => true, onMoveShouldSetPanResponder: () => true, onPanResponderGrant: (_, gs) => { isSeekingRef.current = true; setIsSeeking(true); setShowControls(true); if (hideTimer.current) clearTimeout(hideTimer.current); const x = clamp(gs.x0 - barOffsetX.current, 0, barWidthRef.current); touchXRef.current = x; setTouchX(x); }, onPanResponderMove: (_, gs) => { touchXRef.current = clamp( gs.moveX - barOffsetX.current, 0, barWidthRef.current, ); if (!rafRef.current) { rafRef.current = requestAnimationFrame(() => { setTouchX(touchXRef.current); rafRef.current = null; }); } }, onPanResponderRelease: (_, gs) => { if (rafRef.current) { cancelAnimationFrame(rafRef.current); rafRef.current = null; } const ratio = clamp( (gs.moveX - barOffsetX.current) / barWidthRef.current, 0, 1, ); const t = ratio * durationRef.current; videoRef.current?.seek(t); setCurrentTime(t); touchXRef.current = null; setTouchX(null); isSeekingRef.current = false; setIsSeeking(false); if (hideTimer.current) clearTimeout(hideTimer.current); hideTimer.current = setTimeout( () => setShowControls(false), HIDE_DELAY, ); }, onPanResponderTerminate: () => { if (rafRef.current) { cancelAnimationFrame(rafRef.current); rafRef.current = null; } touchXRef.current = null; setTouchX(null); isSeekingRef.current = false; setIsSeeking(false); }, }), ).current; const touchRatio = touchX !== null ? clamp(touchX / barWidthRef.current, 0, 1) : null; const progressRatio = duration > 0 ? clamp(currentTime / duration, 0, 1) : 0; const bufferedRatio = duration > 0 ? clamp(buffered / duration, 0, 1) : 0; const THUMB_DISPLAY_W = 120; // scaled display width const renderThumbnail = () => { if (touchRatio === null || !shots || !isSeeking) return null; const { img_x_size: TW, img_y_size: TH, img_x_len, img_y_len, image, index, } = shots; const framesPerSheet = img_x_len * img_y_len; const totalFrames = framesPerSheet * image.length; const seekTime = touchRatio * duration; // index[i] = timestamp of frame i (seconds). Binary search returns position i (= frame number). // Cap to index.length-1 to avoid black padding frames beyond valid content. const frameIdx = index?.length && duration > 0 ? clamp(findFrameByTime(index, seekTime), 0, index.length - 1) : clamp(Math.floor(touchRatio * (totalFrames - 1)), 0, totalFrames - 1); const sheetIdx = Math.floor(frameIdx / framesPerSheet); const local = frameIdx % framesPerSheet; const col = local % img_x_len; const row = Math.floor(local / img_x_len); console.log('[thumb]', { seekTime, duration, indexLen: index?.length, frameIdx, totalFrames, sheetIdx, col, row }); // Scale sprite frame to display size const scale = THUMB_DISPLAY_W / TW; const DW = THUMB_DISPLAY_W; const DH = Math.round(TH * scale); const trackLeft = barOffsetX.current; const absLeft = clamp(trackLeft + (touchX ?? 0) - DW / 2, 0, SCREEN_W - DW); // Protocol-relative URLs from B站 API need explicit https: const sheetUrl = image[sheetIdx].startsWith("//") ? `https:${image[sheetIdx]}` : image[sheetIdx]; return ( {formatDuration(Math.floor(seekTime))} ); }; return ( {resolvedUrl ? (