Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432import { createContext, useCallback, useContext, useEffect, useRef, useState,} from 'react'import {View} from 'react-native'import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'
import {getCurrentState, useOnAppStateChange} from '#/lib/appState'import {createPlaybackDurationTracker} from '#/lib/media/video/analytics'import {ErrorBoundary} from '#/view/com/util/ErrorBoundary'import {atoms as a, useTheme} from '#/alf'import {useIsWithinMessage} from '#/components/dms/MessageContext'import {useFullscreen} from '#/components/hooks/useFullscreen'import {ConstrainedImage} from '#/components/images/AutoSizedImage'import {MediaInsetBorder} from '#/components/MediaInsetBorder'import { HLSFatalError, HLSUnsupportedError, VideoEmbedInnerWeb, VideoNotFoundError,} from '#/components/Post/Embed/VideoEmbed/VideoEmbedInner/VideoEmbedInnerWeb'import {useAnalytics} from '#/analytics'import {IS_WEB_FIREFOX} from '#/env'import {type app} from '#/lexicons'import {useActiveVideoWeb} from './ActiveVideoWebContext'import * as VideoFallback from './VideoEmbedInner/VideoFallback'
const noop = () => {}
/** * Minimum card width for the overlay controls (play, time, CC, volume, * fullscreen) to fit without crowding. Narrower cards fall back to the * full-width pillarbox. */const MIN_CARD_WIDTH = 280
export function VideoEmbed({ embed, post,}: { embed: app.bsky.embed.video.View post?: app.bsky.feed.defs.PostView}) { const t = useTheme() const ref = useRef<HTMLDivElement>(null) const { active: activeFromContext, setActive, sendPosition, currentActiveView, } = useActiveVideoWeb() const [onScreen, setOnScreen] = useState(false) const [meaningfullyVisible, setMeaningfullyVisible] = useState(false) const [isFullscreen] = useFullscreen() const lastKnownTime = useRef<number | undefined>(undefined) const impressionTrackedRef = useRef(false) const playbackStartTrackedRef = useRef(false) const ax = useAnalytics()
const isGif = embed.presentation === 'gif' // GIFs don't participate in the "one video at a time" system const active = isGif || activeFromContext const [durationTracker] = useState(() => { const tracker = createPlaybackDurationTracker({ enabled: !isGif, onSegment: segment => { ax.metric('video:playback:duration', { ...segment, postUri: post?.uri, postAuthorDid: post?.author.did, context: 'embed', presentation: isGif ? 'gif' : 'video', }) }, }) tracker.setForeground(getCurrentState() === 'active') return tracker })
useOnAppStateChange(state => { durationTracker.setForeground(state === 'active') })
useEffect(() => { durationTracker.setActive(active && onScreen) }, [active, durationTracker, onScreen])
useEffect(() => { return () => durationTracker.flush('unmounted') }, [durationTracker])
useEffect(() => { if (!meaningfullyVisible || impressionTrackedRef.current) return impressionTrackedRef.current = true ax.metric('video:impression', { postUri: post?.uri, postAuthorDid: post?.author.did, context: 'embed', presentation: isGif ? 'gif' : 'video', }) }, [ax, isGif, meaningfullyVisible, post?.author.did, post?.uri])
useEffect(() => { if (!ref.current) return if (isFullscreen && !IS_WEB_FIREFOX) return const observer = new IntersectionObserver( entries => { const entry = entries[0] if (!entry) return setOnScreen(entry.isIntersecting) setMeaningfullyVisible( entry.isIntersecting && entry.intersectionRatio >= 0.5, ) // GIFs don't send position - they don't compete to be the active video if (!isGif) { sendPosition( entry.boundingClientRect.y + entry.boundingClientRect.height / 2, ) } }, {threshold: 0.5}, ) observer.observe(ref.current) return () => observer.disconnect() }, [sendPosition, isFullscreen, isGif])
const [key, setKey] = useState(0) const renderError = useCallback( (error: unknown) => ( <VideoError embed={embed} error={error} retry={() => setKey(key + 1)} /> ), [key, embed], ) const getErrorMetadata = useCallback((error: Error) => { if (!(error instanceof HLSFatalError)) return {} return { tags: { hls_error_detail: error.detail, hls_error_type: error.type, }, hls: error.diagnostics, } }, [])
let aspectRatio: number | undefined const dims = embed.aspectRatio if (dims) { aspectRatio = dims.width / dims.height if (Number.isNaN(aspectRatio)) { aspectRatio = undefined } }
let constrained: number | undefined if (aspectRatio !== undefined) { const ratio = 1 / 2 // max of 1:2 ratio in feeds constrained = Math.max(aspectRatio, ratio) }
const [containerWidth, setContainerWidth] = useState(0)
/* * Portrait videos render at their own ratio instead of pillarboxed, but * only when the resulting card fits the overlay controls. Videos taller * than 1:2 would still show bars inside a ratio-fit card, and an unknown * ratio can't be fit, so both keep the full-width pillarbox - a narrow * card with black slices down the sides looks broken (see #9371). */ const cardWidth = containerWidth * Math.min(aspectRatio ?? 1, 1) const fullBleed = aspectRatio === undefined || aspectRatio < 1 / 2 || (containerWidth > 0 && cardWidth < MIN_CARD_WIDTH)
const contents = ( <div ref={ref} style={{ display: 'flex', flex: 1, cursor: 'default', position: 'relative', backgroundColor: t.palette.black, backgroundImage: `url(${embed.thumbnail})`, backgroundSize: 'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', }} onClick={evt => evt.stopPropagation()}> {fullBleed && embed.thumbnail && ( <> {/* blurred backdrop fills the bars when the video is boxed */} <div aria-hidden style={{ position: 'absolute', inset: 0, backgroundImage: `url(${embed.thumbnail})`, backgroundSize: 'cover', backgroundPosition: 'center', filter: 'blur(32px)', // hide the transparent fade the blur creates at the edges transform: 'scale(1.2)', }} /> {/* redraw the sharp thumbnail above the blur */} <div aria-hidden style={{ position: 'absolute', inset: 0, backgroundImage: `url(${embed.thumbnail})`, backgroundSize: 'contain', backgroundPosition: 'center', backgroundRepeat: 'no-repeat', }} /> </> )} <ErrorBoundary renderError={renderError} getErrorMetadata={getErrorMetadata} key={key}> <OnlyNearScreen> <VideoEmbedInnerWeb embed={embed} active={active} setActive={setActive} onScreen={onScreen} lastKnownTime={lastKnownTime} onPlaybackStart={autoplay => { if (playbackStartTrackedRef.current) return playbackStartTrackedRef.current = true ax.metric('video:playback:start', { postUri: post?.uri, postAuthorDid: post?.author.did, context: 'embed', presentation: isGif ? 'gif' : 'video', autoplay, }) }} onPlaybackProgress={progressSeconds => { durationTracker.observeProgress(progressSeconds) }} onPlaybackStateChange={state => { durationTracker.setBuffering(state === 'buffering') durationTracker.setPlaying(state === 'playing') }} onPlaybackEnd={() => durationTracker.flush('ended')} /> </OnlyNearScreen> </ErrorBoundary> </div> )
return ( <View style={[a.pt_xs]} onLayout={e => setContainerWidth(e.nativeEvent.layout.width)}> <ViewportObserver sendPosition={isGif ? noop : sendPosition} isAnyViewActive={currentActiveView !== null}> <ConstrainedImage fullBleed={fullBleed} aspectRatio={constrained || 1} // slightly smaller max height than images // images use 16 / 9, for reference minMobileAspectRatio={14 / 9}> {contents} <MediaInsetBorder /> </ConstrainedImage> </ViewportObserver> </View> )}
const NearScreenContext = createContext(false)NearScreenContext.displayName = 'VideoNearScreenContext'
/** * Renders a 100vh tall div and watches it with an IntersectionObserver to * send the position of the div when it's near the screen. * * IMPORTANT: ViewportObserver _must_ not be within a `overflow: hidden` container. */function ViewportObserver({ children, sendPosition, isAnyViewActive,}: { children: React.ReactNode sendPosition: (position: number) => void isAnyViewActive: boolean}) { const ref = useRef<HTMLDivElement>(null) const [nearScreen, setNearScreen] = useState(false) const [isFullscreen] = useFullscreen() const isWithinMessage = useIsWithinMessage()
// Send position when scrolling. This is done with an IntersectionObserver // observing a div of 100vh height useEffect(() => { if (!ref.current) return if (isFullscreen && !IS_WEB_FIREFOX) return const observer = new IntersectionObserver( entries => { const entry = entries[0] if (!entry) return const position = entry.boundingClientRect.y + entry.boundingClientRect.height / 2 sendPosition(position) setNearScreen(entry.isIntersecting) }, {threshold: Array.from({length: 101}, (_, i) => i / 100)}, ) observer.observe(ref.current) return () => observer.disconnect() }, [sendPosition, isFullscreen])
// In case scrolling hasn't started yet, send up the position useEffect(() => { if (ref.current && !isAnyViewActive) { const rect = ref.current.getBoundingClientRect() const position = rect.y + rect.height / 2 sendPosition(position) } }, [isAnyViewActive, sendPosition])
return ( <View style={[a.flex_1, a.flex_row]}> <NearScreenContext.Provider value={nearScreen}> {children} </NearScreenContext.Provider> <div ref={ref} style={{ // Don't escape bounds when in a message ...(isWithinMessage ? {top: 0, height: '100%'} : {top: 'calc(50% - 50vh)', height: '100vh'}), position: 'absolute', left: '50%', width: 1, pointerEvents: 'none', }} /> </View> )}
/** * Awkward data flow here, but we need to hide the video when it's not near the screen. * But also, ViewportObserver _must_ not be within a `overflow: hidden` container. * So we put it at the top level of the component tree here, then hide the children of * the auto-resizing container. */export const OnlyNearScreen = ({children}: {children: React.ReactNode}) => { const nearScreen = useContext(NearScreenContext)
return nearScreen ? children : null}
function VideoError({ embed, error, retry,}: { embed: app.bsky.embed.video.View error: unknown retry: () => void}) { const {_} = useLingui() const ax = useAnalytics()
let showRetryButton = true let text = null let errorClass: string
if (error instanceof VideoNotFoundError) { text = _(msg`Video not found.`) errorClass = 'VideoNotFoundError' } else if (error instanceof HLSUnsupportedError) { showRetryButton = false text = _( msg`This video can’t be played on your device. Your browser or system may be missing the required video codecs (H.264/AAC).`, ) errorClass = 'HLSUnsupportedError' } else { text = _(msg`An error occurred while loading the video. Please try again.`) if (error instanceof HLSFatalError) { errorClass = error.detail } else if (error instanceof Error) { errorClass = error.name || 'Error' } else { errorClass = 'Unknown' } }
const errorMessage = error instanceof Error ? error.message : String(error) const presentation = embed.presentation === 'gif' ? 'gif' : 'video' const playlist = embed.playlist /* * Fire exactly once per failure - the analytics context identity can change * (session/geolocation updates) while this fallback stays mounted, which * would otherwise re-run the effect and double-count. */ const fired = useRef(false) useEffect(() => { if (fired.current) return fired.current = true ax.metric('video:playback:failed', { surface: 'feed', presentation, errorClass, errorMessage: errorMessage.slice(0, 256), playlist, }) }, [ax, presentation, playlist, errorClass, errorMessage])
return ( <VideoFallback.Container> <VideoFallback.Text>{text}</VideoFallback.Text> {showRetryButton && <VideoFallback.RetryButton onPress={retry} />} </VideoFallback.Container> )}