-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.rb
More file actions
662 lines (606 loc) · 26.5 KB
/
Copy pathapi.rb
File metadata and controls
662 lines (606 loc) · 26.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
require 'sinatra/base'
require 'pathname'
require_relative 'source_cache'
module MP4::Server
class API < Sinatra::Base
CONTENT_TYPES = {
'.mpd' => 'application/dash+xml',
'.m3u8' => 'application/vnd.apple.mpegurl',
'.mp4' => 'video/mp4',
'.m4s' => 'video/iso.segment',
}.freeze
SEGMENT_FILENAME = /\Achunk-\d+-\d{5}\.m4s\z/.freeze
INIT_FILENAME = /\Ainit-\d+\.mp4\z/.freeze
PLAYLIST_FILENAME = /\Aplaylist-\d+\.m3u8\z/.freeze
SOURCE_ROUTE_RE = %r{\A(?<path>.+\.mp4)/(?<artifact>.+)\z}.freeze
LOCAL_ROUTE_RE = SOURCE_ROUTE_RE
SEG_ARTIFACT_RE = %r{\A(?<selector>(?:vide|soun)-\d+)/(?<file>init(?:\.hls)?\.mp4|seg-\d+(?:\.hls)?\.m4s|playlist\.m3u8)\z}.freeze
class << self
attr_accessor :segments_dir, :source_cache, :base_dir, :players_default_src,
:demo_src, :demo_s3_uri, :demo_local_uri
end
configure do
enable :logging
set :segments_dir, ENV.fetch('MP4_SEGMENTS_DIR', 'out/fmp4')
set :base_dir, ENV.fetch('MP4_SOURCE_BASE_DIR', 'examples')
set :players_default_src, ENV.fetch('MP4_PLAYERS_DEFAULT_SRC', 'tears_of_steel_1080.mp4')
set :demo_src, ENV.fetch('MP4_DEMO_SRC', 'adaptive_demo.mp4')
set :demo_local_uri, "local:#{ENV.fetch('MP4_DEMO_SRC', 'adaptive_demo.mp4')}"
set :demo_s3_uri, "s3://#{ENV.fetch('MINIO_BUCKET', 'videos')}/#{ENV.fetch('MP4_DEMO_SRC', 'adaptive_demo.mp4')}"
set :source_cache, SourceCache.new(
max_entries: ENV.fetch('MP4_SOURCE_CACHE_SIZE', '4').to_i,
base_dir: ENV.fetch('MP4_SOURCE_BASE_DIR', 'examples'),
)
unless ENV['MP4_SKIP_PREWARM'] == '1'
STDERR.puts '[pre-warm] starting synchronous cache warm-up before WEBrick binds'
STDERR.flush
[settings.demo_local_uri, settings.demo_s3_uri].each do |uri|
started = Time.now
STDERR.puts "[pre-warm] parsing #{uri}"
STDERR.flush
settings.source_cache.fetch(uri) { |_mp4| }
STDERR.puts "[pre-warm] #{uri} ready in #{(Time.now - started).round(1)} s"
STDERR.flush
rescue StandardError => e
STDERR.puts "[pre-warm] #{uri} FAILED — #{e.class}: #{e.message}"
STDERR.puts e.backtrace.first(5).join("\n")
STDERR.flush
end
STDERR.puts '[pre-warm] all sources ready — starting Sinatra'
STDERR.flush
end
end
before do
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Range'
response['Access-Control-Expose-Headers'] = 'Content-Length,Content-Range'
end
options '/*' do
200
end
get '/' do
content_type :json
dir = segments_dir
files = Dir.exist?(dir) ? Dir.children(dir).sort : []
%({"segments_dir":"#{dir}","files":[#{files.map { |f| %("#{f}") }.join(',')}],"demo":"/demo"})
end
get '/demo' do
content_type 'text/html; charset=utf-8'
demo_page
end
get '/players' do
redirect to('/demo'), 301
end
get '/manifest.mpd' do serve_static('manifest.mpd') end
get '/general_playlist.m3u8' do serve_static('general_playlist.m3u8') end
get %r{/(playlist-\d+\.m3u8)} do |name| serve_named(name, PLAYLIST_FILENAME) end
get %r{/(init-\d+\.mp4)} do |name| serve_named(name, INIT_FILENAME) end
get %r{/(chunk-\d+-\d{5}\.m4s)} do |name| serve_named(name, SEGMENT_FILENAME) end
get '/sources.json' do
content_type :json
%({"base_dir":"#{self.class.base_dir}","files":[#{list_source_files.map { |f| %("#{f}") }.join(',')}]})
end
get %r{/local/(.+)} do |tail|
serve_source('local', tail)
end
get %r{/s3/(.+)} do |tail|
serve_source('s3', tail)
end
not_found do
content_type 'text/plain'
"not found: #{request.path_info}"
end
private
def segments_dir
Pathname.new(self.class.segments_dir)
end
def serve_named(name, pattern)
halt 400, 'bad filename' unless pattern.match?(name)
serve_static(name)
end
def serve_static(name)
path = segments_dir.join(name)
halt 404, "not found: #{name}" unless path.file?
ext = File.extname(name)
content_type(CONTENT_TYPES.fetch(ext, 'application/octet-stream'))
send_file(path.to_s, disposition: 'inline')
end
def list_source_files
root = Pathname.new(self.class.base_dir).expand_path
return [] unless root.directory?
Dir.glob(root.join('**', '*.mp4')).map { |p| Pathname.new(p).relative_path_from(root).to_s }.sort
end
def serve_source(scheme, tail)
match = SOURCE_ROUTE_RE.match(tail)
halt 400, "malformed /#{scheme} URL: #{tail}" unless match
path = match[:path]
artifact = match[:artifact]
uri = scheme == 'local' ? "local:#{path}" : "s3://#{path}"
self.class.source_cache.fetch(uri) do |mp4|
dispatch_artifact(mp4, artifact)
end
rescue Errno::ENOENT
halt 404, "source not found: #{tail}"
rescue ArgumentError => e
halt 400, e.message
rescue StandardError => e
MP4.logger.error { "serve_source(#{scheme}) failed for #{tail}: #{e.class} #{e.message}" }
halt 500, "source error: #{e.class}: #{e.message}"
end
def dispatch_artifact(mp4, artifact)
case artifact
when 'manifest.mpd'
content_type CONTENT_TYPES['.mpd']
M4S::LocalStream.dash_manifest(mp4.cache)
when 'master.m3u8'
content_type CONTENT_TYPES['.m3u8']
M4S::LocalStream.hls_master(mp4.cache)
else
seg_match = SEG_ARTIFACT_RE.match(artifact)
halt 404, "unknown artifact: #{artifact}" unless seg_match
dispatch_track_artifact(mp4, seg_match[:selector], seg_match[:file])
end
end
def dispatch_track_artifact(mp4, selector, file)
case file
when 'playlist.m3u8'
content_type CONTENT_TYPES['.m3u8']
M4S::LocalStream.hls_media(mp4.cache, selector)
when 'init.mp4', 'init.hls.mp4'
content_type CONTENT_TYPES['.mp4']
M4S::LocalStream.init_segment(mp4, selector)
else
seg_number = file[/\Aseg-(\d+)/, 1]
halt 404, "unknown artifact: #{file}" unless seg_number
content_type CONTENT_TYPES['.m4s']
M4S::LocalStream.media_segment(mp4, selector, seg_number)
end
end
def demo_page
require 'json'
src = self.class.demo_src.to_s
bucket = ENV.fetch('MINIO_BUCKET', 'videos')
DEMO_HTML
.sub('__DEMO_SRC__', src.to_json)
.sub('__DEMO_S3_BUCKET__', bucket.to_json)
.sub('__HLS_LOCAL__', "/local/#{src}/master.m3u8".to_json)
.sub('__DASH_LOCAL__', "/local/#{src}/manifest.mpd".to_json)
.sub('__HLS_S3__', "/s3/#{bucket}/#{src}/master.m3u8".to_json)
.sub('__DASH_S3__', "/s3/#{bucket}/#{src}/manifest.mpd".to_json)
end
DEMO_HTML = <<~HTML.freeze
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>mp4-rb · adaptive streaming demo</title>
<script src="https://cdn.jsdelivr.net/npm/shaka-player@5.1.10/dist/shaka-player.compiled.min.js"></script>
<style>
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
:root {
--bg: #0e1116;
--panel: #161b22;
--text: #d0d7de;
--muted: #8b949e;
--accent: #58a6ff;
--border: #30363d;
--good: #3fb950;
--bad: #f85149;
}
body {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif;
background: var(--bg);
color: var(--text);
padding: 12px;
font-size: 13px;
line-height: 1.5;
}
header {
display: flex; justify-content: space-between; align-items: center;
padding: 10px 16px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--panel);
margin-bottom: 12px;
}
header h1 { font-size: 14px; font-weight: 600; }
header h1 code { color: var(--accent); font-size: 12px; }
header .meta { font-size: 11px; color: var(--muted); }
header a { color: var(--muted); text-decoration: none; margin-left: 12px; }
header a:hover { color: var(--accent); }
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
}
@media (max-width: 900px) { .grid { grid-template-columns: 1fr; } }
.card {
background: var(--panel);
border: 1px solid var(--border);
border-radius: 6px;
display: flex; flex-direction: column;
overflow: hidden;
}
.card > h2 {
font-size: 12px; font-weight: 600;
letter-spacing: 0.06em; text-transform: uppercase;
color: var(--muted);
padding: 10px 14px;
border-bottom: 1px solid var(--border);
display: flex; justify-content: space-between; align-items: center; gap: 12px;
}
.card > h2 .title { display: flex; gap: 8px; align-items: baseline; }
.card > h2 .title .kind { color: var(--text); }
.card > h2 .title .src { font-size: 10px; color: var(--muted); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; letter-spacing: 0; text-transform: none; }
.card > h2 .status {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px; font-weight: 500;
padding: 2px 8px;
border-radius: 999px;
border: 1px solid var(--border);
color: var(--muted);
letter-spacing: 0.02em;
}
.card > h2 .status.ok { color: var(--good); border-color: #2ea043; }
.card > h2 .status.err { color: var(--bad); border-color: #da3633; }
video { width: 100%; display: block; background: #000; max-height: 34vh; object-fit: contain; }
.controls-row {
display: flex; gap: 10px; padding: 10px 14px;
border-top: 1px solid var(--border);
align-items: center; flex-wrap: wrap; font-size: 12px;
}
.controls-row label { color: var(--muted); }
.controls-row select {
background: #21262d; color: var(--text);
border: 1px solid var(--border); border-radius: 4px;
padding: 4px 8px; font-size: 12px;
flex: 1; min-width: 180px;
}
.controls-row select:disabled { opacity: 0.5; cursor: not-allowed; }
.controls-row .abr { display: inline-flex; gap: 4px; align-items: center; cursor: pointer; }
.stats {
display: grid;
grid-template-columns: max-content 1fr;
gap: 4px 14px;
padding: 10px 14px;
border-top: 1px solid var(--border);
background: #0d1117;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
max-height: 240px; overflow: auto;
}
.stats dt { color: var(--muted); }
.stats dd { color: var(--text); word-break: break-all; margin: 0; }
.err-box {
display: none;
padding: 8px 14px;
background: #3a0000; color: #f88;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
border-top: 1px solid #7a1a1a;
}
footer {
margin-top: 12px;
padding: 10px 16px;
border: 1px solid var(--border);
border-radius: 6px;
background: var(--panel);
color: var(--muted);
font-size: 11px;
}
footer code { color: var(--accent); }
/* First-load modal ---------------------------------------------- */
.modal {
position: fixed;
inset: 0;
z-index: 100;
display: none;
align-items: center;
justify-content: center;
}
.modal.visible { display: flex; }
.modal-backdrop {
position: absolute;
inset: 0;
background: rgba(0, 0, 0, 0.75);
backdrop-filter: blur(4px);
}
.modal-card {
position: relative;
max-width: 480px;
width: calc(100vw - 40px);
background: var(--panel);
border: 1px solid var(--border);
border-radius: 8px;
padding: 22px 26px 20px;
color: var(--text);
z-index: 1;
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.55);
}
.modal-card h2 {
font-size: 16px;
font-weight: 600;
margin-bottom: 10px;
color: var(--accent);
}
.modal-card p {
font-size: 12.5px;
color: var(--muted);
line-height: 1.55;
margin-bottom: 10px;
}
.modal-card p code { color: var(--text); font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 11.5px; }
.modal-card .actions { display: flex; justify-content: flex-end; margin-top: 14px; }
.modal-card button {
padding: 8px 20px;
background: var(--accent);
border: none;
border-radius: 4px;
color: #0e1116;
font-size: 13px;
font-weight: 600;
cursor: pointer;
font-family: inherit;
}
.modal-card button:hover { background: #79b6ff; }
.modal-card button:focus { outline: 2px solid #79b6ff; outline-offset: 2px; }
</style>
</head>
<body>
<div class="modal" id="first-load-modal" role="dialog" aria-modal="true" aria-labelledby="first-load-title">
<div class="modal-backdrop"></div>
<div class="modal-card">
<h2 id="first-load-title">Playback starts in about 5 seconds — please wait</h2>
<p>The server has already parsed the source MP4, memoised the sample table
and pre-warmed the LRU cache. What you'll see next is <code>shaka-player</code>
fetching the manifests + first two or three fMP4 segments — usually
<strong>~5 seconds</strong> until the first frame paints.</p>
<p>All four players stream concurrently — <code>HLS + DASH</code> from a
local file <em>and</em> <code>HLS + DASH</code> from MinIO S3 (via
<code>GetObject</code> byte-range reads).</p>
<div class="actions">
<button id="first-load-ok" autofocus>OK</button>
</div>
</div>
</div>
<header>
<h1>mp4-rb · adaptive streaming demo</h1>
<div class="meta">
<span>4 quality ladder from a single MP4 file · shaka-player 5.1.10</span>
<a href="/sources.json">sources.json</a>
<a href="/">/</a>
</div>
</header>
<div class="grid">
<section class="card">
<h2><span class="title"><span class="kind">HLS · local</span><span class="src" id="url-hls-local"></span></span><span class="status" id="hls-local-status">loading…</span></h2>
<video id="hls-local-video" controls muted playsinline></video>
<div class="err-box" id="hls-local-err"></div>
<div class="controls-row">
<label>quality</label>
<select id="hls-local-tracks" disabled></select>
<label class="abr"><input type="checkbox" id="hls-local-abr" checked> auto</label>
</div>
<dl class="stats" id="hls-local-stats"></dl>
</section>
<section class="card">
<h2><span class="title"><span class="kind">DASH · local</span><span class="src" id="url-dash-local"></span></span><span class="status" id="dash-local-status">loading…</span></h2>
<video id="dash-local-video" controls muted playsinline></video>
<div class="err-box" id="dash-local-err"></div>
<div class="controls-row">
<label>quality</label>
<select id="dash-local-tracks" disabled></select>
<label class="abr"><input type="checkbox" id="dash-local-abr" checked> auto</label>
</div>
<dl class="stats" id="dash-local-stats"></dl>
</section>
<section class="card">
<h2><span class="title"><span class="kind">HLS · s3 (MinIO)</span><span class="src" id="url-hls-s3"></span></span><span class="status" id="hls-s3-status">loading…</span></h2>
<video id="hls-s3-video" controls muted playsinline></video>
<div class="err-box" id="hls-s3-err"></div>
<div class="controls-row">
<label>quality</label>
<select id="hls-s3-tracks" disabled></select>
<label class="abr"><input type="checkbox" id="hls-s3-abr" checked> auto</label>
</div>
<dl class="stats" id="hls-s3-stats"></dl>
</section>
<section class="card">
<h2><span class="title"><span class="kind">DASH · s3 (MinIO)</span><span class="src" id="url-dash-s3"></span></span><span class="status" id="dash-s3-status">loading…</span></h2>
<video id="dash-s3-video" controls muted playsinline></video>
<div class="err-box" id="dash-s3-err"></div>
<div class="controls-row">
<label>quality</label>
<select id="dash-s3-tracks" disabled></select>
<label class="abr"><input type="checkbox" id="dash-s3-abr" checked> auto</label>
</div>
<dl class="stats" id="dash-s3-stats"></dl>
</section>
</div>
<footer>
Served by <code>MP4::Server::API</code> · source: <code id="footer-src"></code> ·
S3 bucket: <code id="footer-bucket"></code> ·
Range reads through <code>MP4::Source::S3</code> against <code>MINIO_ENDPOINT</code>.
</footer>
<script>
'use strict';
const DEMO_SRC = __DEMO_SRC__;
const DEMO_S3_BUCKET = __DEMO_S3_BUCKET__;
const HLS_LOCAL_URL = __HLS_LOCAL__;
const DASH_LOCAL_URL = __DASH_LOCAL__;
const HLS_S3_URL = __HLS_S3__;
const DASH_S3_URL = __DASH_S3__;
document.getElementById('footer-src').textContent = DEMO_SRC;
document.getElementById('footer-bucket').textContent = DEMO_S3_BUCKET;
document.getElementById('url-hls-local').textContent = HLS_LOCAL_URL;
document.getElementById('url-dash-local').textContent = DASH_LOCAL_URL;
document.getElementById('url-hls-s3').textContent = HLS_S3_URL;
document.getElementById('url-dash-s3').textContent = DASH_S3_URL;
function setStatus(id, label, kind) {
const el = document.getElementById(id);
el.textContent = label;
el.classList.remove('ok', 'err');
if (kind) el.classList.add(kind);
}
function showError(id, msg) {
const el = document.getElementById(id);
el.style.display = 'block';
el.textContent = '⚠ ' + msg;
}
function readyStateLabel(rs) {
return ['HAVE_NOTHING','HAVE_METADATA','HAVE_CURRENT_DATA','HAVE_FUTURE_DATA','HAVE_ENOUGH_DATA'][rs] || rs;
}
function fmtRanges(tr) {
if (!tr || !tr.length) return '(none)';
const out = [];
for (let i = 0; i < tr.length; i++) out.push(tr.start(i).toFixed(2) + '–' + tr.end(i).toFixed(2));
return out.join(', ');
}
function fmtKbps(bps) {
if (!isFinite(bps) || bps === 0) return '—';
return (bps / 1000).toFixed(0) + ' kbps';
}
function renderStats(id, rows) {
const el = document.getElementById(id);
el.innerHTML = rows.map(([k, v]) => '<dt>' + k + '</dt><dd>' + (v == null ? '—' : v) + '</dd>').join('');
}
async function initPlayer(spec) {
const video = document.getElementById(spec.videoId);
const statusId = spec.statusId;
const errId = spec.errId;
const statsId = spec.statsId;
const tracksEl = document.getElementById(spec.tracksId);
const abrEl = document.getElementById(spec.abrId);
if (!shaka.Player.isBrowserSupported()) {
setStatus(statusId, 'unsupported', 'err');
showError(errId, 'Browser lacks MSE support required by shaka-player.');
return null;
}
const player = new shaka.Player();
await player.attach(video);
player.addEventListener('error', (event) => {
const e = event.detail;
setStatus(statusId, 'error', 'err');
showError(errId, 'shaka error ' + e.code + ' (cat ' + e.category + '): ' + (e.message || ''));
console.error('[' + spec.label + '] shaka error', e);
});
try {
await player.load(spec.manifestUrl);
setStatus(statusId, 'ready', 'ok');
} catch (e) {
setStatus(statusId, 'load failed', 'err');
showError(errId, 'load failed (code ' + (e.code || '?') + '): ' + (e.message || e));
console.error('[' + spec.label + '] load failed', e);
return null;
}
function rebuildTrackList() {
const tracks = player.getVariantTracks().slice().sort((a, b) => b.bandwidth - a.bandwidth);
tracksEl.innerHTML = '';
tracks.forEach(track => {
const opt = document.createElement('option');
opt.value = track.id;
const kbps = Math.round(track.bandwidth / 1000);
const res = (track.width && track.height) ? (track.width + '×' + track.height) : 'audio-only';
opt.textContent = res + ' ' + kbps + ' kbps';
if (track.active) opt.selected = true;
opt.dataset.track = JSON.stringify(track);
tracksEl.appendChild(opt);
});
tracksEl.disabled = tracks.length <= 1;
}
rebuildTrackList();
function syncSelect() {
const active = player.getVariantTracks().find(t => t.active);
if (!active) return;
for (const opt of tracksEl.options) {
if (Number(opt.value) === active.id) { opt.selected = true; break; }
}
}
player.addEventListener('adaptation', syncSelect);
player.addEventListener('variantchanged', syncSelect);
tracksEl.addEventListener('change', () => {
const track = JSON.parse(tracksEl.options[tracksEl.selectedIndex].dataset.track);
player.configure({ abr: { enabled: false } });
abrEl.checked = false;
player.selectVariantTrack(track, true);
});
abrEl.addEventListener('change', () => {
player.configure({ abr: { enabled: abrEl.checked } });
});
function updateStats() {
const stats = player.getStats();
const active = player.getVariantTracks().find(t => t.active);
const rows = [
['url', spec.manifestUrl],
['currentTime', video.currentTime.toFixed(3) + ' s'],
['duration', isFinite(video.duration) ? video.duration.toFixed(3) + ' s' : '—'],
['paused', video.paused],
['readyState', video.readyState + ' — ' + readyStateLabel(video.readyState)],
['buffered (s)', fmtRanges(video.buffered)],
['videoSize', video.videoWidth + ' × ' + video.videoHeight],
['ABR', abrEl.checked ? 'on' : 'off'],
['est. bandwidth', fmtKbps(stats.estimatedBandwidth)],
['stream bandwidth', fmtKbps(stats.streamBandwidth)],
['active variant', active ? ((active.width || '?') + '×' + (active.height || '?') + ' ' + fmtKbps(active.bandwidth)) : '—'],
['dropped frames', isFinite(stats.droppedFrames) ? stats.droppedFrames : '—'],
['play time', isFinite(stats.playTime) ? stats.playTime.toFixed(1) + ' s' : '—'],
['stall count', isFinite(stats.stallCount) ? stats.stallCount : '—'],
];
renderStats(statsId, rows);
}
updateStats();
setInterval(updateStats, 500);
window.addEventListener('beforeunload', () => player.destroy());
return player;
}
document.addEventListener('DOMContentLoaded', async () => {
// Show the "loads in ~5s" modal on first tab-session open. Players
// start loading immediately in the background; OK just dismisses the
// overlay.
(function () {
const modal = document.getElementById('first-load-modal');
const okBtn = document.getElementById('first-load-ok');
const dismissedKey = 'mp4-rb-demo-modal-dismissed';
if (!sessionStorage.getItem(dismissedKey)) {
modal.classList.add('visible');
okBtn.focus();
}
function dismiss() {
modal.classList.remove('visible');
sessionStorage.setItem(dismissedKey, '1');
}
okBtn.addEventListener('click', dismiss);
modal.querySelector('.modal-backdrop').addEventListener('click', dismiss);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' || e.key === 'Enter') dismiss();
});
})();
shaka.polyfill.installAll();
window.hlsLocal = await initPlayer({
label: 'HLS·local', videoId: 'hls-local-video', manifestUrl: HLS_LOCAL_URL,
statusId: 'hls-local-status', errId: 'hls-local-err', statsId: 'hls-local-stats',
tracksId: 'hls-local-tracks', abrId: 'hls-local-abr',
});
window.dashLocal = await initPlayer({
label: 'DASH·local', videoId: 'dash-local-video', manifestUrl: DASH_LOCAL_URL,
statusId: 'dash-local-status', errId: 'dash-local-err', statsId: 'dash-local-stats',
tracksId: 'dash-local-tracks', abrId: 'dash-local-abr',
});
window.hlsS3 = await initPlayer({
label: 'HLS·s3', videoId: 'hls-s3-video', manifestUrl: HLS_S3_URL,
statusId: 'hls-s3-status', errId: 'hls-s3-err', statsId: 'hls-s3-stats',
tracksId: 'hls-s3-tracks', abrId: 'hls-s3-abr',
});
window.dashS3 = await initPlayer({
label: 'DASH·s3', videoId: 'dash-s3-video', manifestUrl: DASH_S3_URL,
statusId: 'dash-s3-status', errId: 'dash-s3-err', statsId: 'dash-s3-stats',
tracksId: 'dash-s3-tracks', abrId: 'dash-s3-abr',
});
});
</script>
</body>
</html>
HTML
end
end