@banou/media-player 0.10.21 → 0.10.24

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,109 @@
1
+ import type { PlayerMedia } from '../media'
2
+
3
+ import { useEffect } from 'react'
4
+
5
+ import { usePlayer } from '../player'
6
+
7
+ /** Film's frame, until the media has been seen playing. */
8
+ const FALLBACK_FRAME = 1001 / 24000
9
+
10
+ const presented = (video: HTMLVideoElement, timeout: number) => new Promise<void>((done) => {
11
+ const timer = setTimeout(done, timeout)
12
+ video.requestVideoFrameCallback(() => { clearTimeout(timer); done() })
13
+ })
14
+
15
+ /**
16
+ * Offers `stepFrame` for a media whose frames this document can see, one with `requestVideoFrameCallback`.
17
+ *
18
+ * Paused by a seek, the element shows the frame holding `currentTime` (Chrome 155 and Firefox 157), so a step is
19
+ * `currentTime` plus or minus a frame. Paused from playing, Chrome shows the frame after that one in 15 of 40 pauses,
20
+ * so the step starts from the last frame presented while playing and aims at the middle of the next one. A frame a
21
+ * seek presented is never read for its time: Firefox reports the seek's target as its `mediaTime`.
22
+ *
23
+ * The frame's length is learned from the gaps between frames presented one after another while playing at up to 1x:
24
+ * faster, a 60 Hz display presents every other frame of a 60 fps file. A step while a seek waits for its data starts
25
+ * from that seek's target.
26
+ */
27
+ export const useFrameStep = (media: PlayerMedia | null) => {
28
+ const player = usePlayer()
29
+ const setSourceState = usePlayer((state) => state.setSourceState)
30
+ useEffect(() => {
31
+ const video = media as HTMLVideoElement | null
32
+ if (!video || typeof video.requestVideoFrameCallback !== 'function') return
33
+
34
+ let played: VideoFrameCallbackMetadata | undefined
35
+ let bySeek = false
36
+ const gaps: number[] = []
37
+ const onSeeking = () => { bySeek = true; played = undefined }
38
+ // a new media on the same element
39
+ const onEmptied = () => { played = undefined; gaps.length = 0 }
40
+ video.addEventListener('seeking', onSeeking)
41
+ video.addEventListener('emptied', onEmptied)
42
+ let handle = 0
43
+ const onFrame = (_: number, frame: VideoFrameCallbackMetadata) => {
44
+ const fromSeek = bySeek
45
+ // the first frame once a seek has landed while playing can still be the seek's own
46
+ if (!video.paused && !video.seeking) bySeek = false
47
+ if (
48
+ !fromSeek && !video.paused && video.playbackRate <= 1 &&
49
+ played && frame.presentedFrames === played.presentedFrames + 1 && frame.mediaTime > played.mediaTime
50
+ ) {
51
+ gaps.push(frame.mediaTime - played.mediaTime)
52
+ if (gaps.length > 60) gaps.shift()
53
+ }
54
+ played = fromSeek ? undefined : frame
55
+ handle = video.requestVideoFrameCallback(onFrame)
56
+ }
57
+ handle = video.requestVideoFrameCallback(onFrame)
58
+
59
+ const frameLength = () => {
60
+ if (gaps.length < 5) return FALLBACK_FRAME
61
+ const sorted = [...gaps].sort((a, b) => a - b)
62
+ const median = sorted[sorted.length >> 1]!
63
+ // Matroska's millisecond timestamps give gaps of 41 and 42 ms for a 41.708 ms frame: steps by their median of 42
64
+ // drift by a frame within about 65, steps by the mean of the gaps near it do not
65
+ const near = sorted.filter((gap) => Math.abs(gap - median) <= median / 4)
66
+ return near.reduce((sum, gap) => sum + gap, 0) / near.length
67
+ }
68
+
69
+ let busy = false
70
+ const stepFrame = async (direction: 1 | -1) => {
71
+ // a key repeat while a step is on its way is dropped, so a held key steps as fast as frames land
72
+ if (busy) return
73
+ busy = true
74
+ try {
75
+ if (!video.paused) {
76
+ video.pause()
77
+ // Chrome can still report the frame on screen after the pause
78
+ await presented(video, 100)
79
+ }
80
+ const length = frameLength()
81
+ // off `state`: the store has a getter only for the fields it was created with
82
+ const pending = player.state.seekingTo
83
+ const target = pending !== undefined
84
+ ? pending + direction * length
85
+ : played
86
+ ? played.mediaTime + (direction > 0 ? 1.5 : -0.5) * length
87
+ : video.currentTime + direction * length
88
+ const time = Math.max(0, Math.min(target, video.duration || target))
89
+ const landed = new Promise<void>((done) => {
90
+ const timer = setTimeout(done, 1000)
91
+ video.addEventListener('seeked', () => { clearTimeout(timer); done() }, { once: true })
92
+ })
93
+ const { requestSeek } = player.state
94
+ if (requestSeek) requestSeek(time)
95
+ else video.currentTime = time
96
+ await landed
97
+ } finally {
98
+ busy = false
99
+ }
100
+ }
101
+ setSourceState({ stepFrame })
102
+ return () => {
103
+ video.removeEventListener('seeking', onSeeking)
104
+ video.removeEventListener('emptied', onEmptied)
105
+ video.cancelVideoFrameCallback(handle)
106
+ setSourceState({ stepFrame: undefined })
107
+ }
108
+ }, [media, player, setSourceState])
109
+ }
@@ -1,4 +1,4 @@
1
- import type { PlaybackController } from '../../engine'
1
+ import type { PlaybackController, PlaybackOutput } from '../../engine'
2
2
  import type { PlaybackErrorEntry } from '../source-feature'
