Something went wrong. Try again.
Mirror — see github.com/blacksky-algorithms/blacksky.community
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259import {useCallback, useEffect, useRef, useState} from 'react'import {ActivityIndicator, View} from 'react-native'import {ImageBackground} from 'expo-image'import {msg} from '@lingui/core/macro'import {useLingui} from '@lingui/react'import {Trans} from '@lingui/react/macro'
import {getCurrentState, useOnAppStateChange} from '#/lib/appState'import {createPlaybackDurationTracker} from '#/lib/media/video/analytics'import { createPlaybackTelemetry, type PlaybackTelemetry,} from '#/lib/media/video/playbackTelemetry'import {ErrorBoundary} from '#/view/com/util/ErrorBoundary'import {atoms as a, platform} from '#/alf'import {Button} from '#/components/Button'import {useThrottledValue} from '#/components/hooks/useThrottledValue'import {ConstrainedImage} from '#/components/images/AutoSizedImage'import {PlayButtonIcon} from '#/components/video/PlayButtonIcon'import {useAnalytics} from '#/analytics'import {type app} from '#/lexicons'import {GifPresentationControls} from './GifPresentationControls'import {VideoEmbedInnerNative} from './VideoEmbedInner/VideoEmbedInnerNative'import * as VideoFallback from './VideoEmbedInner/VideoFallback'
interface Props { embed: app.bsky.embed.video.View post?: app.bsky.feed.defs.PostView}
export function VideoEmbed({embed, post}: Props) { const [key, setKey] = useState(0)
const renderError = useCallback( (error: unknown) => ( <VideoError error={error} retry={() => setKey(key + 1)} /> ), [key], )
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 contents = ( <ErrorBoundary renderError={renderError} key={key}> <InnerWrapper embed={embed} post={post} /> </ErrorBoundary> )
return ( <View style={[a.pt_xs]}> <ConstrainedImage aspectRatio={constrained || 1} // slightly smaller max height than images // images use 16 / 9, for reference minMobileAspectRatio={14 / 9}> {contents} </ConstrainedImage> </View> )}
function InnerWrapper({embed, post}: Props) { const {_} = useLingui() const ax = useAnalytics() const ref = useRef<{togglePlayback: () => void}>(null)
const [status, setStatus] = useState<'playing' | 'paused' | 'pending'>( 'pending', ) const [isLoading, setIsLoading] = useState(false) const [isActive, setIsActive] = useState(false) const showSpinner = useThrottledValue(isActive && isLoading, 100)
/* * Created lazily on first activation so videos that are never scrolled into * the active position cost nothing. */ const telemetryRef = useRef<PlaybackTelemetry | null>(null) const impressionTrackedRef = useRef(false) const playbackStartTrackedRef = useRef(false) const [durationTracker] = useState(() => { const tracker = createPlaybackDurationTracker({ enabled: embed.presentation !== 'gif', onSegment: segment => { ax.metric('video:playback:duration', { ...segment, postUri: post?.uri, postAuthorDid: post?.author.did, context: 'embed', presentation: embed.presentation === 'gif' ? 'gif' : 'video', }) }, }) tracker.setForeground(getCurrentState() === 'active') return tracker }) useOnAppStateChange(state => { durationTracker.setForeground(state === 'active') }) useEffect(() => { return () => { telemetryRef.current?.deactivated() durationTracker.flush('unmounted') } }, [durationTracker])
const showOverlay = !isActive || isLoading || (status === 'paused' && !isActive) || status === 'pending'
if (!isActive && status !== 'pending') { setStatus('pending') }
return ( <> <VideoEmbedInnerNative embed={embed} setStatus={s => { setStatus(s) durationTracker.setPlaying(s === 'playing') if (s === 'playing') { telemetryRef.current?.playing() } }} setIsLoading={loading => { setIsLoading(loading) durationTracker.setBuffering(loading) if (!loading) { telemetryRef.current?.ready() } }} setIsActive={active => { setIsActive(active) durationTracker.setActive(active) if (active) { if (!impressionTrackedRef.current) { impressionTrackedRef.current = true ax.metric('video:impression', { postUri: post?.uri, postAuthorDid: post?.author.did, context: 'embed', presentation: embed.presentation === 'gif' ? 'gif' : 'video', }) } if (telemetryRef.current == null) { telemetryRef.current = createPlaybackTelemetry({ surface: 'feed', presentation: embed.presentation === 'gif' ? 'gif' : 'video', }) } telemetryRef.current.activated() } else { telemetryRef.current?.deactivated() } }} onPlaybackStart={autoplay => { if (playbackStartTrackedRef.current) return playbackStartTrackedRef.current = true ax.metric('video:playback:start', { postUri: post?.uri, postAuthorDid: post?.author.did, context: 'embed', presentation: embed.presentation === 'gif' ? 'gif' : 'video', autoplay, }) }} onPlaybackProgress={progressSeconds => { durationTracker.observeProgress(progressSeconds) }} onError={error => { durationTracker.flush('error') telemetryRef.current?.error(error) ax.metric('video:playback:failed', { surface: 'feed', presentation: embed.presentation === 'gif' ? 'gif' : 'video', errorClass: 'PlayerError', errorMessage: error.slice(0, 256), playlist: embed.playlist, }) }} ref={ref} /> <ImageBackground source={{uri: embed.thumbnail}} accessibilityIgnoresInvertColors style={[ a.absolute, a.inset_0, { backgroundColor: 'transparent', // If you don't add `backgroundColor` to the styles here, // the play button won't show up on the first render on android 🥴😮💨 }, platform({ android: {display: showOverlay ? 'flex' : 'none'}, ios: {zIndex: showOverlay ? 1 : -1}, }), ]} cachePolicy="memory-disk" // Preferring memory cache helps to avoid flicker when re-displaying on android > {showOverlay && (embed.presentation === 'gif' ? ( <GifPresentationControls isPlaying={false} isLoading={showSpinner} onPress={() => { ref.current?.togglePlayback() }} altText={embed.alt} /> ) : ( <Button style={[a.flex_1, a.align_center, a.justify_center]} onPress={() => { ref.current?.togglePlayback() }} label={_(msg`Play video`)}> {showSpinner ? ( <View style={[a.align_center, a.justify_center]}> <ActivityIndicator size="large" color="white" /> </View> ) : ( <PlayButtonIcon /> )} </Button> ))} </ImageBackground> </> )}
function VideoError({retry}: {error: unknown; retry: () => void}) { return ( <VideoFallback.Container> <VideoFallback.Text> <Trans> An error occurred while loading the video. Please try again later. </Trans> </VideoFallback.Text> <VideoFallback.RetryButton onPress={retry} /> </VideoFallback.Container> )}