@banou/media-player 0.10.0 → 0.10.2

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,10 @@
1
+ /**
2
+ * Offers to jump past an opening or ending, when the chapter under the playhead looks like one.
3
+ *
4
+ * The whole feature is this button plus `classifyChapters`, and it is deliberately the weaker half
5
+ * of the pair: the classifier reads titles written by whoever muxed the file, so it is sometimes
6
+ * going to be wrong. Making the offer expire, and never acting on its own, is what makes being wrong
7
+ * cheap. See the classifier for what it matches and the sample it was measured against.
8
+ */
9
+ export declare const SkipChapter: () => import("@emotion/react/jsx-runtime").JSX.Element | null;
10
+ export default SkipChapter;
@@ -3,6 +3,7 @@ export declare const Player: import("@videojs/react").CreatePlayerResult<import(
3
3
  size?: number;
4
4
  downloadedRanges?: import("./source-feature").DownloadedRange[];
5
5
  indexes: import("..").MediaIndex[];
6
+ chapters: import("..").MediaChapter[];
6
7
  thumbnails: import("..").ThumbnailImage[];
7
8
  thumbnailAt?: (time: number) => import("..").ThumbnailImage | undefined;
8
9
  requestThumbnail: (time: number | undefined) => void;
@@ -1,4 +1,4 @@
1
- import type { MediaIndex, PictureInPictureMode, ThumbnailImage } from '../engine';
1
+ import type { MediaChapter, MediaIndex, PictureInPictureMode, ThumbnailImage } from '../engine';
2
2
  /**
3
3
  * One row of a track menu, already named.
4
4
  *
@@ -70,6 +70,14 @@ export type SourceState = {
70
70
  downloadedRanges?: DownloadedRange[];
71
71
  /** Keyframe index of the input, which turns a downloaded byte range into a time range. */
72
72
  indexes: MediaIndex[];
73
+ /**
74
+ * Named spans of the timeline, drawn as segments on the seekbar. Empty when the source has none.
75
+ *
76
+ * Ordered by start and non-overlapping, which is what the seekbar assumes. They need not cover the
77
+ * whole duration: the engine passes on whatever the container declared, and a caller-supplied list
78
+ * is whatever the caller knows.
79
+ */
80
+ chapters: MediaChapter[];
73
81
  thumbnails: ThumbnailImage[];
74
82
  /**
75
83
  * Answers for one time directly, when the source has a storyboard it can index but not enumerate.
@@ -168,6 +176,14 @@ export declare const sourceFeature: import("@videojs/react").PlayerFeature<{
168
176
  downloadedRanges?: DownloadedRange[];
169
177
  /** Keyframe index of the input, which turns a downloaded byte range into a time range. */
170
178
  indexes: MediaIndex[];
179
+ /**
180
+ * Named spans of the timeline, drawn as segments on the seekbar. Empty when the source has none.
181
+ *
182
+ * Ordered by start and non-overlapping, which is what the seekbar assumes. They need not cover the
183
+ * whole duration: the engine passes on whatever the container declared, and a caller-supplied list
184
+ * is whatever the caller knows.
185
+ */
186
+ chapters: MediaChapter[];
171
187
  thumbnails: ThumbnailImage[];
172
188
  /**
173
189
  * Answers for one time directly, when the source has a storyboard it can index but not enumerate.
@@ -1,4 +1,5 @@
1
1
  import type { ReactNode } from 'react';
2
+ import type { MediaChapter } from '../engine';
2
3
  import type { DownloadedRange } from './source-feature';
3
4
  import type { DelegatedTracks, ExternalThumbnails, PlayerMedia } from './media';
4
5
  import type { ExposePlayerOptions } from '../remote';
@@ -35,6 +36,18 @@ type CommonOptions = {
35
36
  */
36
37
  title?: string;
37
38
  autoplay?: boolean;
39
+ /**
40
+ * Named spans of the timeline, drawn as segments on the seekbar.
41
+ *
42
+ * Common to both arms rather than remote-only, unlike `thumbnails`. A local file is just as likely
43
+ * to declare none (mp4 and webm routinely carry no chapters at all), and a caller often knows
44
+ * chapters the container does not: skip-intro ranges from a metadata API are the usual case. Given
45
+ * here they WIN over whatever the container declared, and they paint on the first frame rather than
46
+ * waiting for the pipeline to boot.
47
+ *
48
+ * Expected in seconds, ordered by start and non-overlapping. They need not cover the duration.
49
+ */
50
+ chapters?: MediaChapter[];
38
51
  /**
39
52
  * Draw the control bar. Defaults to true.
40
53
  *
@@ -0,0 +1,37 @@
1
+ import type { MediaChapter } from '../engine';
2
+ /**
3
+ * Where the bar is broken, as percentages, including the two ends: [0, ...breaks, 100].
4
+ *
5
+ * Both edges of every chapter count, so chapters that leave un-named time between them break the
6
+ * bar on each side of the gap and the un-named span becomes a segment of its own. Returns nothing
7
+ * when there is no break worth drawing, which is what leaves a file with no chapters, or one whose
8
+ * single chapter spans the whole picture, rendering exactly as it did before chapters existed.
9
+ */
10
+ export declare const segmentBounds: (chapters: MediaChapter[], duration: number) => number[];
11
+ /**
12
+ * A mask painting the segments `keep` accepts, with a gap at every boundary between segments.
13
+ *
14
+ * The gap is cut from both sides of a boundary so it stays centred on it, and never from the two
15
+ * outer edges, where it would shorten the bar rather than divide it.
16
+ */
17
+ export declare const segmentMask: (bounds: number[], keep: (index: number) => boolean) => string;
18
+ /**
19
+ * What a chapter is, when its title says plainly enough to offer a skip.
20
+ *
21
+ * Only ever a suggestion: the player shows a button for a few seconds and does nothing unless it is
22
+ * pressed. That is what lets this be generous rather than careful. A chapter wrongly called an
23
+ * opening costs a button nobody presses, while an opening this fails to recognise costs the feature.
24
+ *
25
+ * Every rule below was checked against 192 real files (891 chapter markers, 79 distinct chapter
26
+ * sequences) rather than guessed, and the counts quoted are from that sample.
27
+ */
28
+ export type ChapterKind = 'opening' | 'ending';
29
+ /**
30
+ * What each chapter is, decided across the whole list rather than one title at a time.
31
+ *
32
+ * The list is what resolves the hedged words. A file whose chapters read Intro, OP, Episode, ED,
33
+ * Preview has already said which one the theme is, so its Intro is left alone; one that reads
34
+ * Episode, Intro, Episode, Credits has not, so its Intro is offered. Both shapes are in the sample,
35
+ * 13 files and 24 files.
36
+ */
37
+ export declare const classifyChapters: (chapters: MediaChapter[]) => (ChapterKind | undefined)[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@banou/media-player",
3
- "version": "0.10.0",
3
+ "version": "0.10.2",
4
4
  "description": "A video player for containers and codecs the browser cannot play natively, remuxed on the fly",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -1,5 +1,5 @@
1
1
  export { startPlayback, terminateRemuxer, MediaElementError, isMediaElementError, DEFAULT_BUFFER_SIZE } from './playback'
2
- export type { PlaybackOptions, PlaybackController, MediaIndex, AudioStream } from './playback'
2
+ export type { PlaybackOptions, PlaybackController, MediaIndex, MediaChapter, AudioStream } from './playback'
3
3
 
4
4
  export { createSubtitleRenderer, SUBTITLES_OFF } from './subtitles'
5
5
  export type { SubtitleRenderer, SubtitleRendererOptions, SubtitleStream } from './subtitles'
@@ -11,6 +11,18 @@ export type { AudioStream }
11
11
  /** A keyframe index entry: the byte offset a keyframe starts at, and the time it plays at. */
12
12
  export type MediaIndex = { pos: number, timestamp: number }
13
13
 
14
+ /**
15
+ * One named span of the timeline, in SECONDS.
16
+ *
17
+ * Chapters are not required to tile the duration: a container routinely declares a last chapter that
18
+ * ends fractionally before the file does, and nothing guarantees the first starts at zero. Anything
19
+ * drawing them has to treat the gaps as ordinary un-named time rather than assume full cover.
20
+ *
21
+ * libav also reports an `index`, dropped here the way `MediaIndex` drops it: array position already
22
+ * carries it, and a caller supplying their own chapters should not have to number them.
23
+ */
24
+ export type MediaChapter = { start: number, end: number, title: string }
25
+
14
26
  export type PlaybackOptions = {
15
27
  videoElement: HTMLVideoElement
16
28
  /**
@@ -55,6 +67,8 @@ export type PlaybackController = {
55
67
  selectSubtitleStream: (streamIndex: number | undefined) => void
56
68
  /** Keyframe index of the input, which is what maps a downloaded byte range onto the timeline. */
57
69
  indexes: MediaIndex[]
70
+ /** Named spans the container declared, empty when it declared none. */
71
+ chapters: MediaChapter[]
58
72
  duration: number
59
73
  videoMimeType: string
60
74
  audioMimeType: string
@@ -643,6 +657,7 @@ export const startPlayback = async (options: PlaybackOptions): Promise<PlaybackC
643
657
  videoElement,
644
658
  selectSubtitleStream: (streamIndex: number | undefined) => subtitles.selectStream(streamIndex),
645
659
  indexes: metadata.indexes ?? [],
660
+ chapters: metadata.chapters ?? [],
646
661
  duration: metadata.info.input.duration,
647
662
  videoMimeType: metadata.info.output.videoMimeType,
648
663
  audioMimeType: metadata.info.output.audioMimeType,
@@ -25,6 +25,17 @@ const READAHEAD = 1_000_000
25
25
  const MAX_ATTEMPTS = 3
26
26
  // a keyframe decode can hang without ever settling
27
27
  const KEYFRAME_TIMEOUT = 10_000
28
+ /**
29
+ * How much more of the file has to become readable before the index is walked again.
30
+ *
31
+ * An index is only as complete as the bytes behind it, and over a torrent those arrive for minutes
32
+ * after the player starts. Re-walking on every range change would demux the file over and over; a
33
+ * multiplier makes the number of walks logarithmic in the file size instead, so a download that
34
+ * starts at 2% re-indexes around eight times on its way to whole rather than hundreds.
35
+ */
36
+ const REINDEX_GROWTH = 1.5
37
+ /** And never re-walk for a trickle, however early. */
38
+ const REINDEX_MIN_BYTES = 4_000_000
28
39
 
29
40
  export type ThumbnailGenerator = {
30
41
  /** Report which byte ranges are readable. Called with no argument when the whole file is. */
@@ -60,22 +71,37 @@ export const createThumbnailGenerator = async (options: ThumbnailGeneratorOption
60
71
  const interval = Math.max(options.interval ?? INTERVAL, duration / MAX_THUMBNAILS)
61
72
 
62
73
  type Slot = { timestamp: number, endTime: number, startByte: number, endByte: number, done: boolean, attempts: number }
63
- const slots: Slot[] = []
64
- for (const [i, index] of metadata.indexes.entries()) {
65
- const last = slots.at(-1)
66
- if (last && index.timestamp - last.timestamp < interval) continue
67
- slots.push({
68
- timestamp: index.timestamp,
69
- endTime: duration,
70
- startByte: index.pos,
71
- endByte: Math.min((metadata.indexes[i + 1]?.pos ?? length) + READAHEAD, length),
72
- done: false,
73
- attempts: 0,
74
- })
74
+ let slots: Slot[] = []
75
+
76
+ /**
77
+ * The slot list for one index, which is only ever as complete as the bytes it was built from.
78
+ *
79
+ * libav walks the clusters it can read and stops, WITHOUT failing: on a file whose first tenth is
80
+ * readable it reports a single keyframe and a correct duration, because the duration comes from
81
+ * the header. That single entry then becomes a single slot whose endTime falls through to the
82
+ * duration, which is one preview covering the whole seekbar.
83
+ */
84
+ const buildSlots = (indexes: typeof metadata.indexes): Slot[] => {
85
+ const built: Slot[] = []
86
+ for (const [i, index] of indexes.entries()) {
87
+ const last = built.at(-1)
88
+ if (last && index.timestamp - last.timestamp < interval) continue
89
+ built.push({
90
+ timestamp: index.timestamp,
91
+ endTime: duration,
92
+ startByte: index.pos,
93
+ endByte: Math.min((indexes[i + 1]?.pos ?? length) + READAHEAD, length),
94
+ done: false,
95
+ attempts: 0,
96
+ })
97
+ }
98
+ for (const [i, slot] of built.entries()) slot.endTime = built[i + 1]?.timestamp ?? duration
99
+ // reading the last keyframe runs the demuxer into EOF, which crashes the libav build
100
+ if (built.length > 1 && (built.at(-1)!.timestamp > duration - interval * 2)) built.pop()
101
+ return built
75
102
  }
76
- for (const [i, slot] of slots.entries()) slot.endTime = slots[i + 1]?.timestamp ?? duration
77
- // reading the last keyframe runs the demuxer into EOF, which crashes the libav build
78
- if (slots.length > 1 && (slots.at(-1)!.timestamp > duration - interval * 2)) slots.pop()
103
+
104
+ slots = buildSlots(metadata.indexes)
79
105
 
80
106
  let thumbnails: ThumbnailImage[] = []
81
107
  let destroyed = false
@@ -93,6 +119,19 @@ export const createThumbnailGenerator = async (options: ThumbnailGeneratorOption
93
119
  /** Where the pointer is on the seekbar, or undefined when it is off it. */
94
120
  let priorityTime: number | undefined
95
121
 
122
+ /**
123
+ * How much of the file was readable when the current index was built.
124
+ *
125
+ * Negative until the first update, which establishes it: the boot walk has just happened against
126
+ * whatever was readable then, so the first report of the ranges is the baseline rather than a
127
+ * reason to walk again.
128
+ */
129
+ let indexedBytes = -1
130
+ let reindexWanted = false
131
+ let reindexing = false
132
+ /** The ranges last reported, so a walk deferred behind a decode can still claim against them. */
133
+ let lastRanges: [number, number][] | undefined
134
+
96
135
  /*
97
136
  * The slot to decode next: the one under the pointer when it is still waiting, else the oldest claim.
98
137
  *
@@ -146,7 +185,25 @@ export const createThumbnailGenerator = async (options: ThumbnailGeneratorOption
146
185
 
147
186
  // one decode at a time, because there is one wasm worker behind them all
148
187
  const pump = () => {
149
- if (running || destroyed || !pending.length) return
188
+ if (running || destroyed || reindexing) return
189
+ /*
190
+ * A deferred index walk goes first.
191
+ *
192
+ * There is one worker behind both, and a walk started while a decode holds it would have them
193
+ * interleaved on the same demuxer. Taking it here means the walk happens at the one moment
194
+ * nothing else is using it, and it happens BEFORE the next decode so that decode comes from
195
+ * the new slot list rather than the stale one.
196
+ */
197
+ if (reindexWanted) {
198
+ reindexWanted = false
199
+ const ranges = lastRanges
200
+ void reindex(readableTo(ranges)).then(() => {
201
+ claimReadable(ranges)
202
+ pump()
203
+ })
204
+ return
205
+ }
206
+ if (!pending.length) return
150
207
  const slot = pending.splice(nextIndex(), 1)[0]!
151
208
  running = true
152
209
  void decode(slot)
@@ -167,15 +224,74 @@ export const createThumbnailGenerator = async (options: ThumbnailGeneratorOption
167
224
  pump()
168
225
  }
169
226
 
227
+ /**
228
+ * Walk the index again now that more of the file can be read, and keep what is already drawn.
229
+ *
230
+ * A preview survives if its slot survives, which is why the previous timestamps are matched
231
+ * rather than the list being thrown away: the first slot is almost always still the first slot,
232
+ * and re-decoding it would throw away work and flicker the seekbar for no reason. What DOES
233
+ * change is its endTime, since a slot that used to run to the end of the file now runs only as
234
+ * far as the neighbour the new index revealed.
235
+ */
236
+ const reindex = async (readable: number) => {
237
+ reindexing = true
238
+ try {
239
+ const next = await remuxer.init()
240
+ if (destroyed) return
241
+ indexedBytes = readable
242
+ const rebuilt = buildSlots(next.indexes)
243
+ if (!rebuilt.length) return
244
+
245
+ const drawn = new Map(thumbnails.map((t) => [t.startTime, t]))
246
+ for (const slot of rebuilt) {
247
+ if (drawn.has(slot.timestamp)) slot.done = true
248
+ }
249
+ slots = rebuilt
250
+ // a preview whose slot is gone is no longer addressable, and its blob would leak
251
+ const kept = new Set(rebuilt.map((slot) => slot.timestamp))
252
+ for (const t of thumbnails) if (!kept.has(t.startTime)) URL.revokeObjectURL(t.url)
253
+ thumbnails = rebuilt
254
+ .filter((slot) => drawn.has(slot.timestamp))
255
+ .map((slot) => ({ url: drawn.get(slot.timestamp)!.url, startTime: slot.timestamp, endTime: slot.endTime }))
256
+ // anything claimed against the old list is stale, and the update below re-claims from the new one
257
+ pending.length = 0
258
+ emit()
259
+ } catch {
260
+ // an index that could not be re-read leaves the old one in place, and the next update retries
261
+ } finally {
262
+ reindexing = false
263
+ }
264
+ }
265
+
266
+ /** The end of what can be read, which is what an index walk can reach. */
267
+ const readableTo = (ranges?: [number, number][]) =>
268
+ ranges ? ranges.reduce((most, [, to]) => Math.max(most, to), 0) : length
269
+
270
+ const claimReadable = (ranges?: [number, number][]) => {
271
+ for (const slot of slots) {
272
+ if (slot.done) continue
273
+ if (!ranges || ranges.some(([from, to]) => from <= slot.startByte && slot.endByte <= to)) claim(slot)
274
+ }
275
+ }
276
+
170
277
  emit()
171
278
 
172
279
  return {
173
280
  update: (ranges) => {
174
281
  if (destroyed) return
175
- for (const slot of slots) {
176
- if (slot.done) continue
177
- if (!ranges || ranges.some(([from, to]) => from <= slot.startByte && slot.endByte <= to)) claim(slot)
282
+ lastRanges = ranges
283
+ const readable = readableTo(ranges)
284
+ if (indexedBytes < 0) indexedBytes = readable
285
+ else {
286
+ const grown = readable >= Math.max(indexedBytes * REINDEX_GROWTH, indexedBytes + REINDEX_MIN_BYTES)
287
+ // and one last walk when the file becomes whole, so a finished download is fully indexed
288
+ const whole = readable >= length && indexedBytes < length
289
+ if (grown || whole) reindexWanted = true
178
290
  }
291
+ claimReadable(ranges)
292
+ // claims first, so a walk that has to wait for a decode does not hold up the previews that
293
+ // the current index can already produce
294
+ pump()
179
295
  },
180
296
  prioritize: (time) => {
181
297
  if (destroyed) return
package/src/lib/index.tsx CHANGED
@@ -35,6 +35,7 @@ export type { RemuxerInput } from './utils/source'
35
35
  // The engine is also published on its own subpath for consumers that want the pipeline with no React.
36
36
  export type {
37
37
  AudioStream,
38
+ MediaChapter,
38
39
  MediaIndex,
39
40
  PictureInPictureController,
40
41
  PlaybackController,
@@ -8,6 +8,7 @@ import { usePlayer } from '../player'
8
8
  import { Overlay } from './overlay'
9
9
  import ControlBar from './control-bar'
10
10
  import BurnInHint from './burn-in-hint'
11
+ import SkipChapter from './skip-chapter'
11
12
 
12
13
  const AUTO_HIDE_DELAY = 3_000
13
14
 
@@ -233,6 +234,7 @@ export const Chrome = ({ ref, onVideoRef, onSubtitleRef, overlay, controls, chil
233
234
  {controls === false ? null : <ControlBar />}
234
235
  {/* Not tied to `hideUI`: it says what to do next, and it is on screen for nine seconds. */}
235
236
  <BurnInHint />
237
+ <SkipChapter />
236
238
  <div className="video" onClick={onVideoClick}>
237
239
  {onVideoRef ? <video ref={onVideoRef} playsInline /> : null}
238
240
  {children}
@@ -7,6 +7,8 @@ import { css } from '@emotion/react'
7
7
  import { usePlayer } from '../player'
8
8
  import { useDragValue } from '../hooks/use-drag-value'
9
9
  import { fonts } from '../../utils/fonts'
10
+ import { formatTime } from '../../utils/time'
11
+ import { segmentBounds, segmentMask } from '../../utils/chapters'
10
12
 
11
13
  const style = css`
12
14
  position: relative;
@@ -41,6 +43,37 @@ const style = css`
41
43
  }
42
44
  }
43
45
 
46
+ /*
47
+ * One copy of the track per mask, stacked.
48
+ *
49
+ * The rest track paints every segment except the one under the pointer, the focus track paints only that one and
50
+ * is the only element that grows. Both are full bar width, which is what keeps every percentage
51
+ * and every scaleX inside them meaning exactly what it meant before chapters existed: the gaps are
52
+ * cut by a mask, not by resizing anything.
53
+ *
54
+ * The mask sits HERE and never on .loaded-part or .play. Those two carry a scaleX, and a mask
55
+ * travels with its element's transform, so a gap drawn on them would slide with the fill.
56
+ */
57
+ .track {
58
+ position: absolute;
59
+ inset: 0;
60
+ /* never a hit target: .padding is the only one, and a second would break the drag gesture and
61
+ fire a bubbling mouseout at every boundary crossing */
62
+ pointer-events: none;
63
+ }
64
+
65
+ /*
66
+ * The segment under the pointer, on TOP of the growth the whole bar already got.
67
+ *
68
+ * Measured off YouTube's live player, hovering one chapter of five: every other segment goes 4px
69
+ * to 6px, and the one under the pointer goes to 10px. Both grow about the bar's centre line, so
70
+ * the emphasised segment bulges above and below its neighbours rather than sitting on them. 6 x
71
+ * 1.667 is 10, and the 1.5 the layers inside already carry gets this track from 4 to exactly that.
72
+ */
73
+ .track.focus {
74
+ transform: scaleY(1.667);
75
+ }
76
+
44
77
 
45
78
  .background-bar {
46
79
  position: absolute;
@@ -64,6 +97,23 @@ const style = css`
64
97
  text-shadow: 0 0 4px rgba(0, 0, 0, 1);
65
98
  ${fonts.bMedium.bold}
66
99
 
100
+ gap: calc(.6 * var(--mp-unit));
101
+
102
+ /*
103
+ * The chapter under the pointer, next to the time, which is where the reference puts it.
104
+ *
105
+ * It is the one part of this pill whose width the player does not control, so it is capped and
106
+ * ellipsised rather than allowed to push the box outside the picture. The cap and the clamp that
107
+ * positions the pill are set together on the element, since a centred box can only be kept
108
+ * inside the bar if the clamp knows its half width.
109
+ */
110
+ .chapter-title {
111
+ overflow: hidden;
112
+ text-overflow: ellipsis;
113
+ min-width: 0;
114
+ font-weight: normal;
115
+ }
116
+
67
117
  position: absolute;
68
118
  /* Anchored on its bottom edge rather than its top: now that it has a background its height
69
119
  follows the font size, and a top-anchored box would grow downward into the track. */
@@ -195,6 +245,7 @@ export const ProgressBar = () => {
195
245
  const thumbnails = usePlayer((state) => state.thumbnails)
196
246
  const thumbnailAt = usePlayer((state) => state.thumbnailAt)
197
247
  const requestThumbnail = usePlayer((state) => state.requestThumbnail)
248
+ const chapters = usePlayer((state) => state.chapters)
198
249
 
199
250
  const progressBarRef = useRef<HTMLDivElement>(null)
200
251
 
@@ -326,17 +377,6 @@ export const ProgressBar = () => {
326
377
  [duration, indexes.length, downloadedRanges?.map(({ startByteOffset, endByteOffset }) => `${startByteOffset}/${endByteOffset}`).join(',')]
327
378
  )
328
379
 
329
- const cusorTimeString = useMemo(() => {
330
- if (!progressBarHoverTime || progressBarHoverTime < 0) return undefined
331
- const hours = Math.floor(progressBarHoverTime! / 3600)
332
- const minutes = Math.floor((progressBarHoverTime! - hours * 3600) / 60)
333
- const seconds = Math.floor(progressBarHoverTime! - hours * 3600 - minutes * 60)
334
- const hoursString =
335
- hours > 0
336
- ? `${hours}:`
337
- : ''
338
- return `${hoursString}${minutes < 10 ? '0' : ''}${minutes}:${seconds < 10 ? '0' : ''}${seconds}`
339
- }, [progressBarHoverTime])
340
380
 
341
381
  /*
342
382
  * Follow the pointer while it is actually moving, and NOT on the press itself.
@@ -359,6 +399,38 @@ export const ProgressBar = () => {
359
399
  : currentTime / duration
360
400
  }, [duration, currentTime])
361
401
 
402
+ const bounds = useMemo(() => segmentBounds(chapters, duration), [chapters, duration])
403
+ const segmented = bounds.length > 0
404
+
405
+ /*
406
+ * Which segment the pointer is in, or -1.
407
+ *
408
+ * Compared against `undefined` rather than tested for truth: a hover at exactly time zero is a
409
+ * real hover, and the falsy check used elsewhere in this file silently drops it.
410
+ */
411
+ const focusedSegment = useMemo(() => {
412
+ if (!segmented || progressBarHoverTime === undefined || !duration) return -1
413
+ const at = (progressBarHoverTime / duration) * 100
414
+ const found = bounds.findIndex((from, i) => i < bounds.length - 1 && at >= from && at < bounds[i + 1]!)
415
+ // past the last boundary the pointer is in the final segment, which no `at < to` test catches
416
+ return found >= 0 ? found : bounds.length - 2
417
+ }, [segmented, bounds, progressBarHoverTime, duration])
418
+
419
+ const restMask = useMemo(
420
+ () => segmented ? segmentMask(bounds, (i) => i !== focusedSegment) : undefined,
421
+ [segmented, bounds, focusedSegment],
422
+ )
423
+ const focusMask = useMemo(
424
+ () => focusedSegment >= 0 ? segmentMask(bounds, (i) => i === focusedSegment) : undefined,
425
+ [bounds, focusedSegment],
426
+ )
427
+
428
+ /** The chapter the pointer is over. Absent while it is over un-named time between chapters. */
429
+ const hoveredChapter = useMemo(() => {
430
+ if (progressBarHoverTime === undefined) return undefined
431
+ return chapters.find(({ start, end }) => start <= progressBarHoverTime && progressBarHoverTime < end)
432
+ }, [chapters, progressBarHoverTime])
433
+
362
434
  // an empty url is a gap sentinel, so it renders nothing
363
435
  const thumbnail = useMemo(() => {
364
436
  if (!progressBarHoverTime) return undefined
@@ -372,41 +444,71 @@ export const ProgressBar = () => {
372
444
  )
373
445
  }, [thumbnails, thumbnailAt, progressBarHoverTime])
374
446
 
447
+ /*
448
+ * The whole track, drawn once per mask.
449
+ *
450
+ * Every layer inside is full bar width whichever mask it carries, so the loaded parts' percentage
451
+ * offsets and both scaleX transforms keep meaning what they meant before chapters existed. Only
452
+ * what is painted differs.
453
+ */
454
+ const track = (variant: 'focus' | undefined, mask: string | undefined) => (
455
+ <div
456
+ className={variant ? `track ${variant}` : 'track'}
457
+ style={mask ? { maskImage: mask } : undefined}
458
+ >
459
+ <div className="background-bar" />
460
+ {/* bar showing the currently loaded progress */}
461
+ <div className="loaded">
462
+ {loadedParts}
463
+ </div>
464
+ {/* bar displaying the current playback progress */}
465
+ <div className="play-container">
466
+ <div className="play" style={{ transform: `scaleX(${scaleX})` }}></div>
467
+ </div>
468
+ </div>
469
+ )
470
+
375
471
  return (
376
472
  <div
377
473
  css={style}
378
474
  ref={progressBarRef}
379
- className={dragging ? 'progress-bar dragging' : 'progress-bar'}
475
+ className={[
476
+ 'progress-bar',
477
+ dragging ? 'dragging' : '',
478
+ segmented ? 'segmented' : '',
479
+ ].filter(Boolean).join(' ')}
380
480
  onMouseMove={onProgressBarOver}
381
481
  onMouseOut={hideProgressBarTime}
382
482
  >
383
- <div className="background-bar" />
483
+ {track(undefined, restMask)}
384
484
  {
385
485
  progressBarHoverTime
386
486
  ? (
387
487
  <div
388
488
  className="cursor-time"
389
489
  /* the inset grew with the pill: content sized and centred, its half width is now the
390
- padding plus the text, so the old 18px let a filled box hang past both ends */
391
- style={{ left: `clamp(calc(3 * var(--mp-unit)), ${timePercentage(progressBarHoverTime)}%, calc(100% - calc(3 * var(--mp-unit))))` }}
490
+ padding plus the text, so the old 18px let a filled box hang past both ends. With a
491
+ chapter title the box is wider again and capped, so the clamp switches to half that
492
+ cap, which is the only width a centred box can be kept inside the bar by. */
493
+ style={{
494
+ left: hoveredChapter
495
+ ? `clamp(var(--thumbnail-half), ${timePercentage(progressBarHoverTime)}%, calc(100% - var(--thumbnail-half)))`
496
+ : `clamp(calc(3 * var(--mp-unit)), ${timePercentage(progressBarHoverTime)}%, calc(100% - calc(3 * var(--mp-unit))))`,
497
+ maxWidth: hoveredChapter ? 'var(--thumbnail-width)' : undefined,
498
+ }}
392
499
  >
393
- {cusorTimeString}
500
+ <span className="cursor-time-value">{formatTime(progressBarHoverTime)}</span>
501
+ {hoveredChapter ? <span className="chapter-title">{hoveredChapter.title}</span> : undefined}
394
502
  </div>
395
503
  )
396
504
  : undefined
397
505
  }
398
506
  <div className="progress"></div>
399
- {/* bar showing the currently loaded progress */}
400
- <div className="loaded">
401
- {loadedParts}
402
- </div>
403
507
  {/* bar to show when hovering to potentially seek */}
404
508
  <div className="hover"></div>
405
- {/* bar displaying the current playback progress */}
406
- <div className='play-container'>
407
- <div className="play" style={{ transform: `scaleX(${scaleX})` }}></div>
408
- </div>
409
- <div className="chapters"></div>
509
+ {/* the segment under the pointer, drawn taller. Sits after the flat track so it paints over
510
+ it, and before .padding so it never takes the press. */}
511
+ {focusMask ? track('focus', focusMask) : undefined}
410
512
  <div className="scrubber"></div>
411
513
  <div
412
514
  className="padding"