3
3
  import type { MediaPlayerLocalOptions } from '../video-player'
4
4
 
@@ -74,6 +74,7 @@ export const usePlayback = (
74
74
  subtitles: HTMLElement | null,
75
75
  /** null when the media is remote: there are no bytes, so there is no pipeline to run. */
76
76
  options: MediaPlayerLocalOptions | null,
77
+ onOutput?: (output: PlaybackOutput) => void,
77
78
  ) => {
78
79
  const player = usePlayer()
79
80
  // The four asset urls are required on the local arm, so a default only ever applies when options is
@@ -147,6 +148,8 @@ export const usePlayback = (
147
148
  onSeekRef.current = options?.onSeek
148
149
  const onPlaybackErrorRef = useRef(options?.onPlaybackError)
149
150
  onPlaybackErrorRef.current = options?.onPlaybackError
151
+ const onOutputRef = useRef(onOutput)
152
+ onOutputRef.current = onOutput
150
153
 
151
154
  // The store's ids are opaque, but everything this hook writes into it came from libav, so every id
152
155
  // that comes back is one of its own stream indices.
@@ -355,6 +358,7 @@ export const usePlayback = (
355
358
  onError: fail,
356
359
  onRecovered: () => { if (!cancelled) player.setSourceState({ playbackError: null }) },
357
360
  onSeek: (fraction) => onSeekRef.current?.(fraction),
361
+ onOutput: (output) => onOutputRef.current?.(output),
358
362
  onSubtitleStreams: (streams) => {
359
363
  if (cancelled) return
360
364
  player.setSourceState({
@@ -1,5 +1,6 @@
1
1
  import type { VolumeNormalizer } from '../../audio/volume-normalizer'
2
2
  import type { LoudnessSource } from '../../audio/loudness-analysis'
3
+ import type { PlaybackTap } from '../../audio/playback-tap'
3
4
 
4
5
  import { useEffect, useRef, useState } from 'react'
5
6
 
@@ -12,13 +13,13 @@ import { startLoudnessAnalysis } from '../../audio/loudness-analysis'
12
13
  * engine turned the element down, which leaves it playing exactly as before.
13
14
  *
14
15
  * With a `source`, the file is also analysed ahead of the playhead while it is on, reading only the byte `ranges`
15
- * given (all of them when undefined).
16
+ * given (all of them when undefined), or with a `tap`, from the audio playback remuxed.
16
17
  */
17
18
  export const useVolumeNormalizer = (
18
19
  video: HTMLVideoElement | null,
19
20
  workletUrl: string | undefined,
20
21
  enabled: boolean,
21
- source?: LoudnessSource,
22
+ source?: LoudnessSource | { tap: PlaybackTap, audioStreamIndex: number },
22
23
  ranges?: [number, number][],
23
24
  ) => {
24
25
  const handle = useRef<VolumeNormalizer | null>(null)
@@ -53,7 +54,9 @@ export const useVolumeNormalizer = (
53
54
  const analysis = useRef<ReturnType<typeof startLoudnessAnalysis> | null>(null)
54
55
  const sourceRef = useRef(source)
55
56
  sourceRef.current = source
56
- const { length, publicPath, libavWorkerUrl, audioStreamIndex } = source ?? {}
57
+ const { length, publicPath, libavWorkerUrl } = source && 'read' in source ? source : {}
58
+ const tap = source && 'tap' in source ? source.tap : undefined
59
+ const audioStreamIndex = source?.audioStreamIndex
57
60
  useEffect(() => {
58
61
  const current = sourceRef.current
59
62
  if (!node || !video || !workletUrl || !enabled || !current) return
@@ -64,7 +67,7 @@ export const useVolumeNormalizer = (
64
67
  started.stop()
65
68
  analysis.current = null
66
69
  }
67
- }, [node, video, workletUrl, enabled, length, publicPath, libavWorkerUrl, audioStreamIndex])
70
+ }, [node, video, workletUrl, enabled, length, publicPath, libavWorkerUrl, audioStreamIndex, tap])
68
71
 
69
72
  useEffect(() => { analysis.current?.update(ranges) }, [ranges])
70
73
 
@@ -238,6 +238,9 @@ export type SourceState = {
238
238
  */
239
239
  requestSeek?: (time: number) => void
240
240
 
241
+ /** One frame back or forward, pausing first. Undefined for a media whose frames this document cannot see. */
242
+ stepFrame?: (direction: 1 | -1) => void
243
+
241
244
  /** Set when the pipeline fails. Cleared when it recovers. */
242
245
  playbackError: unknown
243
246
  /**
@@ -11,19 +11,25 @@ import { useContainerAttach, useMediaAttach } from '@videojs/react'
11
11
 
12
12
  import { Player, usePlayer } from './player'
13
13
  import { usePlayback } from './hooks/use-playback'
14
+ import { useFrameStep } from './hooks/use-frame-step'
14
15
  import { useSeekThumbnails } from './hooks/use-thumbnails'
15
16
  import { usePictureInPicture } from './hooks/use-picture-in-picture'
16
17
  import { usePassThroughPictureInPicture } from './hooks/use-pass-through-picture-in-picture'
17
18
  import { useVolumeNormalizer } from './hooks/use-volume-normalizer'
19
+ import { createPlaybackTap } from '../audio/playback-tap'
18
20
  import Chrome from './components/chrome'
19
21
 
20
22
  /**
21
23
  * The source, read a range at a time: the player never downloads the whole file. Both fields travel
22
24
  * together, so passing one without the other is a type error.
25
+ *
26
+ * `readsDownload` marks a source each read of which is a download, a file over HTTP, so the volume normalizer
27
+ * analyses the audio playback fetched instead of reading the file again. Without it, and with no
28
+ * `downloadedRanges`, every byte is taken to be readable for free, as a local file's are.
23
29
  */
24
30
  export type MediaPlayerSource =
25
- | { read: (offset: number, size: number) => Promise<ArrayBuffer>, size: number }
26
- | { read?: undefined, size?: undefined }
31
+ | { read: (offset: number, size: number) => Promise<ArrayBuffer>, size: number, readsDownload?: boolean }
32
+ | { read?: undefined, size?: undefined, readsDownload?: undefined }
27
33
 
28
34
  /** Shared by both arms: nothing here depends on who owns the media. */
29
35
  type CommonOptions = {
@@ -161,7 +167,8 @@ export type MediaPlayerLocalOptions =
161
167
  * They are the same by default so generation shares playback's fetch order. A consumer whose
162
168
  * reads are not free wants them apart: a torrent hands this a non-prioritising, fail-fast reader
163
169
  * so generating previews cannot steal download order from the bytes playback is blocked on. The
164
- * analysis asks it only for bytes inside `downloadedRanges`, and with none given, for the whole file.
170
+ * analysis asks it only for bytes inside `downloadedRanges`, with none given for the whole file, and for
171
+ * nothing when the source `readsDownload`.
165
172
  */
166
173
  thumbnailRead?: (offset: number, size: number) => Promise<ArrayBuffer>
167
174
  /** Off entirely. A second wasm worker during pipeline boot is worth avoiding on a slow source. */
@@ -183,7 +190,8 @@ export type MediaPlayerLocalOptions =
183
190
  * `onNormalizeVolumeChange` reports and passes it back.
184
191
  *
185
192
  * While it is on the file is read a second time, in a worker, as far as `downloadedRanges` allows, to find the
186
- * loud parts ahead of the playhead. The sound plays 10 ms behind its input, on or off, once routed.
193
+ * loud parts ahead of the playhead; a source that `readsDownload` is not read again, and its loud parts are found
194
+ * in what playback fetched. The sound plays 10 ms behind its input, on or off, once routed.
187
195
  *
188
196
  * The first time it is on, the element is routed through Web Audio for the rest of its life (off then
189
197
  * bypasses). If autoplay rules hold the audio back, that waits for the page's next click, tap or key press, and
@@ -250,7 +258,7 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
250
258
  // local arm and is absent when the media is remote.
251
259
  const { title, chapters } = options
252
260
  const {
253
- size, downloadedRanges, publicPath, libavWorkerUrl, read, thumbnailRead, thumbnailsEnabled,
261
+ size, downloadedRanges, publicPath, libavWorkerUrl, read, thumbnailRead, thumbnailsEnabled, readsDownload,
254
262
  } = local ?? ({} as Partial<MediaPlayerLocalOptions>)
255
263
 
256
264
  const setMedia = useMediaAttach()
@@ -266,6 +274,7 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
266
274
  // permanent no-op.
267
275
  const media = remote?.media ?? video
268
276
  useEffect(() => { setMedia?.(media); return () => setMedia?.(null) }, [media, setMedia])
277
+ useFrameStep(media)
269
278
 
270
279
  // Served after it is attached, and re-served when the media changes: what an embedder drives is
271
280
  // whatever this player drives at the time. Keyed on the option's `origin` and `channel`, not on the
@@ -298,9 +307,12 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
298
307
  return () => { dropped = true; stop?.() }
299
308
  }, [media, !!expose, exposeId, exposeOrigin, exposeChannel])
300
309
 
310
+ // one per file, as `size` is the source's identity everywhere here
311
+ const tap = useMemo(() => createPlaybackTap(), [size])
312
+
301
313
  // Each of these no-ops on null inputs, which is what a remote arm supplies: it renders no <video>,
302
314
  // so there is nothing for them to attach to and nothing to guard at the call site.
303
- usePlayback(video, subtitleLayer, local)
315
+ usePlayback(video, subtitleLayer, local, readsDownload ? tap.push : undefined)
304
316
 
305
317
  const normalizeVolumeProp = local?.normalizeVolume ?? true
306
318
  const [normalizeVolume, setNormalizeVolume] = useState(normalizeVolumeProp)
@@ -315,15 +327,17 @@ const PlayerRoot = ({ options, children }: { options: MediaPlayerOptions, childr
315
327
  const hasRead = !!read
316
328
  const normalizerSource = useMemo(
317
329
  () => hasRead && size && publicPath && libavWorkerUrl && typeof playingAudio === 'number' && playingAudio >= 0
318
- ? {
319
- read: (offset: number, length: number) => analysisRead.current!(offset, length),
320
- length: size,
321
- publicPath,
322
- libavWorkerUrl,
323
- audioStreamIndex: playingAudio,
324
- }
330
+ ? readsDownload
331
+ ? { tap, audioStreamIndex: playingAudio }
332
+ : {
333
+ read: (offset: number, length: number) => analysisRead.current!(offset, length),
334
+ length: size,
335
+ publicPath,
336
+ libavWorkerUrl,
337
+ audioStreamIndex: playingAudio,
338
+ }
325
339
  : undefined,
326
- [hasRead, size, publicPath, libavWorkerUrl, playingAudio],
340
+ [hasRead, size, publicPath, libavWorkerUrl, playingAudio, readsDownload, tap],
327
341
  )
328
342
  const normalizerRanges = useMemo(
329
343
  () => downloadedRanges?.map(({ startByteOffset, endByteOffset }) => [startByteOffset, endByteOffset] as [number, number]),
@@ -42,14 +42,18 @@ const fromUrl = async (
42
42
  if (!response.ok) throw new Error(`The source could not be read: HTTP ${response.status}`)
43
43
  return response.arrayBuffer()
44
44
  }
45
- return { length, name, read }
45
+ return { length, name, read, readsDownload: true }
46
46
  }
47
47
 
48
- /** A source resolved down to what the remuxer needs: a total length and a byte-range reader. */
48
+ /**
49
+ * A source resolved down to what the remuxer needs: a total length and a byte-range reader, and whether each read
50
+ * is a download, which the player's `readsDownload` takes.
51
+ */
49
52
  export type RemuxerInput = {
50
53
  length: number
51
54
  name?: string
52
55
  read: (offset: number, size: number) => Promise<ArrayBuffer>
56
+ readsDownload?: boolean
53
57
  }
54
58
 
55
59
  export const inputToRemuxerInput = async (