Spaces:
Sleeping
Sleeping
Replace prototype with 114-second cinematic Douwei film in two formats
Browse files- .gitattributes +2 -0
- .gitignore +3 -0
- README.md +19 -9
- index.html +18 -39
- studio/app.js +0 -161
- studio/assets/finished.mp4 +0 -3
- studio/assets/message.mp4 +0 -3
- studio/assets/miniprogram-code.png +0 -3
- studio/assets/palette.jpg +0 -3
- studio/assets/pattern.jpg +0 -3
- studio/assets/peel.mp4 +0 -3
- studio/assets/result.jpg +0 -3
- studio/assets/scan.mp4 +0 -3
- studio/assets/soundtrack.m4a +0 -3
- studio/assets/voice-0.mp3 +0 -3
- studio/assets/voice-1.mp3 +0 -3
- studio/assets/voice-2.mp3 +0 -3
- studio/assets/voice-3.mp3 +0 -3
- studio/assets/voice-4.mp3 +0 -3
- studio/assets/voice-5.mp3 +0 -3
- studio/assets/voice-6.mp3 +0 -3
- studio/assets/voice-7.mp3 +0 -3
- studio/assets/voice-8.mp3 +0 -3
- studio/{assets/app.mp4 → film/douwei-portrait-114s.mp4} +2 -2
- studio/{assets/craft.jpg → film/douwei-wide-114s.mp4} +2 -2
- studio/{assets/heat.mp4 → film/soundtrack-114s.m4a} +2 -2
- studio/player.js +48 -0
- studio/style.css +1 -2
- studio/tools/build_assets.py +0 -88
- studio/tools/build_film.py +173 -0
- studio/vendor/mp4-muxer.mjs +0 -1879
.gitattributes
CHANGED
|
@@ -57,3 +57,5 @@ BeadQR/docs/promo/douwei-1080.mp4 filter=lfs diff=lfs merge=lfs -text
|
|
| 57 |
BeadQR/docs/promo/douwei-720-cover.png filter=lfs diff=lfs merge=lfs -text
|
| 58 |
BeadQR/docs/promo/douwei-720.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
studio/assets/* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 57 |
BeadQR/docs/promo/douwei-720-cover.png filter=lfs diff=lfs merge=lfs -text
|
| 58 |
BeadQR/docs/promo/douwei-720.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 59 |
studio/assets/* filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
studio/film/*.mp4 filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
studio/film/*.m4a filter=lfs diff=lfs merge=lfs -text
|
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
studio/film/.build/
|
| 2 |
+
**/__pycache__/
|
| 3 |
+
*.pyc
|
README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
---
|
| 2 |
-
title: 豆维 · 把
|
| 3 |
emoji: 🧩
|
| 4 |
colorFrom: green
|
| 5 |
colorTo: yellow
|
|
@@ -8,14 +8,24 @@ app_file: index.html
|
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
-
# 豆维
|
| 12 |
|
| 13 |
-
|
| 14 |
|
| 15 |
-
|
| 16 |
-
- **原始手作与小程序拍摄素材**:仓库根目录。`studio/assets/` 中的短片仅是为浏览器兼容转换的镜头片段,**不是成片**。网页实时完成分镜、字幕、动效和音画合成。
|
| 17 |
-
- **小程序源代码**:`BeadQR/`;功能详情与部署步骤见 [`BeadQR/README.md`](BeadQR/README.md)。小程序的图纸、色号、导出和扫码自检等能力经过源代码核对,宣传片中展示的是拍摄素材中的真实制作过程。实际扫码成功率会受摆珠精度、熨烫、光线和拍摄角度影响。
|
| 18 |
-
- **素材重建**:在仓库根目录执行 `uv pip install --target /tmp/surf-media imageio-ffmpeg pillow-heif edge-tts`,然后 `PYTHONPATH=/tmp/surf-media python studio/tools/build_assets.py`。该脚本会从原始素材生成 H.264 网页源镜头和原创合成器音轨,调用 Edge 在线语音合成服务生成旁白;仓库中已经包含预生成的音频、镜头和封面所用图片,正常观看不需要执行此步骤或访问语音服务。
|
| 19 |
-
- **本地预览**:运行 `python -m http.server 8000`,访问 `http://localhost:8000/`。请勿直接双击 HTML(浏览器本地文件限制会阻止模块与部分音频操作)。
|
| 20 |
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: 豆维 · 把想说的话亲手拼出来
|
| 3 |
emoji: 🧩
|
| 4 |
colorFrom: green
|
| 5 |
colorTo: yellow
|
|
|
|
| 8 |
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# 豆维|一份会说话的礼物
|
| 12 |
|
| 13 |
+
这次的交付主体是 **1 分 54 秒、30 帧/秒的完整宣传片**,而不是一套逐帧在浏览器中绘制的网页动效。用原始视频拍摄素材和豆维小程序代码核实过的功能,制作了 12 场叙事:创作初衷 → 首次扫码失败 → 写话选图 → 调整与扫码自检 → 色板与图纸 → 逐颗摆豆 → 熨烫揭开 → 实拍扫码 → 邀请体验。配有原创合成器配乐、节奏音效、中文配音和两套为画幅分别排版的画面内文字。
|
| 14 |
|
| 15 |
+
**在线直接看电影:** [ethscriptions-cut.static.hf.space](https://ethscriptions-cut.static.hf.space/)。网页只承担原生视频播放、选画幅、保存影片/封面和复制发布文案;播放无需进行耗时的 Canvas 解码、seek 或逐帧渲染。
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
+
| 成片 | 尺寸 | 编码 | 时长 |
|
| 18 |
+
|---|---:|---|---:|
|
| 19 |
+
| `studio/film/douwei-wide-114s.mp4` | 1920×1080 横屏 | H.264 / AAC, 30fps | 01:54 |
|
| 20 |
+
| `studio/film/douwei-portrait-114s.mp4` | 1080×1920 竖屏 | H.264 / AAC, 30fps | 01:54 |
|
| 21 |
+
|
| 22 |
+
抖音版在画面上方与下方预留文字安全区;想导出视频时,网页直接将**已完成的 MP4 成片**下载到浏览器本地(而不是重新编码,避免卡顿与画质损耗)。两张发布封面:`studio/assets/cover-landscape.png`、`studio/assets/cover-portrait.png`。
|
| 23 |
+
|
| 24 |
+
## 素材、来源和制作
|
| 25 |
+
|
| 26 |
+
- **真实手作与扫码实拍**:仓库根目录 `.MP4/.MOV/.HEIC/.PNG`;未用原有 `BeadQR/docs/promo/` 的成片。
|
| 27 |
+
- **微信小程序源码**:`BeadQR/`。功能按 `BeadQR/miniprogram/pages/index/index.js`、`utils/palette.js`、`utils/pdf.js` 等代码核对。色板可选 24/48/72/96/144/221/291 色、调整二维码位置与大小、扫码自检失败时一键切换扫码优先、导出带色号与用量的 A4/PDF 图纸。
|
| 28 |
+
- **分镜、合成、配音与音乐的可复现脚本**:`studio/tools/build_film.py`。生成时使用 FFmpeg、Pillow/HEIC、NumPy 和 Edge 在线语音;原声旁白片段和场景中间文件保存在被忽略的 `.build/`,发布使用的完整成片已入库。正常观看无需安装制作环境。
|
| 29 |
+
- **扫码说明**:实拍素材展示一次没扫出的过程和随后成功识别的过程,不能承诺任何作品在任意设备、光线、烫熨程度下都一定可扫;完成前后建议在小程序中自检。
|
| 30 |
+
|
| 31 |
+
本地预览:在仓库根目录运行 `python -m http.server 8000`,打开 `http://localhost:8000/`。制作工具链详见脚本开头的说明。
|
index.html
CHANGED
|
@@ -1,40 +1,19 @@
|
|
| 1 |
<!doctype html>
|
| 2 |
-
<html lang="zh-CN">
|
| 3 |
-
<
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
</
|
| 11 |
-
<
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
<div class="screen-side"><div class="screen-shell" id="screenShell"><canvas id="screen" width="1280" height="720" role="img" aria-label="豆维宣传片实时画面"></canvas><button class="center-play" id="centerPlay" aria-label="播放宣传片">▶ <span>点击播放 / 开启声音</span></button><div class="screen-watermark">DOUWEI <span>✳</span> ORIGINAL FILM</div></div>
|
| 21 |
-
<div class="player-controls"><button id="playBtn" class="icon-btn" aria-label="播放或暂停">▶</button><span id="currentTime" class="timecode">00:00</span><input id="seek" type="range" min="0" max="43" value="0" step="0.01" aria-label="视频进度" /><span class="timecode">00:43</span><button id="muteBtn" class="control-word" aria-label="切换静音">声音 开</button><button id="fullscreenBtn" class="icon-btn fullscreen" aria-label="全屏播放">⛶</button></div>
|
| 22 |
-
<p class="video-caption">真实拼豆实拍 × 小程序实录 × 原创合成配乐与中文旁白 <span>·</span> 所见即所导出</p>
|
| 23 |
-
</div>
|
| 24 |
-
<aside class="control-side"><div class="panel-top"><span class="section-n">DIRECTOR'S DESK</span><span class="small-pip">● LIVE</span></div><h3>选一个画幅,<br><em>把故事带走。</em></h3><p class="aside-intro">每一帧都在你的浏览器里实时合成。无需上传素材,无需服务器渲染。</p>
|
| 25 |
-
<fieldset class="format-switch"><legend>画幅比例 / FORMAT</legend><button data-format="landscape" class="format-option active" aria-pressed="true"><span class="ratio-icon wide"></span><span><strong>横屏 16:9</strong><small>哔哩哔哩 · 1920 × 1080</small></span><b>↗</b></button><button data-format="portrait" class="format-option" aria-pressed="false"><span class="ratio-icon tall"></span><span><strong>竖屏 9:16</strong><small>抖音 · 1080 × 1920</small></span><b>↗</b></button></fieldset>
|
| 26 |
-
<div class="output-details"><div><span>时长</span><strong>43 秒</strong></div><div><span>格式</span><strong>MP4 · H.264 + AAC</strong></div><div><span>制作方式</span><strong>浏览器本地编码</strong></div></div>
|
| 27 |
-
<button class="export-btn" id="exportBtn"><span>导出当前画幅 MP4</span><span>↗</span></button><p class="export-hint" id="exportHint">建议使用桌面版 Chrome / Edge;导出期间保持页面开启。</p><div class="export-progress" id="exportProgress" hidden><div class="export-progress-bar" id="exportProgressBar"></div></div>
|
| 28 |
-
<div class="safety-note"><span>✳</span><p>竖屏字幕和重点内容已避开顶部刘海与底部抖音操作区。导出文件无水印、无页面按钮。</p></div>
|
| 29 |
-
</aside>
|
| 30 |
-
</div>
|
| 31 |
-
</section>
|
| 32 |
-
<section class="chapters"><div class="section-heading"><span class="section-n">02 / THE STORY</span><h2>从一句话,到一份<em>可以收到的礼物。</em></h2></div><div class="chapter-grid"><button data-jump="0"><small>01 / THE IDEA</small><strong>藏进作品里的话</strong><span>00:00 — 00:08 ↗</span></button><button data-jump="8"><small>02 / THE DESIGN</small><strong>在豆维里,画出心意</strong><span>00:08 — 00:17 ↗</span></button><button data-jump="17"><small>03 / THE MAKING</small><strong>一颗一颗,慢慢拼好</strong><span>00:17 — 00:32 ↗</span></button><button data-jump="32"><small>04 / THE MOMENT</small><strong>扫一扫,就能读到</strong><span>00:32 — 00:43 ↗</span></button></div></section>
|
| 33 |
-
<section class="covers"><div class="section-heading"><span class="section-n">03 / THE COVERS</span><h2>第一眼,就让人<em>想点开。</em></h2><p>封面使用片中实拍和拼豆图纸;可下载高清 PNG,分别匹配横屏与竖屏。</p></div><div class="cover-grid"><div class="cover-card"><div class="cover-view wide-cover"><img id="coverWide" src="studio/assets/cover-landscape.png" alt="豆维 B 站横屏宣传封面" loading="lazy"></div><div class="cover-meta"><div><span>BILIBILI / 16:9</span><strong>横屏主视觉</strong></div><button data-cover="landscape">下载 1920 × 1080 PNG ↓</button></div></div><div class="cover-card portrait-card"><div class="cover-view tall-cover"><img id="coverTall" src="studio/assets/cover-portrait.png" alt="豆维抖音竖屏宣传封面" loading="lazy"></div><div class="cover-meta"><div><span>DOUYIN / 9:16</span><strong>竖屏主视觉</strong></div><button data-cover="portrait">下载 1080 × 1920 PNG ↓</button></div></div></div></section>
|
| 34 |
-
<section class="publish"><div class="section-heading"><span class="section-n">04 / READY TO PUBLISH</span><h2>视频做好了,<em>文案也准备好了。</em></h2></div><div class="publish-grid"><article class="publish-card"><div class="publish-top"><span>01 / 哔哩哔哩</span><span>16:9 · 横屏</span></div><h3>让手作,有话可说。</h3><label>视频标题<button data-copy="bili-title">复制标题 ↗</button></label><p id="bili-title">我把一句话拼进了拼豆里,没想到真的能扫出来!|豆维</p><label>视频简介<button data-copy="bili-desc">复制简介 ↗</button></label><p id="bili-desc">一颗一颗拼好,再用微信扫一扫——原来拼豆作品真的可以藏下一句话。这个视频记录了从在「豆维」里写下心意、生成拼豆图纸、对照色号制作,到完成作品并实际扫码的全过程。\n\n豆维是微信小程序:输入文字或链接,可选照片,生成可导出的拼豆图纸。实际扫码效果受拼豆工艺、光线和拍摄角度影响,建议制作前后先自检。\n\n#拼豆 #手工制作 #微信小程序 #DIY礼物 #二维码拼豆 #豆维</p><label>推荐标签<button data-copy="bili-tags">复制标签 ↗</button></label><p id="bili-tags">拼豆, 手工, 手工制作, 微信小程序, DIY礼物, 创意礼物, 豆维, 二维码拼豆</p></article><article class="publish-card"><div class="publish-top"><span>02 / 抖音</span><span>9:16 · 竖屏</span></div><h3>扫一下,心意就出现了。</h3><label>视频标题<button data-copy="dy-title">复制标题 ↗</button></label><p id="dy-title">拼豆居然能藏话?我亲手拼完用微信一扫,真的出来了✨</p><label>视频描述<button data-copy="dy-desc">复制描述 ↗</button></label><p id="dy-desc">把想说的话藏进拼豆里,一颗颗拼好,再用微信扫一扫读出来。图纸来自「豆维」微信小程序。你会把哪句话送给谁?💚 实际扫码效果与制作精度和光线有关,记得先自检。 #拼豆 #手工 #创意礼物 #微信小程序 #二维码拼豆 #豆维</p><label>推荐话题<button data-copy="dy-tags">复制话题 ↗</button></label><p id="dy-tags">#拼豆 #手工 #创意礼物 #微信小程序 #二维码拼豆 #豆维</p></article></div></section>
|
| 35 |
-
<footer><div><span class="brand-mark">✳</span><strong>豆维</strong><span>把一句话,拼成一份礼物。</span></div><p>真实手作 · 原创视听 · 本地导出 <span>© 2026 DOUWEI STUDIO</span></p></footer>
|
| 36 |
-
</main>
|
| 37 |
-
<audio id="soundtrack" preload="auto" src="studio/assets/soundtrack.m4a"></audio>
|
| 38 |
-
<script type="module" src="studio/app.js"></script>
|
| 39 |
-
</body>
|
| 40 |
-
</html>
|
|
|
|
| 1 |
<!doctype html>
|
| 2 |
+
<html lang="zh-CN"><head>
|
| 3 |
+
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover"><meta name="theme-color" content="#071710">
|
| 4 |
+
<title>豆维 · 一份会说话的礼物|1 分 54 秒完整宣传片</title>
|
| 5 |
+
<meta name="description" content="豆维微信小程序完整宣传片:真实手作与扫码实拍,十二段叙事,中文旁白与原创配乐。支持横屏、竖屏观看和保存 MP4。">
|
| 6 |
+
<link rel="stylesheet" href="studio/style.css"></head>
|
| 7 |
+
<body><main>
|
| 8 |
+
<header class="top"><a class="wordmark" href="#film">✳ <b>豆维</b><small>DOUWEI FILM</small></a><span>一份会说话的礼物 <i>·</i> THE FULL FILM</span><span class="runtime">01:54 <i> / </i> 30 FPS</span></header>
|
| 9 |
+
<section class="cinema" id="film" aria-label="豆维完整宣传片">
|
| 10 |
+
<div class="cinema-info"><div class="overline">A FILM ABOUT MAKING A MESSAGE</div><h1>把想说的话,<em>亲手拼出来。</em></h1><p>从一次没有扫出的尝试,到一份真正能被读到的手作。关于豆维,也关于把心意变成礼物的全过程。</p></div>
|
| 11 |
+
<div class="format-row"><div class="formats" role="group" aria-label="选择视频画幅"><button data-mode="wide" aria-pressed="true" class="chosen">▰ 哔哩哔哩横屏 <small>1920 × 1080</small></button><button data-mode="portrait" aria-pressed="false">▯ 抖音竖屏 <small>1080 × 1920</small></button></div><span class="quality">1080P · H.264 · AAC · 中文字幕</span></div>
|
| 12 |
+
<div class="stage" id="stage"><video id="movie" preload="metadata" controls playsinline webkit-playsinline poster="studio/assets/cover-landscape.png" src="studio/film/douwei-wide-114s.mp4" aria-label="豆维完整宣传片,1 分 54 秒"></video><button class="play-cover" id="startFilm"><span class="play-disc">▶</span><strong>播放完整宣传片</strong><small>戴上耳机,体验更好 · 01:54</small></button></div>
|
| 13 |
+
<div class="under"><div class="film-meta"><span class="pulse"></span><b>完整成片</b><span>12 段 · 1 分 54 秒 · 真实拍摄与制作过程</span></div><button id="saveFilm" class="primary">保存本版 MP4 <span>↗</span></button></div><p class="save-status" id="saveStatus" role="status" aria-live="polite"></p>
|
| 14 |
+
</section>
|
| 15 |
+
<section class="chapters"><div class="section-id">CHAPTERS / 四幕故事</div><div class="chapter-list"><button data-time="0"><span>01 萌芽</span><strong>一件会说话的手作,怎么诞生?</strong><small>00:00 →</small></button><button data-time="16"><span>02 设计</span><strong>写下文字、选张照片、生成图纸</strong><small>00:16 →</small></button><button data-time="62"><span>03 制作</span><strong>一颗颗拼好,烫平,轻轻揭开</strong><small>01:02 →</small></button><button data-time="94"><span>04 惊喜</span><strong>真实作品,用微信扫一扫</strong><small>01:34 →</small></button></div></section>
|
| 16 |
+
<section class="extras"><div class="section-id">TAKE IT WITH YOU / 让作品去到更多人面前</div><h2>影片、封面和发布文案,<br><em>都准备好了。</em></h2><div class="cover-links"><a href="studio/assets/cover-landscape.png" download="豆维-哔哩哔哩横屏封面.png"><img src="studio/assets/cover-landscape.png" alt="豆维横屏封面 1920 × 1080" loading="lazy"><span>下载哔哩哔哩封面 · 1920 × 1080 ↓</span></a><a href="studio/assets/cover-portrait.png" download="豆维-抖音竖屏封面.png"><img src="studio/assets/cover-portrait.png" alt="豆维竖屏封面 1080 × 1920" loading="lazy"><span>下载抖音封面 · 1080 × 1920 ↓</span></a></div>
|
| 17 |
+
<details class="copy"><summary>展开可复制的发布标题、简介与话题 <span>+</span></summary><div class="copy-grid"><article><h3>哔哩哔哩 · 横屏</h3><p id="b-title">我把一句话拼进拼豆里,最后真的用微信扫出来了|豆维完整制作记录</p><button data-copy="b-title">复制标题</button><p id="b-desc">从第一次扫不出来,到亲手拼完后真的被手机读到。这部 1 分 54 秒的影片记录了「豆维」微信小程序设计拼豆图纸、选择照片、对照色号制作、烫平和实拍扫码的全过程。\n\n豆维支持输入文字或链接、可选照片、调整图案与扫码模式,以及导出带色号和用量信息的拼豆图纸。实际扫码效果受制作精度、光线与角度影响,建议先使用自检功能。\n\n#拼豆 #手工制作 #创意礼物 #微信小程序 #豆维 #二维码拼豆</p><button data-copy="b-desc">复制简介</button><p id="b-tags">拼豆, 手工, DIY礼物, 微信小程序, 豆维, 拼豆图纸, 二维码拼豆, 创意礼物</p><button data-copy="b-tags">复制标签</button></article><article><h3>抖音 · 竖屏</h3><p id="d-title">拼豆里藏了句话,我亲手拼完一扫,真的读出来了✨</p><button data-copy="d-title">复制标题</button><p id="d-desc">写一句话,选张图,对照图纸一颗颗拼出来。手机一扫,那句话真的出现了。送礼物的时候,你会想藏哪一句?💚「豆维」微信小程序。制作前后记得先做扫码自检。 #拼豆 #手工 #DIY礼物 #微信小程序 #豆维 #二维码拼豆</p><button data-copy="d-desc">复制描述</button><p id="d-tags">#拼豆 #手工 #DIY礼物 #微信小程序 #豆维 #二维码拼豆</p><button data-copy="d-tags">复制话题</button></article></div></details></section>
|
| 18 |
+
<footer><strong>✳ 豆维</strong><span>可扫码的拼豆 · 看得见,也读得到。</span><small>以真实拍摄素材制作 · 镜头与扫码结果因实际条件而异</small></footer>
|
| 19 |
+
</main><script src="studio/player.js" defer></script></body></html>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
studio/app.js
DELETED
|
@@ -1,161 +0,0 @@
|
|
| 1 |
-
import { Muxer, ArrayBufferTarget } from './vendor/mp4-muxer.mjs';
|
| 2 |
-
|
| 3 |
-
const $ = (id) => document.getElementById(id);
|
| 4 |
-
const canvas = $('screen'), ctx = canvas.getContext('2d', { alpha:false });
|
| 5 |
-
const audio = $('soundtrack'), seekBar = $('seek');
|
| 6 |
-
const TOTAL = 43, FPS = 24;
|
| 7 |
-
const ASSET = 'studio/assets/';
|
| 8 |
-
const SCENES = [
|
| 9 |
-
{start:0,end:4,asset:'finished',label:'01 / THE IDEA',title:['有些话,','想亲手送给你。'],caption:'一颗颗拼出来的,不只是图案。',accent:'#e1f4b3'},
|
| 10 |
-
{start:4,end:8,asset:'scan',label:'02 / THE QUESTION',title:['如果作品','也能说话?'],caption:'用微信扫一扫,让心意有了回响。',accent:'#e5ef97'},
|
| 11 |
-
{start:8,end:13,asset:'app',label:'03 / THE APP',title:['先写下一句','想说的话。'],caption:'打开「豆维」,输入文字或链接。',accent:'#bdecb2'},
|
| 12 |
-
{start:13,end:17,asset:'pattern',label:'04 / THE DESIGN',title:['把照片和心意','画成一张图纸。'],caption:'生成可打印的拼豆图纸,带色号和用量。',accent:'#c9f1a5'},
|
| 13 |
-
{start:17,end:22,asset:'craft',label:'05 / THE HANDWORK',title:['一颗一颗,','把它拼出来。'],caption:'每一格,都是亲手完成的心意。',accent:'#ffe4a0'},
|
| 14 |
-
{start:22,end:27,asset:'heat',label:'06 / THE MAKING',title:['轻轻烫平,','让它成为作品。'],caption:'盖上烫纸,等拼豆慢慢定型。',accent:'#f4d6a7'},
|
| 15 |
-
{start:27,end:32,asset:'peel',label:'07 / THE REVEAL',title:['慢慢揭开,','惊喜就在眼前。'],caption:'从图纸,到一份真实的礼物。',accent:'#f7e5a9'},
|
| 16 |
-
{start:32,end:37,asset:'message',label:'08 / THE MAGIC',title:['扫一扫,','心意真的出现了。'],caption:'作品里的话,终于被读到。',accent:'#d4ef9f'},
|
| 17 |
-
{start:37,end:43,asset:'result',label:'09 / DOUWEI',title:['豆维。','让礼物有话可说。'],caption:'在微信搜索「豆维」,开始拼你的故事。',accent:'#dbf3a6'},
|
| 18 |
-
];
|
| 19 |
-
const videoNames = [...new Set(SCENES.filter(s=>!['pattern','craft','result'].includes(s.asset)).map(s=>s.asset))];
|
| 20 |
-
const videos = Object.fromEntries(videoNames.map(name=>{
|
| 21 |
-
const v=document.createElement('video');v.crossOrigin='anonymous';v.muted=true;v.playsInline=true;v.preload='auto';v.disablePictureInPicture=true;v.src=ASSET+name+'.mp4';v.load();return [name,v];
|
| 22 |
-
}));
|
| 23 |
-
const images = {};
|
| 24 |
-
for(const name of ['pattern','palette','craft','result','miniprogram-code']) {
|
| 25 |
-
const img=new Image();img.crossOrigin='anonymous';img.src=ASSET+name+(name==='miniprogram-code'?'.png':'.jpg');images[name]=img;
|
| 26 |
-
}
|
| 27 |
-
let format='landscape', playing=false, playStart=0, time=0, raf=0, exporting=false, currentScene=-1;
|
| 28 |
-
const clamp=(n,a,b)=>Math.max(a,Math.min(b,n));
|
| 29 |
-
const ease=n=>1-Math.pow(1-clamp(n,0,1),3);
|
| 30 |
-
const sceneAt=t=>Math.min(SCENES.length-1,SCENES.findIndex(s=>t<s.end)===-1?SCENES.length-1:SCENES.findIndex(s=>t<s.end));
|
| 31 |
-
const ready=(img)=>img&&img.complete&&img.naturalWidth;
|
| 32 |
-
function fitCover(c,im,x,y,w,h,zoom=1,dx=0,dy=0){if(!im||!(im.videoWidth||im.naturalWidth))return;let iw=im.videoWidth||im.naturalWidth,ih=im.videoHeight||im.naturalHeight;let scale=Math.max(w/iw,h/ih)*zoom,sw=w/scale,sh=h/scale,sx=(iw-sw)/2+dx,sy=(ih-sh)/2+dy;c.drawImage(im,clamp(sx,0,iw-sw),clamp(sy,0,ih-sh),sw,sh,x,y,w,h)}
|
| 33 |
-
function rounded(c,x,y,w,h,r){c.beginPath();c.roundRect(x,y,w,h,r)}
|
| 34 |
-
function text(c,str,x,y,size,color='#fff',weight=700,align='left'){c.fillStyle=color;c.font=`${weight} ${size}px 'Noto Sans SC', 'Microsoft YaHei', sans-serif`;c.textAlign=align;c.textBaseline='middle';c.fillText(str,x,y)}
|
| 35 |
-
function latin(c,str,x,y,size,color='#fff',weight=600,align='left'){c.fillStyle=color;c.font=`${weight} ${size}px 'DM Sans', Arial, sans-serif`;c.textAlign=align;c.textBaseline='middle';c.fillText(str,x,y)}
|
| 36 |
-
function gradient(c,x,y,w,h,stops){let g=c.createLinearGradient(x,y,x+w,y+h);stops.forEach(([p,col])=>g.addColorStop(p,col));return g}
|
| 37 |
-
function paint(t){
|
| 38 |
-
const s=SCENES[sceneAt(t)], local=t-s.start, p=clamp(local/(s.end-s.start),0,1), W=canvas.width,H=canvas.height,portrait=format==='portrait';
|
| 39 |
-
ctx.clearRect(0,0,W,H);ctx.fillStyle='#0b1914';ctx.fillRect(0,0,W,H);
|
| 40 |
-
let media=videos[s.asset]||images[s.asset];
|
| 41 |
-
if(portrait){
|
| 42 |
-
// Long-form mobile safe composition: top 220px (notch), bottom 390px (captions / controls).
|
| 43 |
-
if(media && (media.readyState>=2||ready(media)))fitCover(ctx,media,0,0,W,H,1.07+.03*p);
|
| 44 |
-
ctx.fillStyle=gradient(ctx,0,0,0,H,[[0,'#08160fed'],[.22,'#08160f99'],[.47,'#0a160f18'],[.68,'#08140b70'],[1,'#06140de9']]);ctx.fillRect(0,0,W,H);
|
| 45 |
-
ctx.fillStyle='#d5f1a1';ctx.fillRect(78,193,50,5);latin(ctx,'DOUWEI / A LITTLE FILM',147,195,20,'#e2f0d5',700);
|
| 46 |
-
ctx.globalAlpha=ease(local/.38);latin(ctx,s.label,82,308,24,s.accent,700);
|
| 47 |
-
s.title.forEach((line,i)=>text(ctx,line,77,420+i*103,78,'#f8f6eb',800));
|
| 48 |
-
ctx.globalAlpha=1;
|
| 49 |
-
if(s.asset==='app'){rounded(ctx,67,675,304,69,12);ctx.fillStyle='#d2f1aa';ctx.fill();text(ctx,'写一句话 →',92,710,32,'#112d21',800)}
|
| 50 |
-
if(s.asset==='pattern'){rounded(ctx,68,686,359,69,12);ctx.fillStyle='#e7f6c6';ctx.fill();text(ctx,'生成专属拼豆图纸',88,722,27,'#12301d',700)}
|
| 51 |
-
if(s.asset==='message'){ctx.save();ctx.strokeStyle='#dbf6a8';ctx.lineWidth=6;ctx.globalAlpha=.5+.45*Math.sin(local*5)**2;let cy=H*.58;for(let xx of [140,W-140])for(let yy of [cy-190,cy+190]){ctx.beginPath();ctx.moveTo(xx+(xx<W/2?65:-65),yy);ctx.lineTo(xx,yy);ctx.lineTo(xx,yy+(yy<cy?65:-65));ctx.stroke()}ctx.restore()}
|
| 52 |
-
if(s.asset==='result'){
|
| 53 |
-
ctx.fillStyle='#d4f0a8';rounded(ctx,74,992,932,340,30);ctx.fill();
|
| 54 |
-
text(ctx,'扫描小程序码',112,1080,53,'#132b1c',800);text(ctx,'开始拼你的故事 ↗',112,1160,38,'#284531',500);
|
| 55 |
-
if(ready(images['miniprogram-code']))ctx.drawImage(images['miniprogram-code'],780,1050,182,182);
|
| 56 |
-
}
|
| 57 |
-
ctx.fillStyle='#d8f3a0';ctx.fillRect(77,H-558,62,3);latin(ctx,`${String(sceneAt(t)+1).padStart(2,'0')} / 09`,154,H-556,21,'#dcecbf',700);
|
| 58 |
-
text(ctx,s.caption,77,H-505,30,'#f5f5e8',600);
|
| 59 |
-
latin(ctx,'DOUWEI · MADE WITH HEART',79,H-441,19,'#bdd3b0',600);
|
| 60 |
-
ctx.fillStyle='#ffffff3d';ctx.fillRect(78,H-396,W-156,3);ctx.fillStyle='#d5ed9e';ctx.fillRect(78,H-396,(W-156)*t/TOTAL,3);
|
| 61 |
-
} else {
|
| 62 |
-
if(media && (media.readyState>=2||ready(media))) {
|
| 63 |
-
ctx.save();ctx.filter='blur(65px) brightness(.38)';fitCover(ctx,media,-70,-70,W+140,H+140,1.14);ctx.restore();
|
| 64 |
-
ctx.fillStyle=gradient(ctx,0,0,W,0,[[0,'#061712f9'],[.49,'#0c2019ef'],[.79,'#0a1912a9'],[1,'#0b1b13a1']]);ctx.fillRect(0,0,W,H);
|
| 65 |
-
ctx.save();rounded(ctx,734,66,474,588,19);ctx.clip();fitCover(ctx,media,734,66,474,588,1.05+.025*p);ctx.restore();
|
| 66 |
-
ctx.strokeStyle='#d1ed9e5c';ctx.lineWidth=2;rounded(ctx,734,66,474,588,19);ctx.stroke();
|
| 67 |
-
}
|
| 68 |
-
ctx.fillStyle='#d3f39d';ctx.fillRect(73,73,37,3);latin(ctx,'D O U W E I / O R I G I N A L F I L M',123,74,13,'#d6edbd',700);
|
| 69 |
-
ctx.globalAlpha=ease(local/.36);latin(ctx,s.label,78,190,16,s.accent,700);
|
| 70 |
-
s.title.forEach((line,i)=>text(ctx,line,73,286+i*88,58,'#f8f7ec',800));ctx.globalAlpha=1;
|
| 71 |
-
ctx.fillStyle='#d9f1ae';ctx.fillRect(77,480,59,3);
|
| 72 |
-
text(ctx,s.caption,78,528,20,'#d8e5d5',500);
|
| 73 |
-
if(s.asset==='result') {
|
| 74 |
-
rounded(ctx,763,382,395,235,18);ctx.fillStyle='#d9f3ae';ctx.fill();
|
| 75 |
-
text(ctx,'微信搜索「豆维」',791,443,30,'#182c20',800);text(ctx,'开启你的拼豆故事 ↗',791,491,21,'#314930',500);
|
| 76 |
-
if(ready(images['miniprogram-code']))ctx.drawImage(images['miniprogram-code'],1038,507,100,100);
|
| 77 |
-
}
|
| 78 |
-
latin(ctx,`${String(sceneAt(t)+1).padStart(2,'0')} / 09`,78,657,14,'#c7dba9',700);
|
| 79 |
-
ctx.fillStyle='#ffffff44';ctx.fillRect(160,655,480,2);ctx.fillStyle='#d1f2a6';ctx.fillRect(160,655,480*t/TOTAL,2);
|
| 80 |
-
latin(ctx,'THE MAKING OF A MESSAGE',1177,688,12,'#bac9b2',600,'right');
|
| 81 |
-
}
|
| 82 |
-
}
|
| 83 |
-
function setScene(t, startPlayback){
|
| 84 |
-
const n=sceneAt(clamp(t,0,TOTAL-.01));
|
| 85 |
-
if(n===currentScene && !startPlayback)return;
|
| 86 |
-
for(const v of Object.values(videos))v.pause();
|
| 87 |
-
currentScene=n;
|
| 88 |
-
const scene=SCENES[n],v=videos[scene.asset];
|
| 89 |
-
if(v){const offset=clamp(t-scene.start,0,Math.max(0,(v.duration||scene.end-scene.start)-.1));if(Math.abs(v.currentTime-offset)>.15)v.currentTime=offset;if(startPlayback)v.play().catch(()=>{});}
|
| 90 |
-
}
|
| 91 |
-
function displayTime(t){$('currentTime').textContent=`${String(Math.floor(t/60)).padStart(2,'0')}:${String(Math.floor(t%60)).padStart(2,'0')}`;seekBar.value=String(t)}
|
| 92 |
-
function tick(){if(!playing)return;time=clamp((performance.now()-playStart)/1000,0,TOTAL);if(time>=TOTAL){pause();time=TOTAL;audio.pause();$('centerPlay').classList.remove('hidden')}else {if(sceneAt(time)!==currentScene)setScene(time,true);const s=SCENES[sceneAt(time)],v=videos[s.asset];if(v&&v.readyState>=2&&Math.abs(v.currentTime-(time-s.start))>.35)v.currentTime=clamp(time-s.start,0,Math.max(0,v.duration-.05));raf=requestAnimationFrame(tick)}paint(time);displayTime(time)}
|
| 93 |
-
function pause(){playing=false;cancelAnimationFrame(raf);audio.pause();for(const v of Object.values(videos))v.pause();$('playBtn').textContent='▶'}
|
| 94 |
-
function play(){if(exporting)return;if(playing){pause();return}if(time>=TOTAL-.1)time=0;setScene(time,true);audio.currentTime=time;audio.play().catch(()=>{ $('exportHint').textContent='请点击画面开启声音;如果浏览器自动播放受限,画面仍可观看。';});playStart=performance.now()-time*1000;playing=true;$('playBtn').textContent='Ⅱ';$('centerPlay').classList.add('hidden');tick()}
|
| 95 |
-
function jump(t){pause();time=clamp(t,0,TOTAL);setScene(Math.min(time,TOTAL-.01));const s=SCENES[sceneAt(Math.min(time,TOTAL-.01))],v=videos[s.asset];if(v){v.currentTime=clamp(time-s.start,0,Math.max(0,(v.duration||5)-.05));v.addEventListener('seeked',()=>paint(time),{once:true})}audio.currentTime=time;paint(time);displayTime(time);$('centerPlay').classList.remove('hidden')}
|
| 96 |
-
function setFormat(name){if(exporting)return;pause();format=name;canvas.width=name==='portrait'?1080:1280;canvas.height=name==='portrait'?1920:720;document.querySelectorAll('.format-option').forEach(b=>{b.classList.toggle('active',b.dataset.format===name);b.setAttribute('aria-pressed',b.dataset.format===name?'true':'false')});$('screenShell').classList.toggle('portrait-screen',name==='portrait');$('exportBtn').firstElementChild.textContent=`导出${name==='portrait'?'竖屏':'横屏'} MP4`;paint(time);renderCovers()}
|
| 97 |
-
function saveBlob(blob,filename){const url=URL.createObjectURL(blob),a=document.createElement('a');a.href=url;a.download=filename;a.click();setTimeout(()=>URL.revokeObjectURL(url),60000)}
|
| 98 |
-
function showExportStatus(message,ratio){$('exportHint').textContent=message;$('exportProgress').hidden=false;$('exportProgressBar').style.width=`${Math.round(ratio*100)}%`}
|
| 99 |
-
async function waitForSeek(v,target){if(v.readyState<1)await new Promise((resolve,reject)=>{v.addEventListener('loadedmetadata',resolve,{once:true});v.addEventListener('error',reject,{once:true})});target=clamp(target,0,Math.max(0,v.duration-.05));if(Math.abs(v.currentTime-target)<.016 && v.readyState>=2)return;await new Promise((resolve,reject)=>{let timer=setTimeout(()=>{cleanup();reject(new Error('素材视频定位超时。'))},12000);function cleanup(){clearTimeout(timer);v.removeEventListener('seeked',ok);v.removeEventListener('error',bad)}function ok(){cleanup();resolve()}function bad(){cleanup();reject(new Error('素材解码失败。'))}v.addEventListener('seeked',ok);v.addEventListener('error',bad);v.currentTime=target})}
|
| 100 |
-
async function exportVideo(){
|
| 101 |
-
if(exporting)return;
|
| 102 |
-
if(!window.VideoEncoder||!window.AudioEncoder||!window.AudioData){$('exportHint').textContent='当前浏览器暂不支持本地 H.264 + AAC 编码。请使用最新版桌面 Chrome / Edge 打开此页面。';return}
|
| 103 |
-
const portrait=format,w=portrait?1080:1920,h=portrait?1920:1080,fps=FPS,n=TOTAL*fps;
|
| 104 |
-
const config={codec:'avc1.42E028',width:w,height:h,bitrate:portrait?6400000:7500000,framerate:fps,avc:{format:'avc'}};
|
| 105 |
-
const aconfig={codec:'mp4a.40.2',sampleRate:48000,numberOfChannels:2,bitrate:160000};
|
| 106 |
-
try{
|
| 107 |
-
let vs=await VideoEncoder.isConfigSupported(config),as=await AudioEncoder.isConfigSupported(aconfig);
|
| 108 |
-
if(!vs.supported||!as.supported)throw new Error('本机不支持 H.264 或 AAC 硬件/软件编码,请换用最新版桌面 Chrome / Edge。');
|
| 109 |
-
exporting=true;pause();$('exportBtn').disabled=true;showExportStatus('准备素材和音轨…',0);
|
| 110 |
-
const muxer=new Muxer({target:new ArrayBufferTarget(),video:{codec:'avc',width:w,height:h},audio:{codec:'aac',sampleRate:48000,numberOfChannels:2},fastStart:'in-memory'});
|
| 111 |
-
let encoderError=null;
|
| 112 |
-
const ve=new VideoEncoder({output:(chunk,meta)=>muxer.addVideoChunk(chunk,meta),error:e=>encoderError=e});ve.configure(config);
|
| 113 |
-
const ae=new AudioEncoder({output:(chunk,meta)=>muxer.addAudioChunk(chunk,meta),error:e=>encoderError=e});ae.configure(aconfig);
|
| 114 |
-
const audioContext=new AudioContext({sampleRate:48000});
|
| 115 |
-
const decoded=await audioContext.decodeAudioData(await (await fetch(ASSET+'soundtrack.m4a')).arrayBuffer());await audioContext.close();
|
| 116 |
-
const totalSamples=Math.min(Math.round(TOTAL*48000),decoded.length);
|
| 117 |
-
for(let pos=0;pos<totalSamples;pos+=1024){let frames=Math.min(1024,totalSamples-pos),buf=new Float32Array(frames*2);for(let ch=0;ch<2;ch++)buf.set(decoded.getChannelData(Math.min(ch,decoded.numberOfChannels-1)).subarray(pos,pos+frames),ch*frames);let packet=new AudioData({format:'f32-planar',sampleRate:48000,numberOfFrames:frames,numberOfChannels:2,timestamp:Math.round(pos*1000000/48000),data:buf});ae.encode(packet);packet.close();if(ae.encodeQueueSize>25)await ae.flush()}
|
| 118 |
-
await ae.flush();ae.close();
|
| 119 |
-
// Canvas and video decoders remain inside the browser; no generated video is sent to a server.
|
| 120 |
-
const exportCanvas=document.createElement('canvas');exportCanvas.width=w;exportCanvas.height=h;
|
| 121 |
-
const ectx=exportCanvas.getContext('2d',{alpha:false});
|
| 122 |
-
// Render in the preview coordinate system, then scale to the selected publication size.
|
| 123 |
-
for(let i=0;i<n;i++){
|
| 124 |
-
if(encoderError)throw encoderError;
|
| 125 |
-
const t=i/fps,s=SCENES[sceneAt(t)],v=videos[s.asset];
|
| 126 |
-
if(v)await waitForSeek(v,t-s.start);
|
| 127 |
-
paint(t);
|
| 128 |
-
ectx.drawImage(canvas,0,0,w,h);
|
| 129 |
-
let frame=new VideoFrame(exportCanvas,{timestamp:Math.round(i*1000000/fps),duration:Math.round(1000000/fps)});
|
| 130 |
-
ve.encode(frame,{keyFrame:i%48===0});frame.close();
|
| 131 |
-
if(ve.encodeQueueSize>6)await ve.flush();
|
| 132 |
-
if(i%24===0){showExportStatus(`浏览器本地渲染 ${Math.round(100*i/n)}% · 请保持页面开启`,i/n);await new Promise(r=>setTimeout(r,0))}
|
| 133 |
-
}
|
| 134 |
-
await ve.flush();ve.close();if(encoderError)throw encoderError;
|
| 135 |
-
showExportStatus('正在封装 MP4 文件…',.99);muxer.finalize();
|
| 136 |
-
saveBlob(new Blob([muxer.target.buffer],{type:'video/mp4'}),`豆维-宣传片-${portrait?'抖音竖屏1080x1920':'B站横屏1920x1080'}.mp4`);
|
| 137 |
-
showExportStatus('导出完成!文件已保存到浏览器下载目录。',1);
|
| 138 |
-
}catch(e){console.error('MP4 export failed',e);$('exportHint').textContent=`导出失败:${e?.message||e}。可尝试更新 Chrome / Edge,并关闭其他占用内存的页面。`;$('exportProgress').hidden=true}
|
| 139 |
-
finally{exporting=false;$('exportBtn').disabled=false;paint(time)}
|
| 140 |
-
}
|
| 141 |
-
// A distinct still-cover art direction, rendered at full publication dimensions.
|
| 142 |
-
function drawCover(mode){let portrait=mode==='portrait',c=document.createElement('canvas');c.width=portrait?1080:1920;c.height=portrait?1920:1080;let g=c.getContext('2d'),W=c.width,H=c.height;
|
| 143 |
-
g.fillStyle='#0e241b';g.fillRect(0,0,W,H);
|
| 144 |
-
if(portrait){if(ready(images.result))fitCover(g,images.result,0,245,W,1400,1.03);g.fillStyle=gradient(g,0,0,0,H,[[0,'#07160ffb'],[.29,'#081b1055'],[.55,'#07150a22'],[.73,'#08190c9d'],[1,'#06160ffb']]);g.fillRect(0,0,W,H);latin(g,'DOUWEI / MADE WITH HEART',82,195,24,'#dfedca',700);text(g,'拼豆里,',76,387,94,'#f8f7eb',800);text(g,'真的能',76,508,94,'#f8f7eb',800);text(g,'藏下一句话。',76,629,88,'#ddf4a8',800);rounded(g,72,1335,936,240,26);g.fillStyle='#d4efaa';g.fill();text(g,'一扫就能读到心意',101,1423,51,'#15301e',800);text(g,'豆维 · 可扫码的拼豆',101,1504,36,'#456147',600);g.fillStyle='#d5f3a5';g.fillRect(79,H-241,80,5);latin(g,'THE MAKING OF A MESSAGE',80,H-197,25,'#f1f4e2',600)}
|
| 145 |
-
else{if(ready(images.result))fitCover(g,images.result,925,0,995,H,1.03);g.fillStyle=gradient(g,0,0,W,0,[[0,'#0a2119'],[.41,'#0c2219fa'],[.65,'#0b2114ba'],[1,'#0b211422']]);g.fillRect(0,0,W,H);g.fillStyle='#d9f3aa';g.fillRect(104,125,58,5);latin(g,'D O U W E I / O R I G I N A L F I L M',184,129,23,'#e5f0d3',700);text(g,'我把一句话,',97,402,104,'#f8f9ee',800);text(g,'拼进了',97,536,109,'#f8f9ee',800);text(g,'拼豆里。',97,673,113,'#ddf4a8',800);text(g,'微信一扫,真的能读出来。',102,766,39,'#f4f5e7',600);latin(g,'A HANDMADE MESSAGE YOU CAN ACTUALLY READ',104,971,22,'#c9daae',600)}
|
| 146 |
-
return c;
|
| 147 |
-
}
|
| 148 |
-
function renderCovers(){for(let [name,id] of [['landscape','coverWide'],['portrait','coverTall']]){let c=drawCover(name);$(id).src=c.toDataURL('image/png')}}
|
| 149 |
-
$('playBtn').addEventListener('click',play);$('centerPlay').addEventListener('click',play);$('screen').addEventListener('click',play);
|
| 150 |
-
$('muteBtn').addEventListener('click',()=>{audio.muted=!audio.muted;$('muteBtn').textContent=audio.muted?'声音 关':'声音 开'});
|
| 151 |
-
$('fullscreenBtn').addEventListener('click',()=>{if(document.fullscreenElement)document.exitFullscreen();else $('screenShell').requestFullscreen?.()});
|
| 152 |
-
seekBar.addEventListener('input',()=>jump(+seekBar.value));
|
| 153 |
-
document.querySelectorAll('.format-option').forEach(b=>b.addEventListener('click',()=>setFormat(b.dataset.format)));
|
| 154 |
-
document.querySelectorAll('[data-jump]').forEach(b=>b.addEventListener('click',()=>{jump(+b.dataset.jump);$('screenShell').scrollIntoView({behavior:'smooth',block:'center'})}));
|
| 155 |
-
$('exportBtn').addEventListener('click',exportVideo);
|
| 156 |
-
document.querySelectorAll('[data-cover]').forEach(b=>b.addEventListener('click',()=>{let c=drawCover(b.dataset.cover);c.toBlob(blob=>{if(blob)saveBlob(blob,`豆维-${b.dataset.cover==='portrait'?'抖音竖屏':'B站横屏'}-封面.png`)},'image/png')}));
|
| 157 |
-
document.querySelectorAll('[data-copy]').forEach(b=>b.addEventListener('click',async()=>{let content=$(b.dataset.copy).textContent.replaceAll('\\n','\n').trim();try{await navigator.clipboard.writeText(content)}catch{let el=document.createElement('textarea');el.value=content;document.body.append(el);el.select();document.execCommand('copy');el.remove()}let old=b.textContent;b.textContent='已复制 ✓';setTimeout(()=>b.textContent=old,1800)}));
|
| 158 |
-
window.addEventListener('keydown',e=>{if(e.code==='Space'&&!['INPUT','TEXTAREA','BUTTON'].includes(document.activeElement.tagName)){e.preventDefault();play()}});
|
| 159 |
-
for(let img of Object.values(images))img.addEventListener('load',()=>{paint(time);renderCovers()});
|
| 160 |
-
for(let v of Object.values(videos))v.addEventListener('loadeddata',()=>{if(!playing)paint(time)});
|
| 161 |
-
paint(0);renderCovers();displayTime(0);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/finished.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:a1ff835b2015599d4bc62818f2eeb1691f16d7d568c2bda301cb6697468be563
|
| 3 |
-
size 1047000
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/message.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:f084324118d8fe320b92ce6a4b0d73afc4c16b77cc3859ce53f79f4e8b325375
|
| 3 |
-
size 54085
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/miniprogram-code.png
DELETED
Git LFS Details
|
studio/assets/palette.jpg
DELETED
Git LFS Details
|
studio/assets/pattern.jpg
DELETED
Git LFS Details
|
studio/assets/peel.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:0c2c800e2841d49ba94a623c918ba5a0feb529212fda353e0346b1121c8d527b
|
| 3 |
-
size 670164
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/result.jpg
DELETED
Git LFS Details
|
studio/assets/scan.mp4
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:d84b21b458ef4b137720bc5c32bdacc863bb76bfacce94e5c341d3d70f4081de
|
| 3 |
-
size 495765
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/soundtrack.m4a
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:7133373bdeebefc60a263b35657ae46a7f07cd85de2ed0b3a5d51064132774c2
|
| 3 |
-
size 869351
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-0.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:e2ff9331ded5749160ef50afce136f4d44943be685906ec6b1f38c4392360213
|
| 3 |
-
size 19296
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-1.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:3f05f73fbad222d85991efcbe65f1809ab5c6c7c0cbded6a502cb22112aa4854
|
| 3 |
-
size 17136
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-2.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:6bf1ee4b9ab3fcea36fbbf26e7abd02e3af6c20c611cbd3d12ddd7301094d8db
|
| 3 |
-
size 15984
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-3.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:39717db9b9e144173f595495496e74e02e6b3a47655db88c395d83add16066b2
|
| 3 |
-
size 24480
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-4.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:05f359b23fed244a5e2cea8d8f6930f9196f7bdb7f91504fdf6ec43c733aac5c
|
| 3 |
-
size 20448
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-5.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:ac3ff481e31b0de6542a3afabbef026b07e52cf4a465e1e5b642879189a2582f
|
| 3 |
-
size 14256
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-6.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:0ef802181ce05c8ababaf55f1b1520d78a737ce7374bb9bfc1d57b0d9d0c7da1
|
| 3 |
-
size 13680
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-7.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:db15a3a5a389c0688bfcda16390fde0b55a7375e3772522aec0dee5938164ad2
|
| 3 |
-
size 23328
|
|
|
|
|
|
|
|
|
|
|
|
studio/assets/voice-8.mp3
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:dcecace6799ce255d5115a3e97f9e5e9d7b944fb9c55ed8238c785f06c025a62
|
| 3 |
-
size 25632
|
|
|
|
|
|
|
|
|
|
|
|
studio/{assets/app.mp4 → film/douwei-portrait-114s.mp4}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3cde93027eea3f58d39fd79a07e920c21a41541a3e01cf1aba61b318fda90926
|
| 3 |
+
size 16905438
|
studio/{assets/craft.jpg → film/douwei-wide-114s.mp4}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d813550d6a40a5889589ecb443e144ac0a7180846a7f43bbc25eb5ae18b1c40b
|
| 3 |
+
size 16440502
|
studio/{assets/heat.mp4 → film/soundtrack-114s.m4a}
RENAMED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3c6ec58acd8186294b5eafbaa852106e0db315396f4e88fe2c8ccd461bbf0375
|
| 3 |
+
size 2767560
|
studio/player.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// A film player, not a frame-by-frame canvas render: native hardware video decoding stays fluid.
|
| 2 |
+
const movie=document.querySelector('#movie');
|
| 3 |
+
const start=document.querySelector('#startFilm');
|
| 4 |
+
const stage=document.querySelector('#stage');
|
| 5 |
+
const save=document.querySelector('#saveFilm');
|
| 6 |
+
const status=document.querySelector('#saveStatus');
|
| 7 |
+
const files={wide:'studio/film/douwei-wide-114s.mp4',portrait:'studio/film/douwei-portrait-114s.mp4'};
|
| 8 |
+
const covers={wide:'studio/assets/cover-landscape.png',portrait:'studio/assets/cover-portrait.png'};
|
| 9 |
+
let mode='wide';
|
| 10 |
+
function switchMode(next){
|
| 11 |
+
if(next===mode)return;
|
| 12 |
+
const wasPlaying=!movie.paused;
|
| 13 |
+
const current=movie.currentTime||0;
|
| 14 |
+
mode=next;
|
| 15 |
+
movie.pause();movie.src=files[next];movie.poster=covers[next];movie.load();
|
| 16 |
+
stage.classList.toggle('portrait',next==='portrait');
|
| 17 |
+
document.querySelectorAll('[data-mode]').forEach(b=>{b.classList.toggle('chosen',b.dataset.mode===next);b.setAttribute('aria-pressed',String(b.dataset.mode===next))});
|
| 18 |
+
const resume=()=>{if(current>0)movie.currentTime=Math.min(current,113.9);if(wasPlaying)movie.play().catch(()=>{});movie.removeEventListener('loadedmetadata',resume)};
|
| 19 |
+
movie.addEventListener('loadedmetadata',resume);
|
| 20 |
+
start.classList.toggle('is-hidden',current>0);
|
| 21 |
+
status.textContent='';
|
| 22 |
+
}
|
| 23 |
+
document.querySelectorAll('[data-mode]').forEach(button=>button.addEventListener('click',()=>switchMode(button.dataset.mode)));
|
| 24 |
+
start.addEventListener('click',async()=>{try{await movie.play();start.classList.add('is-hidden')}catch{status.textContent='浏览器阻止自动播放,请点击视频自带的播放键。'}});
|
| 25 |
+
movie.addEventListener('play',()=>start.classList.add('is-hidden'));
|
| 26 |
+
movie.addEventListener('ended',()=>start.classList.remove('is-hidden'));
|
| 27 |
+
document.querySelectorAll('[data-time]').forEach(b=>b.addEventListener('click',()=>{movie.currentTime=Number(b.dataset.time);start.classList.add('is-hidden');movie.play().catch(()=>{});stage.scrollIntoView({behavior:'smooth',block:'center'})}));
|
| 28 |
+
save.addEventListener('click',async()=>{
|
| 29 |
+
if(save.disabled)return;
|
| 30 |
+
save.disabled=true;status.textContent='正在保存完整影片,请保持页面开启…';
|
| 31 |
+
try{
|
| 32 |
+
const response=await fetch(files[mode]);if(!response.ok)throw new Error(`下载服务返回 ${response.status}`);
|
| 33 |
+
const total=Number(response.headers.get('Content-Length'))||0;
|
| 34 |
+
const reader=response.body?.getReader();let blob;
|
| 35 |
+
if(reader){const parts=[];let size=0;while(true){const {done,value}=await reader.read();if(done)break;parts.push(value);size+=value.byteLength;if(total)status.textContent=`影片保存中 ${Math.round(size/total*100)}% · ${mode==='portrait'?'竖屏':'横屏'} MP4`;}
|
| 36 |
+
blob=new Blob(parts,{type:'video/mp4'});
|
| 37 |
+
}else blob=await response.blob();
|
| 38 |
+
const url=URL.createObjectURL(blob);const a=document.createElement('a');a.href=url;a.download=`豆维-完整宣传片-${mode==='portrait'?'抖音竖屏1080x1920':'B站横屏1920x1080'}-1分54秒.mp4`;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),120000);
|
| 39 |
+
status.textContent='已交给浏览器保存。若未弹出下载,请检查浏览器下载权限。';
|
| 40 |
+
}catch(e){console.error(e);status.textContent=`保存失败:${e.message}。可以长按影片或使用浏览器下载功能重试。`}
|
| 41 |
+
finally{save.disabled=false}
|
| 42 |
+
});
|
| 43 |
+
document.querySelectorAll('[data-copy]').forEach(b=>b.addEventListener('click',async()=>{const value=document.getElementById(b.dataset.copy).textContent.replaceAll('\\n','\n').trim();try{await navigator.clipboard.writeText(value)}catch{const el=document.createElement('textarea');el.value=value;document.body.append(el);el.select();document.execCommand('copy');el.remove()}const old=b.textContent;b.textContent='已复制 ✓';setTimeout(()=>b.textContent=old,1800)}));
|
| 44 |
+
// LFS may redirect assets to a CDN; turn cover art into a same-origin Blob URL to ensure download, not navigation.
|
| 45 |
+
document.querySelectorAll('.cover-links a').forEach(link=>link.addEventListener('click',async(event)=>{
|
| 46 |
+
event.preventDefault();try{const r=await fetch(link.href);if(!r.ok)throw new Error(String(r.status));const url=URL.createObjectURL(await r.blob());const a=document.createElement('a');a.href=url;a.download=link.download;document.body.append(a);a.click();a.remove();setTimeout(()=>URL.revokeObjectURL(url),60000)}catch(e){status.textContent=`封面保存失败:${e.message}`}
|
| 47 |
+
}));
|
| 48 |
+
if(matchMedia('(max-width: 720px) and (orientation: portrait)').matches)switchMode('portrait');
|
studio/style.css
CHANGED
|
@@ -1,2 +1 @@
|
|
| 1 |
-
@font-face{font-family:
|
| 2 |
-
:root{font-family:'DM Sans','Noto Sans SC',system-ui,sans-serif;color:#f4f3e9;background:#091512;font-synthesis:none}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;overflow-x:hidden}button{font:inherit;cursor:pointer}button:focus-visible,input:focus-visible,a:focus-visible{outline:2px solid #c8fd76;outline-offset:3px}::selection{background:#dbf28f;color:#102217}.page-glow{position:absolute;inset:0 0 auto;height:940px;pointer-events:none;background:radial-gradient(ellipse 55% 37% at 76% 27%,#37775931,transparent 85%),radial-gradient(ellipse 40% 30% at 8% 15%,#a2b64017,transparent 90%)}main,.site-header{position:relative;max-width:1480px;padding-inline:clamp(20px,5vw,80px);margin-inline:auto}.site-header{height:91px;display:flex;justify-content:space-between;align-items:center;border-bottom:1px solid #ffffff1d}.brand{color:#fff;text-decoration:none;display:inline-flex;gap:13px;align-items:center;font-size:25px;font-weight:800;letter-spacing:-1px}.brand-mark{color:#cdf389;font-size:32px;line-height:1}.brand-en{font-size:11px;font-weight:600;letter-spacing:2px;color:#8faaa0}.header-end{color:#8faaa0;font-size:10px;font-weight:700;letter-spacing:1.55px}.edition{margin-left:34px;color:#d2dfc8}.live-pip,.small-pip{color:#c6ed87}.live-pip{display:inline-block;background:#c6ed87;width:7px;height:7px;border-radius:50%;margin-right:8px;box-shadow:0 0 15px #b5f67a}.eyebrow,.section-n{font-size:11px;color:#c9ed95;letter-spacing:2.3px;font-weight:700}.hero-kicker{display:flex;align-items:center;gap:14px;margin:62px 0 22px}.hero-kicker .line{display:block;width:23px;height:1px;background:#c9ed95}.eyebrow-en{margin-left:11px;color:#738a80;font-size:10px}.hero-heading{display:flex;justify-content:space-between;align-items:center}.hero h1{font-size:clamp(47px,6vw,91px);font-weight:800;line-height:1.2;letter-spacing:-4px;margin:0 0 22px}.hero em,.section-heading em,.control-side h3 em{font-style:normal;color:#cbeb9c}.hero p{color:#a2b5a9;margin:0 0 72px;font-size:15px;line-height:1.9}.hero-seal{width:144px;height:144px;border:1px solid #67876a80;border-radius:50%;display:flex;align-items:center;justify-content:center;transform:rotate(13deg);position:relative;color:#cfe5b0;letter-spacing:1px;font-size:15px;line-height:1.08;font-weight:800}.seal-dot{position:absolute;right:10px;top:23px;color:#d2f296;font-size:25px}.studio{border-top:1px solid #ffffff2b}.studio-top{display:flex;justify-content:space-between;align-items:end;margin:28px 0}.studio-top h2{font-size:25px;letter-spacing:-.6px;margin:10px 0 0}.duration-label{font-size:10px;color:#a5b8ab;letter-spacing:1.5px}.duration-label i{display:inline-block;width:4px;height:4px;border-radius:50%;background:#d3edb4;margin:2px 6px}.workspace{display:grid;grid-template-columns:minmax(0,1.75fr) minmax(310px,.85fr);gap:19px}.screen-side{min-width:0}.screen-shell{position:relative;background:#050d0b;aspect-ratio:16/9;display:grid;place-items:center;overflow:hidden;border:1px solid #2c493a;border-radius:8px;box-shadow:0 22px 80px #0006}.screen-shell.portrait-screen{min-height:620px;aspect-ratio:auto}.screen-shell canvas{width:100%;height:100%;object-fit:contain;display:block}.screen-shell.portrait-screen canvas{width:auto;height:100%;max-width:100%}.screen-watermark{position:absolute;left:18px;top:14px;letter-spacing:2px;font-size:9px;color:#e9f5dc90;pointer-events:none}.screen-watermark span{color:#d3ec8c}.center-play{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);border:1px solid #ffffff80;background:#07130fa6;backdrop-filter:blur(8px);width:96px;height:96px;border-radius:100%;color:#e4fbb1;font-size:23px;padding-left:5px;display:grid;place-content:center;gap:5px;transition:.2s}.center-play span{font-size:9px;white-space:nowrap;color:#d9edc8;margin-left:-5px;letter-spacing:1px}.center-play:hover{background:#1d452f;transform:translate(-50%,-50%) scale(1.06)}.center-play.hidden{display:none}.player-controls{display:flex;align-items:center;gap:14px;padding:15px 3px 10px}.icon-btn,.control-word{border:0;background:transparent;color:#ecf2df}.icon-btn{font-size:18px;width:28px}.timecode{font-variant-numeric:tabular-nums;color:#c2d0c5;font-size:11px}.player-controls input{flex:1;accent-color:#cdef9c;height:3px;cursor:pointer}.control-word{font-size:11px;white-space:nowrap}.video-caption{color:#849d8e;font-size:11px;margin:8px 0 28px;letter-spacing:.3px}.video-caption span{color:#badb95;padding-inline:6px}.control-side{background:#10211b;border:1px solid #284436;border-radius:8px;padding:clamp(19px,2.5vw,31px);display:flex;flex-direction:column}.panel-top{display:flex;justify-content:space-between}.small-pip{font-size:10px;letter-spacing:1px}.control-side h3{font-size:clamp(24px,2.55vw,38px);line-height:1.25;margin:27px 0 12px;letter-spacing:-1px}.aside-intro{font-size:12px;color:#9db3a3;line-height:1.9;margin:0 0 26px}.format-switch{margin:0;padding:0;border:0}.format-switch legend{font-size:10px;color:#a6c2a6;letter-spacing:2px;margin-bottom:12px}.format-option{display:flex;align-items:center;width:100%;background:#10231b;border:1px solid #385041;border-radius:6px;padding:12px 13px;margin-bottom:9px;text-align:left;color:#f6f9ef;gap:12px;transition:.2s}.format-option.active{border-color:#c5e996;background:#263c2d}.format-option:hover{border-color:#b2d78d}.format-option strong{display:block;font-size:13px}.format-option small{display:block;font-size:10px;color:#9aac9d;margin-top:4px}.format-option b{margin-left:auto;color:#c2e6a5;font-weight:400}.ratio-icon{width:28px;height:19px;border:2px solid #b5d296;border-radius:2px;flex:none}.ratio-icon.tall{width:16px;height:28px;margin-inline:6px}.output-details{margin:16px 0 17px}.output-details div{border-bottom:1px solid #ffffff1a;display:flex;justify-content:space-between;padding:9px 0;font-size:11px}.output-details span{color:#899e8e}.output-details strong{font-weight:500;color:#dae6d3}.export-btn{background:#d3f3a5;color:#122019;border:0;border-radius:5px;padding:17px;display:flex;justify-content:space-between;font-size:13px;font-weight:800;transition:.2s}.export-btn:hover{background:#e6ffc3}.export-btn:disabled{opacity:.55;cursor:wait}.export-hint{font-size:10px;color:#8ca28e;line-height:1.6;margin:11px 0 18px;min-height:29px}.export-progress{height:5px;background:#294535;margin-bottom:15px;border-radius:5px;overflow:hidden}.export-progress-bar{height:100%;width:0;background:#c8ed8c;transition:width .2s}.safety-note{display:flex;align-items:start;gap:10px;border-top:1px solid #ffffff20;padding-top:16px;margin-top:auto;color:#a4bbab;font-size:10px;line-height:1.8}.safety-note span{color:#d4efa5;font-size:17px}.safety-note p{margin:0}.section-heading{margin:0 0 29px}.section-heading h2{font-size:clamp(27px,3vw,44px);line-height:1.3;letter-spacing:-1.7px;margin:16px 0}.section-heading p{font-size:13px;color:#94a999}.chapters,.covers,.publish{padding-top:105px}.chapter-grid{display:grid;grid-template-columns:repeat(4,1fr);border-top:1px solid #54705a;border-bottom:1px solid #54705a}.chapter-grid button{background:none;color:#ebf1e5;text-align:left;border:0;border-right:1px solid #335344;padding:25px 20px 30px;transition:.2s}.chapter-grid button:last-child{border:0}.chapter-grid button:hover{background:#1f3929}.chapter-grid small{font-size:10px;letter-spacing:1.8px;color:#cae99b}.chapter-grid strong{display:block;margin:33px 0 23px;font-size:15px}.chapter-grid span{font-size:10px;color:#8da796}.cover-grid{display:grid;grid-template-columns:1.4fr .8fr;gap:20px;align-items:end}.cover-card{min-width:0}.cover-view{background:#17241a;border-radius:8px;overflow:hidden;border:1px solid #426046;display:grid;place-items:center}.cover-view img{display:block;width:100%;height:100%;object-fit:cover}.wide-cover{aspect-ratio:16/9}.tall-cover{aspect-ratio:9/10;max-height:430px}.tall-cover img{object-fit:cover;object-position:center 35%}.cover-meta{display:flex;justify-content:space-between;align-items:center;padding:19px 0;border-bottom:1px solid #45614c}.cover-meta span{display:block;color:#9bb592;font-size:10px;letter-spacing:1.6px;margin-bottom:4px}.cover-meta strong{font-size:14px}.cover-meta button,.publish-card button{background:transparent;border:0;color:#cdef95;font-size:11px;font-weight:700}.cover-meta button:hover,.publish-card button:hover{text-decoration:underline}.publish-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px}.publish-card{border:1px solid #3b5943;background:#10221c;border-radius:7px;padding:26px 29px}.publish-top{display:flex;justify-content:space-between;color:#bde590;font-size:10px;letter-spacing:1px}.publish-top span:last-child{color:#849d87}.publish-card h3{font-size:21px;margin:26px 0 27px}.publish-card label{display:flex;justify-content:space-between;align-items:center;font-size:11px;color:#87aa89;border-top:1px solid #314a39;padding-top:16px}.publish-card p{white-space:pre-line;margin:10px 0 24px;color:#dce7d8;line-height:1.9;font-size:12px;overflow-wrap:anywhere}footer{border-top:1px solid #456449;margin-top:110px;padding:28px 0 40px;display:flex;justify-content:space-between;align-items:center;color:#c3d6bc}footer div{display:flex;gap:14px;align-items:center}footer strong{font-size:20px;color:#fff}footer div span:last-child,footer p{font-size:11px;color:#849e88}footer p span{margin-left:30px}@media(max-width:1000px){.workspace{grid-template-columns:1fr}.control-side{max-width:none}.cover-grid{grid-template-columns:1fr 1fr}.chapter-grid{grid-template-columns:repeat(2,1fr)}.chapter-grid button:nth-child(2){border:0}.chapter-grid button:nth-child(-n+2){border-bottom:1px solid #335344}}@media(max-width:650px){.site-header{height:68px}.brand{font-size:20px}.brand-en,.header-end,.hero-seal,.eyebrow-en,.duration-label{display:none}.hero-kicker{margin-top:47px}.hero h1{font-size:clamp(40px,9.5vw,57px);letter-spacing:-2.5px}.hero p{margin-bottom:54px;font-size:13px}.studio-top h2{font-size:20px}.screen-shell.portrait-screen{min-height:0;height:min(72vh,730px)}.video-caption{font-size:10px}.chapters,.covers,.publish{padding-top:76px}.chapter-grid strong{margin:20px 0}.cover-grid,.publish-grid{grid-template-columns:1fr}.tall-cover{aspect-ratio:9/12;max-height:610px}.cover-meta{gap:10px}.cover-meta button{font-size:10px}.publish-card{padding:20px}footer{margin-top:80px;display:block}footer p span{display:block;margin:10px 0 0}body{padding-bottom:env(safe-area-inset-bottom)}.screen-watermark{font-size:7px}}@media(prefers-reduced-motion:reduce){*{scroll-behavior:auto!important;transition:none!important}}
|
|
|
|
| 1 |
+
@font-face{font-family:Douwei;src:url('assets/NotoSansSC-subset.woff2') format('woff2');font-display:swap;font-weight:100 900}*{box-sizing:border-box}html{scroll-behavior:smooth}body{margin:0;background:#081911;color:#f6f6e9;font-family:Douwei,'Noto Sans SC',system-ui,sans-serif}button,a{font:inherit}button{cursor:pointer}button:focus-visible,a:focus-visible,summary:focus-visible{outline:2px solid #c7f0a0;outline-offset:4px}a{text-decoration:none;color:inherit}main{min-height:100vh;background:radial-gradient(circle at 80% 10%,#30503445,transparent 36%),#081911}.top{height:80px;margin:auto;max-width:1660px;padding:0 4%;display:flex;align-items:center;justify-content:space-between;border-bottom:1px solid #c9e3ac31;font-size:11px;color:#9eb59e;letter-spacing:2px}.top i{color:#e1f6b7;font-style:normal}.wordmark{display:flex;gap:10px;align-items:center;color:#d6f3b2;font-size:26px;letter-spacing:0}.wordmark b{color:#f4f6e9;font-size:19px}.wordmark small{font-size:10px;letter-spacing:2px;color:#acbfa8}.runtime{font-variant-numeric:tabular-nums}.cinema,.chapters,.extras,footer{max-width:1520px;padding-inline:4%;margin:auto}.cinema-info{margin:50px 0 28px}.overline,.section-id{color:#c5e997;font-size:11px;letter-spacing:2.5px;font-weight:700}.cinema-info h1{font-size:clamp(34px,4.6vw,72px);letter-spacing:-2px;margin:13px 0 12px;line-height:1.28}.cinema-info h1 em,.extras h2 em{font-style:normal;color:#d2ef9d}.cinema-info p{font-size:15px;line-height:1.8;color:#aabfab;margin:0}.format-row{display:flex;align-items:center;justify-content:space-between;margin-bottom:17px;gap:10px}.formats{display:flex;gap:8px}.formats button{background:transparent;color:#a9c3a4;border:1px solid #5d755b;border-radius:100px;padding:12px 18px;transition:background .2s,border-color .2s}.formats button.chosen{background:#d9efad;color:#102418;border-color:#d9efad;font-weight:700}.formats button:hover{border-color:#e5f2c6}.formats small{font-size:11px;opacity:.8;padding-left:6px}.quality{color:#a2bca0;font-size:10px;letter-spacing:1.8px}.stage{position:relative;display:grid;place-items:center;aspect-ratio:16/9;background:#030c08;overflow:hidden;border-radius:5px;box-shadow:0 45px 100px #0008;border:1px solid #5771566b}.stage.portrait{height:min(85vh,1100px);aspect-ratio:auto}.stage video{height:100%;width:100%;object-fit:contain;display:block}.stage.portrait video{width:auto;height:100%;max-width:100%}.play-cover{position:absolute;inset:0;width:100%;height:100%;border:0;background:#04160b35;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:13px;color:#f6f9e8;transition:background .2s}.play-cover:hover{background:#04160b10}.play-cover.is-hidden{display:none}.play-disc{width:87px;height:87px;border-radius:50%;display:grid;place-items:center;background:#d5edac;color:#17341f;font-size:28px;padding-left:7px;box-shadow:0 8px 45px #081a13;transition:transform .2s}.play-cover:hover .play-disc{transform:scale(1.07)}.play-cover strong{font-size:21px}.play-cover small{font-size:11px;letter-spacing:1px;color:#d2e9cb}.under{display:flex;justify-content:space-between;align-items:center;padding:22px 0 7px;gap:16px}.film-meta{display:flex;gap:11px;align-items:center;font-size:12px;color:#a5bba9}.film-meta b{color:#d0eda4}.pulse{width:7px;height:7px;border-radius:50%;background:#aadb78;box-shadow:0 0 12px #b8ff8c}.primary{min-width:190px;border:0;border-radius:4px;background:#d4ed9f;color:#14251b;font-weight:800;padding:16px 20px;display:flex;gap:19px;justify-content:space-between}.primary:hover{background:#e4ffc3}.primary:disabled{opacity:.5}.save-status{height:20px;font-size:11px;color:#b5d293;margin:2px 0 0}.chapters{padding-top:65px}.chapter-list{margin-top:19px;display:grid;grid-template-columns:repeat(4,1fr);border-top:1px solid #647d5d;border-bottom:1px solid #647d5d}.chapter-list button{border:0;border-right:1px solid #415a40;background:none;color:#f7f8e8;text-align:left;display:flex;flex-direction:column;align-items:flex-start;gap:22px;padding:22px;min-height:142px;transition:background .2s}.chapter-list button:last-child{border:0}.chapter-list button:hover{background:#28452c}.chapter-list span{font-size:11px;color:#c9e7a1}.chapter-list strong{font-size:15px;line-height:1.6}.chapter-list small{font-size:11px;color:#bad99c}.extras{padding-top:100px}.extras h2{font-size:clamp(30px,3.2vw,52px);line-height:1.35;margin:16px 0 33px}.cover-links{display:grid;grid-template-columns:1.3fr .7fr;gap:24px;align-items:end}.cover-links a{border:1px solid #59775a;display:block;background:#142b1c;border-radius:5px;overflow:hidden}.cover-links a:hover{border-color:#d1f39d}.cover-links img{display:block;width:100%;aspect-ratio:16/9;object-fit:cover}.cover-links a:nth-child(2) img{aspect-ratio:16/9;object-position:center 38%}.cover-links span{display:block;padding:13px 17px;color:#d2ecb2;font-size:12px}.copy{border-top:1px solid #587456;margin-top:60px}.copy summary{cursor:pointer;list-style:none;padding:24px 2px;display:flex;justify-content:space-between;color:#d5eeb8;font-weight:600}.copy summary::-webkit-details-marker{display:none}.copy summary span{font-size:22px}.copy-grid{display:grid;grid-template-columns:1fr 1fr;gap:20px;padding-bottom:40px}.copy article{border:1px solid #446245;background:#10251a;padding:25px;border-radius:5px}.copy h3{margin:0 0 25px}.copy p{font-size:13px;color:#c6dbbd;line-height:1.85;white-space:pre-line;overflow-wrap:anywhere}.copy button{border:1px solid #aacb95;color:#deeece;padding:6px 13px;background:none;border-radius:3px;font-size:11px;margin-bottom:16px}footer{border-top:1px solid #567655;margin-top:90px;padding-top:30px;padding-bottom:40px;display:flex;gap:20px;align-items:center;color:#b8ceb3;font-size:12px}footer strong{color:#d7eeb3;font-size:19px}footer small{margin-left:auto;color:#829783}@media(max-width:720px){.top{height:60px}.top>span:not(.runtime),.wordmark small,.quality{display:none}.cinema-info{margin:28px 0 23px}.cinema-info h1{letter-spacing:-1px}.cinema-info p{font-size:12px}.formats{width:100%}.formats button{flex:1;padding:10px 8px;font-size:12px;white-space:nowrap}.formats small{display:block;font-size:9px}.stage.portrait{height:min(79vh,790px)}.play-disc{width:68px;height:68px}.play-cover strong{font-size:15px}.under{align-items:stretch;flex-direction:column}.film-meta{font-size:11px}.primary{justify-content:center}.chapter-list,.cover-links,.copy-grid{grid-template-columns:1fr 1fr}.chapter-list button:nth-child(2){border:0}.chapter-list button:nth-child(-n+2){border-bottom:1px solid #597259}.cover-links{gap:10px}.cover-links span{font-size:10px}.extras{padding-top:70px}.copy-grid{grid-template-columns:1fr}.chapters{padding-top:35px}footer{flex-wrap:wrap;margin-top:65px}footer small{margin-left:0}body{padding-bottom:env(safe-area-inset-bottom)}}@media(max-width:480px){.chapter-list strong{font-size:12px}.chapter-list button{min-height:125px;padding:15px}.film-meta span:last-child{font-size:10px}.cover-links a:nth-child(2) img{object-fit:cover}.format-row{margin-bottom:10px}}
|
|
|
studio/tools/build_assets.py
DELETED
|
@@ -1,88 +0,0 @@
|
|
| 1 |
-
"""Build original, browser-friendly *source shots*, stills and soundtrack (not a finished video).
|
| 2 |
-
Requires: uv pip install --target /tmp/surf-media imageio-ffmpeg pillow-heif edge-tts
|
| 3 |
-
Run: PYTHONPATH=/tmp/surf-media python studio/tools/build_assets.py from repo root.
|
| 4 |
-
"""
|
| 5 |
-
from pathlib import Path
|
| 6 |
-
import asyncio, subprocess, math, wave, array, os, struct, random, shutil
|
| 7 |
-
import edge_tts, imageio_ffmpeg, pillow_heif
|
| 8 |
-
from PIL import Image
|
| 9 |
-
pillow_heif.register_heif_opener()
|
| 10 |
-
ROOT=Path(__file__).resolve().parents[2]; OUT=ROOT/'studio/assets'; OUT.mkdir(exist_ok=True)
|
| 11 |
-
FF=imageio_ffmpeg.get_ffmpeg_exe()
|
| 12 |
-
def run(*args):
|
| 13 |
-
print('>', ' '.join(map(str,args))[:240],flush=True)
|
| 14 |
-
subprocess.run([FF,'-hide_banner','-loglevel','error','-y',*map(str,args)],check=True)
|
| 15 |
-
shots=[
|
| 16 |
-
('finished', '对已经制作好的拼豆作品展示.MOV',0,4,1),
|
| 17 |
-
('scan', '烫好了,还没有揭开烫纸,用微信二维码扫一扫,成功扫码.MP4',0,5,1.2),
|
| 18 |
-
('app', '已经制作好微信小程序.MP4',0.3,8,1.6),
|
| 19 |
-
('heat', '用烫豆机对拼好的作品烫.MOV',0.2,5,1),
|
| 20 |
-
('peel', '已经烫好了,准备揭开烫纸.MOV',0,5,1),
|
| 21 |
-
('message', '做成成品后使用微信扫一扫对成品扫二维码,成功扫码.MP4',2.3,5,1),
|
| 22 |
-
]
|
| 23 |
-
for name,src,start,duration,speed in shots:
|
| 24 |
-
dest=OUT/f'{name}.mp4'
|
| 25 |
-
run('-ss',start,'-i',ROOT/src,'-t',duration,'-an','-vf',f'setpts=(PTS-STARTPTS)/{speed},fps=24,scale=540:960:force_original_aspect_ratio=decrease,pad=540:960:(ow-iw)/2:(oh-ih)/2', '-c:v','libx264','-preset','fast','-crf','25','-pix_fmt','yuv420p','-g','12','-movflags','+faststart',dest)
|
| 26 |
-
for name,src in [('pattern','导出的拼豆图纸,仅图案部分.PNG'),('palette','导出的拼豆图纸色号用量情况.PNG'),('craft','拼豆作品制作中拼最后一颗豆.HEIC'),('result','拼豆作品已经完成了,并且烫好了,手拿起来.HEIC')]:
|
| 27 |
-
im=Image.open(ROOT/src).convert('RGB');im.thumbnail((1400,1800),Image.Resampling.LANCZOS)
|
| 28 |
-
im.save(OUT/f'{name}.jpg',quality=85,optimize=True)
|
| 29 |
-
shutil.copyfile(ROOT/'BeadQR/miniprogram/assets/miniprogram-code.png',OUT/'miniprogram-code.png')
|
| 30 |
-
# Each voice line has a precise start, so pacing is independent of network synthesis latency.
|
| 31 |
-
lines=[
|
| 32 |
-
(0.55,'如果一句想说的话,能被亲手拼出来呢?'),
|
| 33 |
-
(4.45,'再用微信扫一扫,真的能读到它。'),
|
| 34 |
-
(8.55,'打开豆维,写下你想说的话。'),
|
| 35 |
-
(13.0,'选一张照片,让图案和二维码变成拼豆图纸。'),
|
| 36 |
-
(17.65,'照着图纸,一颗一颗,拼出自己的心意。'),
|
| 37 |
-
(22.3,'盖上烫纸,轻轻烫平。'),
|
| 38 |
-
(27.15,'等它冷却,慢慢揭开。'),
|
| 39 |
-
(32.2,'拿起手机扫一扫,藏在作品里的话,就出现了。'),
|
| 40 |
-
(37.5,'豆维。把说不出口的心意,做成看得见的礼物。'),
|
| 41 |
-
]
|
| 42 |
-
async def tts():
|
| 43 |
-
for i,(_,text) in enumerate(lines):
|
| 44 |
-
target=OUT/f'voice-{i}.mp3'
|
| 45 |
-
await edge_tts.Communicate(text,'zh-CN-XiaoxiaoNeural',rate='+18%',pitch='-1Hz').save(str(target))
|
| 46 |
-
asyncio.run(tts())
|
| 47 |
-
# Original generative instrumental: plucked pentatonic arpeggio, gentle pulse and a tiny sparkle on reveal.
|
| 48 |
-
sr=32000; seconds=43; n=sr*seconds
|
| 49 |
-
random.seed(42)
|
| 50 |
-
def tone(t,f,attack=.02,decay=.45):
|
| 51 |
-
return (1-math.exp(-t/max(.001,attack)))*math.exp(-t/max(.01,decay))*(math.sin(2*math.pi*f*t)+.28*math.sin(4*math.pi*f*t)+.09*math.sin(6*math.pi*f*t))
|
| 52 |
-
notes=[261.63,329.63,392,493.88,587.33,659.26,783.99,987.77]
|
| 53 |
-
# Pre-calculate additive events; time-local loops keep construction inexpensive.
|
| 54 |
-
events=[]
|
| 55 |
-
for beat in range(86):
|
| 56 |
-
t=beat*.5; ix=[0,2,4,2,1,3,5,3][beat%8]
|
| 57 |
-
events.append((int(t*sr),notes[ix],.18,.53))
|
| 58 |
-
if beat%4==0:
|
| 59 |
-
events.append((int(t*sr),notes[[0,3,4,2][(beat//4)%4]]/2,.15,1.25))
|
| 60 |
-
for t in [3.9,7.9,12.9,16.9,21.9,26.9,31.9,36.9]:
|
| 61 |
-
events.append((int(t*sr),987.77,.11,.28))
|
| 62 |
-
buf=array.array('h',[0])*n
|
| 63 |
-
# Base soft wave with evolving pad/chord; transient synthesized directly into int16 buffer.
|
| 64 |
-
for i in range(n):
|
| 65 |
-
t=i/sr
|
| 66 |
-
fade=min(1,t/1.0,(seconds-t)/2.2)
|
| 67 |
-
pad=(math.sin(2*math.pi*130.81*t)+.48*math.sin(2*math.pi*196*t)+.31*math.sin(2*math.pi*261.63*t))*(.055+.009*math.sin(2*math.pi*.13*t))
|
| 68 |
-
pulse=.16*math.exp(-((t*2)%1)*13)*math.sin(2*math.pi*57*t) if t>8 else 0
|
| 69 |
-
buf[i]=int(max(-1,min(1,(pad+pulse)*fade))*32760)
|
| 70 |
-
for begin,f,vol,decay in events:
|
| 71 |
-
for j in range(min(int(sr*decay*7),n-begin)):
|
| 72 |
-
t=j/sr; k=begin+j
|
| 73 |
-
v=int(32760*vol*tone(t,f,.006,decay))
|
| 74 |
-
buf[k]=max(-32768,min(32767,buf[k]+v))
|
| 75 |
-
wav=OUT/'instrumental.wav'
|
| 76 |
-
with wave.open(str(wav),'wb') as w:
|
| 77 |
-
w.setnchannels(1);w.setsampwidth(2);w.setframerate(sr);w.writeframes(buf.tobytes())
|
| 78 |
-
# Build complete AAC soundtrack for browser preview AND deterministic local MP4 export.
|
| 79 |
-
inputs=[]; filters=['[0:a]volume=0.35[music]'];labels=['[music]']
|
| 80 |
-
inputs += ['-i',wav]
|
| 81 |
-
for i,(start,_) in enumerate(lines):
|
| 82 |
-
inputs+=['-i',OUT/f'voice-{i}.mp3']
|
| 83 |
-
filters.append(f'[{i+1}:a]aresample=async=1,volume=1.6,adelay={round(start*1000)}:all=1[v{i}]')
|
| 84 |
-
labels.append(f'[v{i}]')
|
| 85 |
-
filters.append(''.join(labels)+f'amix=inputs={len(labels)}:duration=first:normalize=0,alimiter=limit=0.90[out]')
|
| 86 |
-
run(*inputs,'-filter_complex',';'.join(filters),'-map','[out]','-t',seconds,'-ar','48000','-ac','2','-c:a','aac','-b:a','160k','-movflags','+faststart',OUT/'soundtrack.m4a')
|
| 87 |
-
wav.unlink()
|
| 88 |
-
print('Done. No finished promotional MP4 generated.')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Render the 114-second Douwei film from ORIGINAL CAMERA ROLLS and original code facts.
|
| 2 |
+
Usage (from repo root): PYTHONPATH=/tmp/surf-film python studio/tools/build_film.py
|
| 3 |
+
Needs imageio-ffmpeg, pillow-heif, edge-tts, numpy, Pillow; /tmp/douwei-font.ttf.
|
| 4 |
+
The resulting two complete films play as native <video> (no per-frame seeking).
|
| 5 |
+
"""
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import os,sys,asyncio,subprocess,math,re,json
|
| 8 |
+
import imageio_ffmpeg,edge_tts,numpy as np,pillow_heif
|
| 9 |
+
from PIL import Image,ImageDraw,ImageFont,ImageFilter
|
| 10 |
+
pillow_heif.register_heif_opener()
|
| 11 |
+
ROOT=Path(__file__).resolve().parents[2]; OUT=ROOT/'studio/film'; CACHE=OUT/'.build';OUT.mkdir(exist_ok=True);CACHE.mkdir(exist_ok=True)
|
| 12 |
+
FONT=os.environ.get('DOUWEI_FONT','/tmp/douwei-font.ttf');FF=imageio_ffmpeg.get_ffmpeg_exe(); FPS=30
|
| 13 |
+
# Every claim below is checked against BeadQR/miniprogram/pages/index/index.js, utils/palette.js and utils/pdf.js.
|
| 14 |
+
SCENES=[
|
| 15 |
+
dict(d=9,name='礼物不只有样子',lines=['一幅拼豆,','能藏下多少心意?'],subtitle='有些话,想亲手做成礼物。',voice='有些礼物很好看,但我想做一件不一样的事:把想说的话,藏进亲手拼好的作品里。',src='对已经制作好的拼豆作品展示.MOV',pos=0),
|
| 16 |
+
dict(d=7,name='一个真实的难题',lines=['好看,还不够。','它得真的扫得出。'],subtitle='从一次没有扫出的尝试开始。',voice='第一次试,作品很好看。可扫一扫,手机却读不出它。',src='使用微信扫码拼豆作品(半成品)发现扫不出来.MP4',pos=0),
|
| 17 |
+
dict(d=10,name='写下一句话',lines=['先写下,','想说的那句话。'],subtitle='一句祝福、一个名字,或者一个链接。',voice='于是,我们做了豆维。第一步,写下一句祝福,或是你想分享的一个链接。',src='已经制作好微信小程序.MP4',pos=0),
|
| 18 |
+
dict(d=10,name='融进照片',lines=['让文字,','遇见喜欢的照片。'],subtitle='把二维码与照片融为一幅拼豆图案。',voice='再选一张照片。豆维把二维码和画面,变成可以一颗一颗拼出的图案。',src='已经制作好微信小程序.MP4',pos=8),
|
| 19 |
+
dict(d=8,name='精心调整',lines=['想怎么摆,','就怎么设计。'],subtitle='大小位置可调 · 扫码自检 · 一键优化',voice='图案的位置和大小都能调整。扫不出来?先自检,再一键切换到扫码优先。' ,src='导出的拼豆图纸,仅图案部分.PNG',pos=0,still=True),
|
| 20 |
+
dict(d=9,name='一颗颗有色号',lines=['每一颗颜色,','都有它的编号。'],subtitle='24 色入门 · 221 色标准 · 291 色完整色板',voice='从二十四色的入门套装,到二百二十一色的标准色板,甚至更完整的颜色选择。每一颗豆子,都有自己的色号。',src='导出的拼豆图纸色号用量情况.PNG',pos=0,still=True),
|
| 21 |
+
dict(d=9,name='导出图纸',lines=['一张图纸,','把创意带出屏幕。'],subtitle='A4 PDF 图纸 · 格子色号 · 豆子用量清单',voice='确认效果后,导出图纸。每格用什么颜色、要准备多少颗豆子,都可以对照着看。',src='导出的拼豆图纸,仅图案部分.PNG',pos=0,still=True),
|
| 22 |
+
dict(d=14,name='亲手制作',lines=['接下来,','交给双手。'],subtitle='一颗、一颗,把心意拼出来。',voice='接下来,是最慢,也最珍贵的部分。对着图纸,拿起镊子,一颗,一颗,把原本在屏幕里的想法,拼在手里。',src='拼豆作品制作中,拼到一半.HEIC',pos=0,still=True,craft=True),
|
| 23 |
+
dict(d=9,name='熨烫定型',lines=['把散落的颜色,','连在一起。'],subtitle='盖好烫纸 · 小心熨烫 · 等待冷却',voice='盖上烫纸,仔细烫平。那些散落的颜色,终于连成了一件真正的作品。',src='用烫豆机对拼好的作品烫.MOV',pos=0),
|
| 24 |
+
dict(d=9,name='掀开作品',lines=['轻轻揭开,','作品诞生了。'],subtitle='你亲手完成的东西,终于有了模样。',voice='等它冷却,再慢慢揭开。每一道颜色,都是自己亲手拼出来的。',src='已经烫好了,准备揭开烫纸.MOV',pos=0),
|
| 25 |
+
dict(d=9,name='手机一扫',lines=['扫一扫,','它真的有话说。'],subtitle='画面中的扫码来自实际拍摄。',voice='然后,拿起手机扫一扫。最惊喜的那句话,终于从作品里,被读了出来。',src='烫好了,还没有揭开烫纸,用微信二维码扫一扫,成功扫码.MP4',pos=0),
|
| 26 |
+
dict(d=11,name='把心意送出去',lines=['豆维。','让礼物有话可说。'],subtitle='写一句话 · 选一张图 · 做一份会说话的礼物',voice='豆维,可扫码的拼豆。把一句话,做成一份看得见、也读得到的礼物。',src='拼豆作品已经完成了,并且烫好了,手拿起来.HEIC',pos=0,still=True,outro=True),
|
| 27 |
+
]
|
| 28 |
+
assert sum(s['d'] for s in SCENES)==114
|
| 29 |
+
|
| 30 |
+
def run(args, timeout=450):
|
| 31 |
+
print('ffmpeg',str(args)[0:185],flush=True)
|
| 32 |
+
subprocess.run([FF,'-hide_banner','-loglevel','error','-y',*map(str,args)],check=True,timeout=timeout)
|
| 33 |
+
def font(n):return ImageFont.truetype(FONT,n)
|
| 34 |
+
def overlay(s,i,mode):
|
| 35 |
+
wide=mode=='wide';W,H=(1920,1080) if wide else (1080,1920)
|
| 36 |
+
im=Image.new('RGBA',(W,H),(0,0,0,0)); pix=im.load()
|
| 37 |
+
# Glass-dark gradient preserves authentic footage and keeps typography legible.
|
| 38 |
+
if wide:
|
| 39 |
+
for x in range(0,W,2):
|
| 40 |
+
a=int(235*(1-max(0,min(1,(x-650)/700)))+37)
|
| 41 |
+
ImageDraw.Draw(im).rectangle((x,0,x+1,H),fill=(7,23,17,min(255,a)))
|
| 42 |
+
d=ImageDraw.Draw(im);d.rectangle((100,107,167,112),fill='#d7ee9b')
|
| 43 |
+
d.text((188,86),'D O U W E I / 一份会说话的礼物',font=font(25),fill='#e2f0d4')
|
| 44 |
+
d.text((110,205),f'{i+1:02d} / {s["name"]}',font=font(33),fill='#cfec99')
|
| 45 |
+
for j,line in enumerate(s['lines']):d.text((103,324+j*132),line,font=font(85),fill='#f6f5eb' if j==0 else '#daefab',stroke_width=1)
|
| 46 |
+
d.rectangle((108,746,161,750),fill='#dbefac')
|
| 47 |
+
d.text((108,784),s['subtitle'],font=font(36),fill='#f8f6e9')
|
| 48 |
+
d.text((110,982),'DOUWEI / 把心意,亲手交给你',font=font(24),fill='#c1d6b7')
|
| 49 |
+
d.text((1710,981),f'{i+1:02d} / 12',font=font(23),fill='#e0ecce')
|
| 50 |
+
if s.get('outro'):
|
| 51 |
+
qr=Image.open(ROOT/'BeadQR/miniprogram/assets/miniprogram-code.png').convert('RGB').resize((240,240));im.paste(qr,(1480,599));d=ImageDraw.Draw(im)
|
| 52 |
+
d.rounded_rectangle((1400,860,1835,930),radius=15,fill='#d8efae');d.text((1430,869),'微信搜索「豆维」',font=font(42),fill='#182f1e')
|
| 53 |
+
else:
|
| 54 |
+
veil=Image.new('RGBA',(W,H));vp=veil.load()
|
| 55 |
+
for y in range(H):
|
| 56 |
+
a=233 if y<740 else int(max(0,233*(1-(y-740)/260))) if y<1000 else 0 if y<1190 else int(min(224,130+(y-1190)*.27))
|
| 57 |
+
ImageDraw.Draw(veil).rectangle((0,y,W,y),fill=(5,22,15,a))
|
| 58 |
+
im=Image.alpha_composite(im,veil);d=ImageDraw.Draw(im)
|
| 59 |
+
d.rectangle((78,188,137,193),fill='#d7efad')
|
| 60 |
+
d.text((157,167),'D O U W E I / 电影短片',font=font(27),fill='#e9f5df')
|
| 61 |
+
d.text((77,277),f'{i+1:02d} / {s["name"]}',font=font(30),fill='#daf1b0')
|
| 62 |
+
for j,line in enumerate(s['lines']):d.text((74,368+j*120),line,font=font(77),fill='#ffffff' if j==0 else '#e2f6b0',stroke_width=1,stroke_fill='#072015')
|
| 63 |
+
d.rectangle((80,1310,143,1314),fill='#e0f3b9')
|
| 64 |
+
d.text((80,1350),s['subtitle'],font=font(31),fill='#fffdf4',stroke_width=1,stroke_fill='#082518')
|
| 65 |
+
d.text((80,1480),'DOUWEI / HANDMADE WITH LOVE',font=font(24),fill='#e2efd2')
|
| 66 |
+
if s.get('outro'):
|
| 67 |
+
qr=Image.open(ROOT/'BeadQR/miniprogram/assets/miniprogram-code.png').convert('RGB').resize((217,217));im.paste(qr,(84,980));d=ImageDraw.Draw(im)
|
| 68 |
+
d.text((331,1050),'微信搜索「豆维」',font=font(42),fill='#ffffff',stroke_width=2,stroke_fill='#082519')
|
| 69 |
+
d.text((78,1560),f'{i+1:02d} / 12 · 亲手拼成的心意',font=font(23),fill='#d1e2c4')
|
| 70 |
+
im.save(CACHE/f'{mode}-{i:02d}.png',compress_level=4)
|
| 71 |
+
|
| 72 |
+
def image_src(s,i):
|
| 73 |
+
path=ROOT/s['src']
|
| 74 |
+
if not s.get('still'):return path,False
|
| 75 |
+
out=CACHE/f'photo-{i:02d}.jpg'
|
| 76 |
+
if s.get('craft'):
|
| 77 |
+
names=['拼豆作品制作中,拼到一半.HEIC','拼豆作品制作中,拼到一半了.HEIC','拼豆作品制作中,差不多拼完了.HEIC','拼豆作品制作中拼最后一颗豆.HEIC']
|
| 78 |
+
photos=[]
|
| 79 |
+
for name in names:
|
| 80 |
+
p=Image.open(ROOT/name).convert('RGB');p.thumbnail((780,1460));photos.append(p)
|
| 81 |
+
im=Image.new('RGB',(780*4,1460),'#23402d')
|
| 82 |
+
for j,p in enumerate(photos):im.paste(p,(780*j+(780-p.width)//2,(1460-p.height)//2))
|
| 83 |
+
im.save(out,quality=88,optimize=True)
|
| 84 |
+
else:
|
| 85 |
+
im=Image.open(path).convert('RGB');im.thumbnail((1700,2400));im.save(out,quality=90,optimize=True)
|
| 86 |
+
return out,True
|
| 87 |
+
|
| 88 |
+
def render_scene(s,i,mode):
|
| 89 |
+
dest=CACHE/f'{mode}-{i:02d}.mp4'
|
| 90 |
+
if dest.exists() and dest.stat().st_size>25000:
|
| 91 |
+
print('reuse',dest,flush=True);return dest
|
| 92 |
+
W,H=(1920,1080) if mode=='wide' else (1080,1920)
|
| 93 |
+
src,still=image_src(s,i)
|
| 94 |
+
overlay(s,i,mode)
|
| 95 |
+
srcargs=['-loop','1','-framerate',str(FPS),'-i',src] if still else ['-ss',s['pos'],'-i',src]
|
| 96 |
+
# Native FFmpeg edit: one fluid 30 fps encode per shot; no browser frame-by-frame seeking.
|
| 97 |
+
# Still shots use continuous 30fps camera moves; the craft panorama pans across four progress photos.
|
| 98 |
+
if still and s.get('craft'):
|
| 99 |
+
moving=f"[0:v]crop=780:1460:x='(iw-780)*n/420':y=0,scale=600:1010:force_original_aspect_ratio=increase,crop=600:1010,fps={FPS}[moving];"
|
| 100 |
+
elif still:
|
| 101 |
+
moving=f"[0:v]scale=600:1010:force_original_aspect_ratio=increase,crop=600:1010,zoompan=z='min(zoom+0.00048,1.14)':d=1:x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':s=600x1010:fps={FPS}[moving];"
|
| 102 |
+
else:
|
| 103 |
+
moving=f'[0:v]fps={FPS}[moving];'
|
| 104 |
+
if mode=='wide':
|
| 105 |
+
base=(moving+'[moving]split=2[back][front];'
|
| 106 |
+
'[back]scale=1920:1080:force_original_aspect_ratio=increase,crop=1920:1080,boxblur=24:2,eq=brightness=-0.07:saturation=0.75[bg];'
|
| 107 |
+
'[front]scale=600:1010:force_original_aspect_ratio=increase,crop=600:1010,eq=saturation=1.09:contrast=1.04[fg];'
|
| 108 |
+
'[bg][fg]overlay=1260:34:shortest=1[visual];[visual][1:v]overlay=0:0:shortest=1[out]')
|
| 109 |
+
else:
|
| 110 |
+
base=(moving+'[moving]scale=1080:1920:force_original_aspect_ratio=increase,crop=1080:1920,eq=saturation=1.06:contrast=1.02[visual];'
|
| 111 |
+
'[visual][1:v]overlay=0:0:shortest=1[out]')
|
| 112 |
+
args=srcargs+['-loop','1','-i',CACHE/f'{mode}-{i:02d}.png','-filter_complex',base,'-map','[out]','-t',s['d'],'-an','-r',FPS,'-c:v','libx264','-preset','veryfast','-crf','23','-maxrate','8M','-bufsize','16M','-pix_fmt','yuv420p','-threads','4','-movflags','+faststart',dest]
|
| 113 |
+
run(args,timeout=550);return dest
|
| 114 |
+
async def make_voices():
|
| 115 |
+
for i,s in enumerate(SCENES):
|
| 116 |
+
out=CACHE/f'voice-{i:02d}.mp3'
|
| 117 |
+
if out.exists() and out.stat().st_size>6000:continue
|
| 118 |
+
print('narration',i,s['voice'],flush=True)
|
| 119 |
+
await edge_tts.Communicate(s['voice'],'zh-CN-XiaoxiaoNeural',rate='+8%',pitch='-2Hz').save(str(out))
|
| 120 |
+
|
| 121 |
+
def make_audio():
|
| 122 |
+
path=CACHE/'music.wav'
|
| 123 |
+
if not path.exists():
|
| 124 |
+
sr=32000; N=114*sr; a=np.zeros(N,dtype=np.float32);t=np.arange(N,dtype=np.float32)/sr
|
| 125 |
+
fade=np.minimum(1,np.minimum(t/1.1,(114-t)/2.8))
|
| 126 |
+
# Original score: two evolving synth pads, percussive subpulse and hand-crafted mallet arpeggio.
|
| 127 |
+
progression=[(130.81,164.81,196),(110,146.83,220),(116.54,174.61,233.08),(98,146.83,196)]
|
| 128 |
+
for i,(a0,b0,c0) in enumerate(progression):
|
| 129 |
+
start=i*28.5; idx=np.where((t>=start)&(t<start+28.5))[0]; tt=t[idx]
|
| 130 |
+
a[idx]+=.048*np.sin(2*np.pi*a0*tt)+.033*np.sin(2*np.pi*b0*tt)+.024*np.sin(2*np.pi*c0*tt)
|
| 131 |
+
beat=60/93
|
| 132 |
+
for k in range(int(114/beat)+1):
|
| 133 |
+
pos=int(k*beat*sr);end=min(N,pos+int(.5*sr));ln=end-pos
|
| 134 |
+
if ln<=0:continue
|
| 135 |
+
tt=np.arange(ln,dtype=np.float32)/sr
|
| 136 |
+
notes=[261.63,329.63,392,493.88,392,329.63,293.66,392]
|
| 137 |
+
n=notes[k%8]*(1 if k<110 else 1.25)
|
| 138 |
+
pluck=.145*np.exp(-tt*6.8)*np.sin(2*np.pi*n*tt)*(1+.25*np.sin(2*np.pi*n*tt))
|
| 139 |
+
a[pos:end]+=pluck
|
| 140 |
+
if k%4==0:
|
| 141 |
+
q=min(N,pos+int(.32*sr));b=np.arange(q-pos,dtype=np.float32)/sr
|
| 142 |
+
a[pos:q]+=.13*np.exp(-b*17)*np.sin(2*np.pi*(55-18*b)*b)
|
| 143 |
+
for st in np.cumsum([0]+[s['d'] for s in SCENES])[:-1]:
|
| 144 |
+
p=int(st*sr);end=min(N,p+int(.25*sr));tt=np.arange(end-p,dtype=np.float32)/sr
|
| 145 |
+
a[p:end]+=.028*np.sin(2*np.pi*(900+1700*tt)*tt)*np.exp(-tt*19)
|
| 146 |
+
a=np.clip(a*fade,-.8,.8);import wave
|
| 147 |
+
with wave.open(str(path),'wb') as f:f.setnchannels(1);f.setsampwidth(2);f.setframerate(sr);f.writeframes((a*32767).astype('<i2').tobytes())
|
| 148 |
+
inputs=['-i',path];filters=['[0:a]volume=0.47[m]'];labels=['[m]'];start=0
|
| 149 |
+
for i,s in enumerate(SCENES):
|
| 150 |
+
v=CACHE/f'voice-{i:02d}.mp3';inputs+=['-i',v]
|
| 151 |
+
# Fit each spoken section to its allotted film segment without clipping consonants.
|
| 152 |
+
meta=subprocess.run([FF,'-hide_banner','-i',str(v)],stderr=subprocess.PIPE,text=True).stderr
|
| 153 |
+
match=re.search(r'Duration: (\d+):(\d+):([\d.]+)',meta)
|
| 154 |
+
dur=int(match.group(1))*3600+int(match.group(2))*60+float(match.group(3)) if match else 6
|
| 155 |
+
fit=max(1,dur/max(1,s['d']-1.2));fit=min(fit,1.65)
|
| 156 |
+
filters.append(f'[{i+1}:a]atempo={fit:.4f},volume=1.65,adelay={int((start+.55)*1000)}:all=1[v{i}]');labels.append(f'[v{i}]')
|
| 157 |
+
print('voice duration',i,round(dur,2),'scene',s['d'],'speed',round(fit,2),flush=True)
|
| 158 |
+
start+=s['d']
|
| 159 |
+
filters.append(''.join(labels)+f'amix=inputs={len(labels)}:duration=first:normalize=0,alimiter=limit=0.88[out]')
|
| 160 |
+
run(inputs+['-filter_complex',';'.join(filters),'-map','[out]','-t','114','-ar','48000','-ac','2','-c:a','aac','-b:a','192k',OUT/'soundtrack-114s.m4a'],timeout=240)
|
| 161 |
+
|
| 162 |
+
def assemble(mode):
|
| 163 |
+
scenes=[render_scene(s,i,mode) for i,s in enumerate(SCENES)]
|
| 164 |
+
listing=CACHE/f'{mode}-list.txt';listing.write_text(''.join(f"file '{p.resolve()}'\n" for p in scenes))
|
| 165 |
+
dest=OUT/f'douwei-{mode}-114s.mp4'
|
| 166 |
+
run(['-f','concat','-safe','0','-i',listing,'-i',OUT/'soundtrack-114s.m4a','-map','0:v:0','-map','1:a:0','-c:v','copy','-c:a','copy','-movflags','+faststart','-shortest',dest],timeout=240)
|
| 167 |
+
print('FINAL',dest,dest.stat().st_size,flush=True)
|
| 168 |
+
|
| 169 |
+
if __name__=='__main__':
|
| 170 |
+
asyncio.run(make_voices())
|
| 171 |
+
make_audio()
|
| 172 |
+
modes=sys.argv[1:] or ['wide','portrait']
|
| 173 |
+
for mode in modes:assemble(mode)
|
studio/vendor/mp4-muxer.mjs
DELETED
|
@@ -1,1879 +0,0 @@
|
|
| 1 |
-
var __accessCheck = (obj, member, msg) => {
|
| 2 |
-
if (!member.has(obj))
|
| 3 |
-
throw TypeError("Cannot " + msg);
|
| 4 |
-
};
|
| 5 |
-
var __privateGet = (obj, member, getter) => {
|
| 6 |
-
__accessCheck(obj, member, "read from private field");
|
| 7 |
-
return getter ? getter.call(obj) : member.get(obj);
|
| 8 |
-
};
|
| 9 |
-
var __privateAdd = (obj, member, value) => {
|
| 10 |
-
if (member.has(obj))
|
| 11 |
-
throw TypeError("Cannot add the same private member more than once");
|
| 12 |
-
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
| 13 |
-
};
|
| 14 |
-
var __privateSet = (obj, member, value, setter) => {
|
| 15 |
-
__accessCheck(obj, member, "write to private field");
|
| 16 |
-
setter ? setter.call(obj, value) : member.set(obj, value);
|
| 17 |
-
return value;
|
| 18 |
-
};
|
| 19 |
-
var __privateWrapper = (obj, member, setter, getter) => ({
|
| 20 |
-
set _(value) {
|
| 21 |
-
__privateSet(obj, member, value, setter);
|
| 22 |
-
},
|
| 23 |
-
get _() {
|
| 24 |
-
return __privateGet(obj, member, getter);
|
| 25 |
-
}
|
| 26 |
-
});
|
| 27 |
-
var __privateMethod = (obj, member, method) => {
|
| 28 |
-
__accessCheck(obj, member, "access private method");
|
| 29 |
-
return method;
|
| 30 |
-
};
|
| 31 |
-
|
| 32 |
-
// src/misc.ts
|
| 33 |
-
var bytes = new Uint8Array(8);
|
| 34 |
-
var view = new DataView(bytes.buffer);
|
| 35 |
-
var u8 = (value) => {
|
| 36 |
-
return [(value % 256 + 256) % 256];
|
| 37 |
-
};
|
| 38 |
-
var u16 = (value) => {
|
| 39 |
-
view.setUint16(0, value, false);
|
| 40 |
-
return [bytes[0], bytes[1]];
|
| 41 |
-
};
|
| 42 |
-
var i16 = (value) => {
|
| 43 |
-
view.setInt16(0, value, false);
|
| 44 |
-
return [bytes[0], bytes[1]];
|
| 45 |
-
};
|
| 46 |
-
var u24 = (value) => {
|
| 47 |
-
view.setUint32(0, value, false);
|
| 48 |
-
return [bytes[1], bytes[2], bytes[3]];
|
| 49 |
-
};
|
| 50 |
-
var u32 = (value) => {
|
| 51 |
-
view.setUint32(0, value, false);
|
| 52 |
-
return [bytes[0], bytes[1], bytes[2], bytes[3]];
|
| 53 |
-
};
|
| 54 |
-
var i32 = (value) => {
|
| 55 |
-
view.setInt32(0, value, false);
|
| 56 |
-
return [bytes[0], bytes[1], bytes[2], bytes[3]];
|
| 57 |
-
};
|
| 58 |
-
var u64 = (value) => {
|
| 59 |
-
view.setUint32(0, Math.floor(value / 2 ** 32), false);
|
| 60 |
-
view.setUint32(4, value, false);
|
| 61 |
-
return [bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]];
|
| 62 |
-
};
|
| 63 |
-
var fixed_8_8 = (value) => {
|
| 64 |
-
view.setInt16(0, 2 ** 8 * value, false);
|
| 65 |
-
return [bytes[0], bytes[1]];
|
| 66 |
-
};
|
| 67 |
-
var fixed_16_16 = (value) => {
|
| 68 |
-
view.setInt32(0, 2 ** 16 * value, false);
|
| 69 |
-
return [bytes[0], bytes[1], bytes[2], bytes[3]];
|
| 70 |
-
};
|
| 71 |
-
var fixed_2_30 = (value) => {
|
| 72 |
-
view.setInt32(0, 2 ** 30 * value, false);
|
| 73 |
-
return [bytes[0], bytes[1], bytes[2], bytes[3]];
|
| 74 |
-
};
|
| 75 |
-
var ascii = (text, nullTerminated = false) => {
|
| 76 |
-
let bytes2 = Array(text.length).fill(null).map((_, i) => text.charCodeAt(i));
|
| 77 |
-
if (nullTerminated)
|
| 78 |
-
bytes2.push(0);
|
| 79 |
-
return bytes2;
|
| 80 |
-
};
|
| 81 |
-
var last = (arr) => {
|
| 82 |
-
return arr && arr[arr.length - 1];
|
| 83 |
-
};
|
| 84 |
-
var lastPresentedSample = (samples) => {
|
| 85 |
-
let result = void 0;
|
| 86 |
-
for (let sample of samples) {
|
| 87 |
-
if (!result || sample.presentationTimestamp > result.presentationTimestamp) {
|
| 88 |
-
result = sample;
|
| 89 |
-
}
|
| 90 |
-
}
|
| 91 |
-
return result;
|
| 92 |
-
};
|
| 93 |
-
var intoTimescale = (timeInSeconds, timescale, round = true) => {
|
| 94 |
-
let value = timeInSeconds * timescale;
|
| 95 |
-
return round ? Math.round(value) : value;
|
| 96 |
-
};
|
| 97 |
-
var rotationMatrix = (rotationInDegrees) => {
|
| 98 |
-
let theta = rotationInDegrees * (Math.PI / 180);
|
| 99 |
-
let cosTheta = Math.cos(theta);
|
| 100 |
-
let sinTheta = Math.sin(theta);
|
| 101 |
-
return [
|
| 102 |
-
cosTheta,
|
| 103 |
-
sinTheta,
|
| 104 |
-
0,
|
| 105 |
-
-sinTheta,
|
| 106 |
-
cosTheta,
|
| 107 |
-
0,
|
| 108 |
-
0,
|
| 109 |
-
0,
|
| 110 |
-
1
|
| 111 |
-
];
|
| 112 |
-
};
|
| 113 |
-
var IDENTITY_MATRIX = rotationMatrix(0);
|
| 114 |
-
var matrixToBytes = (matrix) => {
|
| 115 |
-
return [
|
| 116 |
-
fixed_16_16(matrix[0]),
|
| 117 |
-
fixed_16_16(matrix[1]),
|
| 118 |
-
fixed_2_30(matrix[2]),
|
| 119 |
-
fixed_16_16(matrix[3]),
|
| 120 |
-
fixed_16_16(matrix[4]),
|
| 121 |
-
fixed_2_30(matrix[5]),
|
| 122 |
-
fixed_16_16(matrix[6]),
|
| 123 |
-
fixed_16_16(matrix[7]),
|
| 124 |
-
fixed_2_30(matrix[8])
|
| 125 |
-
];
|
| 126 |
-
};
|
| 127 |
-
var deepClone = (x) => {
|
| 128 |
-
if (!x)
|
| 129 |
-
return x;
|
| 130 |
-
if (typeof x !== "object")
|
| 131 |
-
return x;
|
| 132 |
-
if (Array.isArray(x))
|
| 133 |
-
return x.map(deepClone);
|
| 134 |
-
return Object.fromEntries(Object.entries(x).map(([key, value]) => [key, deepClone(value)]));
|
| 135 |
-
};
|
| 136 |
-
var isU32 = (value) => {
|
| 137 |
-
return value >= 0 && value < 2 ** 32;
|
| 138 |
-
};
|
| 139 |
-
|
| 140 |
-
// src/box.ts
|
| 141 |
-
var box = (type, contents, children) => ({
|
| 142 |
-
type,
|
| 143 |
-
contents: contents && new Uint8Array(contents.flat(10)),
|
| 144 |
-
children
|
| 145 |
-
});
|
| 146 |
-
var fullBox = (type, version, flags, contents, children) => box(
|
| 147 |
-
type,
|
| 148 |
-
[u8(version), u24(flags), contents ?? []],
|
| 149 |
-
children
|
| 150 |
-
);
|
| 151 |
-
var ftyp = (details) => {
|
| 152 |
-
let minorVersion = 512;
|
| 153 |
-
if (details.fragmented)
|
| 154 |
-
return box("ftyp", [
|
| 155 |
-
ascii("iso5"),
|
| 156 |
-
// Major brand
|
| 157 |
-
u32(minorVersion),
|
| 158 |
-
// Minor version
|
| 159 |
-
// Compatible brands
|
| 160 |
-
ascii("iso5"),
|
| 161 |
-
ascii("iso6"),
|
| 162 |
-
ascii("mp41")
|
| 163 |
-
]);
|
| 164 |
-
return box("ftyp", [
|
| 165 |
-
ascii("isom"),
|
| 166 |
-
// Major brand
|
| 167 |
-
u32(minorVersion),
|
| 168 |
-
// Minor version
|
| 169 |
-
// Compatible brands
|
| 170 |
-
ascii("isom"),
|
| 171 |
-
details.holdsAvc ? ascii("avc1") : [],
|
| 172 |
-
ascii("mp41")
|
| 173 |
-
]);
|
| 174 |
-
};
|
| 175 |
-
var mdat = (reserveLargeSize) => ({ type: "mdat", largeSize: reserveLargeSize });
|
| 176 |
-
var free = (size) => ({ type: "free", size });
|
| 177 |
-
var moov = (tracks, creationTime, fragmented = false) => box("moov", null, [
|
| 178 |
-
mvhd(creationTime, tracks),
|
| 179 |
-
...tracks.map((x) => trak(x, creationTime)),
|
| 180 |
-
fragmented ? mvex(tracks) : null
|
| 181 |
-
]);
|
| 182 |
-
var mvhd = (creationTime, tracks) => {
|
| 183 |
-
let duration = intoTimescale(Math.max(
|
| 184 |
-
0,
|
| 185 |
-
...tracks.filter((x) => x.samples.length > 0).map((x) => {
|
| 186 |
-
const lastSample = lastPresentedSample(x.samples);
|
| 187 |
-
return lastSample.presentationTimestamp + lastSample.duration;
|
| 188 |
-
})
|
| 189 |
-
), GLOBAL_TIMESCALE);
|
| 190 |
-
let nextTrackId = Math.max(...tracks.map((x) => x.id)) + 1;
|
| 191 |
-
let needsU64 = !isU32(creationTime) || !isU32(duration);
|
| 192 |
-
let u32OrU64 = needsU64 ? u64 : u32;
|
| 193 |
-
return fullBox("mvhd", +needsU64, 0, [
|
| 194 |
-
u32OrU64(creationTime),
|
| 195 |
-
// Creation time
|
| 196 |
-
u32OrU64(creationTime),
|
| 197 |
-
// Modification time
|
| 198 |
-
u32(GLOBAL_TIMESCALE),
|
| 199 |
-
// Timescale
|
| 200 |
-
u32OrU64(duration),
|
| 201 |
-
// Duration
|
| 202 |
-
fixed_16_16(1),
|
| 203 |
-
// Preferred rate
|
| 204 |
-
fixed_8_8(1),
|
| 205 |
-
// Preferred volume
|
| 206 |
-
Array(10).fill(0),
|
| 207 |
-
// Reserved
|
| 208 |
-
matrixToBytes(IDENTITY_MATRIX),
|
| 209 |
-
// Matrix
|
| 210 |
-
Array(24).fill(0),
|
| 211 |
-
// Pre-defined
|
| 212 |
-
u32(nextTrackId)
|
| 213 |
-
// Next track ID
|
| 214 |
-
]);
|
| 215 |
-
};
|
| 216 |
-
var trak = (track, creationTime) => box("trak", null, [
|
| 217 |
-
tkhd(track, creationTime),
|
| 218 |
-
mdia(track, creationTime)
|
| 219 |
-
]);
|
| 220 |
-
var tkhd = (track, creationTime) => {
|
| 221 |
-
let lastSample = lastPresentedSample(track.samples);
|
| 222 |
-
let durationInGlobalTimescale = intoTimescale(
|
| 223 |
-
lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
|
| 224 |
-
GLOBAL_TIMESCALE
|
| 225 |
-
);
|
| 226 |
-
let needsU64 = !isU32(creationTime) || !isU32(durationInGlobalTimescale);
|
| 227 |
-
let u32OrU64 = needsU64 ? u64 : u32;
|
| 228 |
-
let matrix;
|
| 229 |
-
if (track.info.type === "video") {
|
| 230 |
-
matrix = typeof track.info.rotation === "number" ? rotationMatrix(track.info.rotation) : track.info.rotation;
|
| 231 |
-
} else {
|
| 232 |
-
matrix = IDENTITY_MATRIX;
|
| 233 |
-
}
|
| 234 |
-
return fullBox("tkhd", +needsU64, 3, [
|
| 235 |
-
u32OrU64(creationTime),
|
| 236 |
-
// Creation time
|
| 237 |
-
u32OrU64(creationTime),
|
| 238 |
-
// Modification time
|
| 239 |
-
u32(track.id),
|
| 240 |
-
// Track ID
|
| 241 |
-
u32(0),
|
| 242 |
-
// Reserved
|
| 243 |
-
u32OrU64(durationInGlobalTimescale),
|
| 244 |
-
// Duration
|
| 245 |
-
Array(8).fill(0),
|
| 246 |
-
// Reserved
|
| 247 |
-
u16(0),
|
| 248 |
-
// Layer
|
| 249 |
-
u16(0),
|
| 250 |
-
// Alternate group
|
| 251 |
-
fixed_8_8(track.info.type === "audio" ? 1 : 0),
|
| 252 |
-
// Volume
|
| 253 |
-
u16(0),
|
| 254 |
-
// Reserved
|
| 255 |
-
matrixToBytes(matrix),
|
| 256 |
-
// Matrix
|
| 257 |
-
fixed_16_16(track.info.type === "video" ? track.info.width : 0),
|
| 258 |
-
// Track width
|
| 259 |
-
fixed_16_16(track.info.type === "video" ? track.info.height : 0)
|
| 260 |
-
// Track height
|
| 261 |
-
]);
|
| 262 |
-
};
|
| 263 |
-
var mdia = (track, creationTime) => box("mdia", null, [
|
| 264 |
-
mdhd(track, creationTime),
|
| 265 |
-
hdlr(track.info.type === "video" ? "vide" : "soun"),
|
| 266 |
-
minf(track)
|
| 267 |
-
]);
|
| 268 |
-
var mdhd = (track, creationTime) => {
|
| 269 |
-
let lastSample = lastPresentedSample(track.samples);
|
| 270 |
-
let localDuration = intoTimescale(
|
| 271 |
-
lastSample ? lastSample.presentationTimestamp + lastSample.duration : 0,
|
| 272 |
-
track.timescale
|
| 273 |
-
);
|
| 274 |
-
let needsU64 = !isU32(creationTime) || !isU32(localDuration);
|
| 275 |
-
let u32OrU64 = needsU64 ? u64 : u32;
|
| 276 |
-
return fullBox("mdhd", +needsU64, 0, [
|
| 277 |
-
u32OrU64(creationTime),
|
| 278 |
-
// Creation time
|
| 279 |
-
u32OrU64(creationTime),
|
| 280 |
-
// Modification time
|
| 281 |
-
u32(track.timescale),
|
| 282 |
-
// Timescale
|
| 283 |
-
u32OrU64(localDuration),
|
| 284 |
-
// Duration
|
| 285 |
-
u16(21956),
|
| 286 |
-
// Language ("und", undetermined)
|
| 287 |
-
u16(0)
|
| 288 |
-
// Quality
|
| 289 |
-
]);
|
| 290 |
-
};
|
| 291 |
-
var hdlr = (componentSubtype) => fullBox("hdlr", 0, 0, [
|
| 292 |
-
ascii("mhlr"),
|
| 293 |
-
// Component type
|
| 294 |
-
ascii(componentSubtype),
|
| 295 |
-
// Component subtype
|
| 296 |
-
u32(0),
|
| 297 |
-
// Component manufacturer
|
| 298 |
-
u32(0),
|
| 299 |
-
// Component flags
|
| 300 |
-
u32(0),
|
| 301 |
-
// Component flags mask
|
| 302 |
-
ascii("mp4-muxer-hdlr", true)
|
| 303 |
-
// Component name
|
| 304 |
-
]);
|
| 305 |
-
var minf = (track) => box("minf", null, [
|
| 306 |
-
track.info.type === "video" ? vmhd() : smhd(),
|
| 307 |
-
dinf(),
|
| 308 |
-
stbl(track)
|
| 309 |
-
]);
|
| 310 |
-
var vmhd = () => fullBox("vmhd", 0, 1, [
|
| 311 |
-
u16(0),
|
| 312 |
-
// Graphics mode
|
| 313 |
-
u16(0),
|
| 314 |
-
// Opcolor R
|
| 315 |
-
u16(0),
|
| 316 |
-
// Opcolor G
|
| 317 |
-
u16(0)
|
| 318 |
-
// Opcolor B
|
| 319 |
-
]);
|
| 320 |
-
var smhd = () => fullBox("smhd", 0, 0, [
|
| 321 |
-
u16(0),
|
| 322 |
-
// Balance
|
| 323 |
-
u16(0)
|
| 324 |
-
// Reserved
|
| 325 |
-
]);
|
| 326 |
-
var dinf = () => box("dinf", null, [
|
| 327 |
-
dref()
|
| 328 |
-
]);
|
| 329 |
-
var dref = () => fullBox("dref", 0, 0, [
|
| 330 |
-
u32(1)
|
| 331 |
-
// Entry count
|
| 332 |
-
], [
|
| 333 |
-
url()
|
| 334 |
-
]);
|
| 335 |
-
var url = () => fullBox("url ", 0, 1);
|
| 336 |
-
var stbl = (track) => {
|
| 337 |
-
const needsCtts = track.compositionTimeOffsetTable.length > 1 || track.compositionTimeOffsetTable.some((x) => x.sampleCompositionTimeOffset !== 0);
|
| 338 |
-
return box("stbl", null, [
|
| 339 |
-
stsd(track),
|
| 340 |
-
stts(track),
|
| 341 |
-
stss(track),
|
| 342 |
-
stsc(track),
|
| 343 |
-
stsz(track),
|
| 344 |
-
stco(track),
|
| 345 |
-
needsCtts ? ctts(track) : null
|
| 346 |
-
]);
|
| 347 |
-
};
|
| 348 |
-
var stsd = (track) => fullBox("stsd", 0, 0, [
|
| 349 |
-
u32(1)
|
| 350 |
-
// Entry count
|
| 351 |
-
], [
|
| 352 |
-
track.info.type === "video" ? videoSampleDescription(
|
| 353 |
-
VIDEO_CODEC_TO_BOX_NAME[track.info.codec],
|
| 354 |
-
track
|
| 355 |
-
) : soundSampleDescription(
|
| 356 |
-
AUDIO_CODEC_TO_BOX_NAME[track.info.codec],
|
| 357 |
-
track
|
| 358 |
-
)
|
| 359 |
-
]);
|
| 360 |
-
var videoSampleDescription = (compressionType, track) => box(compressionType, [
|
| 361 |
-
Array(6).fill(0),
|
| 362 |
-
// Reserved
|
| 363 |
-
u16(1),
|
| 364 |
-
// Data reference index
|
| 365 |
-
u16(0),
|
| 366 |
-
// Pre-defined
|
| 367 |
-
u16(0),
|
| 368 |
-
// Reserved
|
| 369 |
-
Array(12).fill(0),
|
| 370 |
-
// Pre-defined
|
| 371 |
-
u16(track.info.width),
|
| 372 |
-
// Width
|
| 373 |
-
u16(track.info.height),
|
| 374 |
-
// Height
|
| 375 |
-
u32(4718592),
|
| 376 |
-
// Horizontal resolution
|
| 377 |
-
u32(4718592),
|
| 378 |
-
// Vertical resolution
|
| 379 |
-
u32(0),
|
| 380 |
-
// Reserved
|
| 381 |
-
u16(1),
|
| 382 |
-
// Frame count
|
| 383 |
-
Array(32).fill(0),
|
| 384 |
-
// Compressor name
|
| 385 |
-
u16(24),
|
| 386 |
-
// Depth
|
| 387 |
-
i16(65535)
|
| 388 |
-
// Pre-defined
|
| 389 |
-
], [
|
| 390 |
-
VIDEO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track),
|
| 391 |
-
track.info.decoderConfig.colorSpace ? colr(track) : null
|
| 392 |
-
]);
|
| 393 |
-
var COLOR_PRIMARIES_MAP = {
|
| 394 |
-
"bt709": 1,
|
| 395 |
-
// ITU-R BT.709
|
| 396 |
-
"bt470bg": 5,
|
| 397 |
-
// ITU-R BT.470BG
|
| 398 |
-
"smpte170m": 6
|
| 399 |
-
// ITU-R BT.601 525 - SMPTE 170M
|
| 400 |
-
};
|
| 401 |
-
var TRANSFER_CHARACTERISTICS_MAP = {
|
| 402 |
-
"bt709": 1,
|
| 403 |
-
// ITU-R BT.709
|
| 404 |
-
"smpte170m": 6,
|
| 405 |
-
// SMPTE 170M
|
| 406 |
-
"iec61966-2-1": 13
|
| 407 |
-
// IEC 61966-2-1
|
| 408 |
-
};
|
| 409 |
-
var MATRIX_COEFFICIENTS_MAP = {
|
| 410 |
-
"rgb": 0,
|
| 411 |
-
// Identity
|
| 412 |
-
"bt709": 1,
|
| 413 |
-
// ITU-R BT.709
|
| 414 |
-
"bt470bg": 5,
|
| 415 |
-
// ITU-R BT.470BG
|
| 416 |
-
"smpte170m": 6
|
| 417 |
-
// SMPTE 170M
|
| 418 |
-
};
|
| 419 |
-
var colr = (track) => box("colr", [
|
| 420 |
-
ascii("nclx"),
|
| 421 |
-
// Colour type
|
| 422 |
-
u16(COLOR_PRIMARIES_MAP[track.info.decoderConfig.colorSpace.primaries]),
|
| 423 |
-
// Colour primaries
|
| 424 |
-
u16(TRANSFER_CHARACTERISTICS_MAP[track.info.decoderConfig.colorSpace.transfer]),
|
| 425 |
-
// Transfer characteristics
|
| 426 |
-
u16(MATRIX_COEFFICIENTS_MAP[track.info.decoderConfig.colorSpace.matrix]),
|
| 427 |
-
// Matrix coefficients
|
| 428 |
-
u8((track.info.decoderConfig.colorSpace.fullRange ? 1 : 0) << 7)
|
| 429 |
-
// Full range flag
|
| 430 |
-
]);
|
| 431 |
-
var avcC = (track) => track.info.decoderConfig && box("avcC", [
|
| 432 |
-
// For AVC, description is an AVCDecoderConfigurationRecord, so nothing else to do here
|
| 433 |
-
...new Uint8Array(track.info.decoderConfig.description)
|
| 434 |
-
]);
|
| 435 |
-
var hvcC = (track) => track.info.decoderConfig && box("hvcC", [
|
| 436 |
-
// For HEVC, description is a HEVCDecoderConfigurationRecord, so nothing else to do here
|
| 437 |
-
...new Uint8Array(track.info.decoderConfig.description)
|
| 438 |
-
]);
|
| 439 |
-
var vpcC = (track) => {
|
| 440 |
-
if (!track.info.decoderConfig) {
|
| 441 |
-
return null;
|
| 442 |
-
}
|
| 443 |
-
let decoderConfig = track.info.decoderConfig;
|
| 444 |
-
if (!decoderConfig.colorSpace) {
|
| 445 |
-
throw new Error(`'colorSpace' is required in the decoder config for VP9.`);
|
| 446 |
-
}
|
| 447 |
-
let parts = decoderConfig.codec.split(".");
|
| 448 |
-
let profile = Number(parts[1]);
|
| 449 |
-
let level = Number(parts[2]);
|
| 450 |
-
let bitDepth = Number(parts[3]);
|
| 451 |
-
let chromaSubsampling = 0;
|
| 452 |
-
let thirdByte = (bitDepth << 4) + (chromaSubsampling << 1) + Number(decoderConfig.colorSpace.fullRange);
|
| 453 |
-
let colourPrimaries = 2;
|
| 454 |
-
let transferCharacteristics = 2;
|
| 455 |
-
let matrixCoefficients = 2;
|
| 456 |
-
return fullBox("vpcC", 1, 0, [
|
| 457 |
-
u8(profile),
|
| 458 |
-
// Profile
|
| 459 |
-
u8(level),
|
| 460 |
-
// Level
|
| 461 |
-
u8(thirdByte),
|
| 462 |
-
// Bit depth, chroma subsampling, full range
|
| 463 |
-
u8(colourPrimaries),
|
| 464 |
-
// Colour primaries
|
| 465 |
-
u8(transferCharacteristics),
|
| 466 |
-
// Transfer characteristics
|
| 467 |
-
u8(matrixCoefficients),
|
| 468 |
-
// Matrix coefficients
|
| 469 |
-
u16(0)
|
| 470 |
-
// Codec initialization data size
|
| 471 |
-
]);
|
| 472 |
-
};
|
| 473 |
-
var av1C = () => {
|
| 474 |
-
let marker = 1;
|
| 475 |
-
let version = 1;
|
| 476 |
-
let firstByte = (marker << 7) + version;
|
| 477 |
-
return box("av1C", [
|
| 478 |
-
firstByte,
|
| 479 |
-
0,
|
| 480 |
-
0,
|
| 481 |
-
0
|
| 482 |
-
]);
|
| 483 |
-
};
|
| 484 |
-
var soundSampleDescription = (compressionType, track) => box(compressionType, [
|
| 485 |
-
Array(6).fill(0),
|
| 486 |
-
// Reserved
|
| 487 |
-
u16(1),
|
| 488 |
-
// Data reference index
|
| 489 |
-
u16(0),
|
| 490 |
-
// Version
|
| 491 |
-
u16(0),
|
| 492 |
-
// Revision level
|
| 493 |
-
u32(0),
|
| 494 |
-
// Vendor
|
| 495 |
-
u16(track.info.numberOfChannels),
|
| 496 |
-
// Number of channels
|
| 497 |
-
u16(16),
|
| 498 |
-
// Sample size (bits)
|
| 499 |
-
u16(0),
|
| 500 |
-
// Compression ID
|
| 501 |
-
u16(0),
|
| 502 |
-
// Packet size
|
| 503 |
-
fixed_16_16(track.info.sampleRate)
|
| 504 |
-
// Sample rate
|
| 505 |
-
], [
|
| 506 |
-
AUDIO_CODEC_TO_CONFIGURATION_BOX[track.info.codec](track)
|
| 507 |
-
]);
|
| 508 |
-
var esds = (track) => {
|
| 509 |
-
let description = new Uint8Array(track.info.decoderConfig.description);
|
| 510 |
-
return fullBox("esds", 0, 0, [
|
| 511 |
-
// https://stackoverflow.com/a/54803118
|
| 512 |
-
u32(58753152),
|
| 513 |
-
// TAG(3) = Object Descriptor ([2])
|
| 514 |
-
u8(32 + description.byteLength),
|
| 515 |
-
// length of this OD (which includes the next 2 tags)
|
| 516 |
-
u16(1),
|
| 517 |
-
// ES_ID = 1
|
| 518 |
-
u8(0),
|
| 519 |
-
// flags etc = 0
|
| 520 |
-
u32(75530368),
|
| 521 |
-
// TAG(4) = ES Descriptor ([2]) embedded in above OD
|
| 522 |
-
u8(18 + description.byteLength),
|
| 523 |
-
// length of this ESD
|
| 524 |
-
u8(64),
|
| 525 |
-
// MPEG-4 Audio
|
| 526 |
-
u8(21),
|
| 527 |
-
// stream type(6bits)=5 audio, flags(2bits)=1
|
| 528 |
-
u24(0),
|
| 529 |
-
// 24bit buffer size
|
| 530 |
-
u32(130071),
|
| 531 |
-
// max bitrate
|
| 532 |
-
u32(130071),
|
| 533 |
-
// avg bitrate
|
| 534 |
-
u32(92307584),
|
| 535 |
-
// TAG(5) = ASC ([2],[3]) embedded in above OD
|
| 536 |
-
u8(description.byteLength),
|
| 537 |
-
// length
|
| 538 |
-
...description,
|
| 539 |
-
u32(109084800),
|
| 540 |
-
// TAG(6)
|
| 541 |
-
u8(1),
|
| 542 |
-
// length
|
| 543 |
-
u8(2)
|
| 544 |
-
// data
|
| 545 |
-
]);
|
| 546 |
-
};
|
| 547 |
-
var dOps = (track) => {
|
| 548 |
-
let preskip = 3840;
|
| 549 |
-
let gain = 0;
|
| 550 |
-
const description = track.info.decoderConfig?.description;
|
| 551 |
-
if (description) {
|
| 552 |
-
if (description.byteLength < 18) {
|
| 553 |
-
throw new TypeError("Invalid decoder description provided for Opus; must be at least 18 bytes long.");
|
| 554 |
-
}
|
| 555 |
-
const view2 = ArrayBuffer.isView(description) ? new DataView(description.buffer, description.byteOffset, description.byteLength) : new DataView(description);
|
| 556 |
-
preskip = view2.getUint16(10, true);
|
| 557 |
-
gain = view2.getInt16(14, true);
|
| 558 |
-
}
|
| 559 |
-
return box("dOps", [
|
| 560 |
-
u8(0),
|
| 561 |
-
// Version
|
| 562 |
-
u8(track.info.numberOfChannels),
|
| 563 |
-
// OutputChannelCount
|
| 564 |
-
u16(preskip),
|
| 565 |
-
u32(track.info.sampleRate),
|
| 566 |
-
// InputSampleRate
|
| 567 |
-
fixed_8_8(gain),
|
| 568 |
-
// OutputGain
|
| 569 |
-
u8(0)
|
| 570 |
-
// ChannelMappingFamily
|
| 571 |
-
]);
|
| 572 |
-
};
|
| 573 |
-
var stts = (track) => {
|
| 574 |
-
return fullBox("stts", 0, 0, [
|
| 575 |
-
u32(track.timeToSampleTable.length),
|
| 576 |
-
// Number of entries
|
| 577 |
-
track.timeToSampleTable.map((x) => [
|
| 578 |
-
// Time-to-sample table
|
| 579 |
-
u32(x.sampleCount),
|
| 580 |
-
// Sample count
|
| 581 |
-
u32(x.sampleDelta)
|
| 582 |
-
// Sample duration
|
| 583 |
-
])
|
| 584 |
-
]);
|
| 585 |
-
};
|
| 586 |
-
var stss = (track) => {
|
| 587 |
-
if (track.samples.every((x) => x.type === "key"))
|
| 588 |
-
return null;
|
| 589 |
-
let keySamples = [...track.samples.entries()].filter(([, sample]) => sample.type === "key");
|
| 590 |
-
return fullBox("stss", 0, 0, [
|
| 591 |
-
u32(keySamples.length),
|
| 592 |
-
// Number of entries
|
| 593 |
-
keySamples.map(([index]) => u32(index + 1))
|
| 594 |
-
// Sync sample table
|
| 595 |
-
]);
|
| 596 |
-
};
|
| 597 |
-
var stsc = (track) => {
|
| 598 |
-
return fullBox("stsc", 0, 0, [
|
| 599 |
-
u32(track.compactlyCodedChunkTable.length),
|
| 600 |
-
// Number of entries
|
| 601 |
-
track.compactlyCodedChunkTable.map((x) => [
|
| 602 |
-
// Sample-to-chunk table
|
| 603 |
-
u32(x.firstChunk),
|
| 604 |
-
// First chunk
|
| 605 |
-
u32(x.samplesPerChunk),
|
| 606 |
-
// Samples per chunk
|
| 607 |
-
u32(1)
|
| 608 |
-
// Sample description index
|
| 609 |
-
])
|
| 610 |
-
]);
|
| 611 |
-
};
|
| 612 |
-
var stsz = (track) => fullBox("stsz", 0, 0, [
|
| 613 |
-
u32(0),
|
| 614 |
-
// Sample size (0 means non-constant size)
|
| 615 |
-
u32(track.samples.length),
|
| 616 |
-
// Number of entries
|
| 617 |
-
track.samples.map((x) => u32(x.size))
|
| 618 |
-
// Sample size table
|
| 619 |
-
]);
|
| 620 |
-
var stco = (track) => {
|
| 621 |
-
if (track.finalizedChunks.length > 0 && last(track.finalizedChunks).offset >= 2 ** 32) {
|
| 622 |
-
return fullBox("co64", 0, 0, [
|
| 623 |
-
u32(track.finalizedChunks.length),
|
| 624 |
-
// Number of entries
|
| 625 |
-
track.finalizedChunks.map((x) => u64(x.offset))
|
| 626 |
-
// Chunk offset table
|
| 627 |
-
]);
|
| 628 |
-
}
|
| 629 |
-
return fullBox("stco", 0, 0, [
|
| 630 |
-
u32(track.finalizedChunks.length),
|
| 631 |
-
// Number of entries
|
| 632 |
-
track.finalizedChunks.map((x) => u32(x.offset))
|
| 633 |
-
// Chunk offset table
|
| 634 |
-
]);
|
| 635 |
-
};
|
| 636 |
-
var ctts = (track) => {
|
| 637 |
-
return fullBox("ctts", 0, 0, [
|
| 638 |
-
u32(track.compositionTimeOffsetTable.length),
|
| 639 |
-
// Number of entries
|
| 640 |
-
track.compositionTimeOffsetTable.map((x) => [
|
| 641 |
-
// Time-to-sample table
|
| 642 |
-
u32(x.sampleCount),
|
| 643 |
-
// Sample count
|
| 644 |
-
u32(x.sampleCompositionTimeOffset)
|
| 645 |
-
// Sample offset
|
| 646 |
-
])
|
| 647 |
-
]);
|
| 648 |
-
};
|
| 649 |
-
var mvex = (tracks) => {
|
| 650 |
-
return box("mvex", null, tracks.map(trex));
|
| 651 |
-
};
|
| 652 |
-
var trex = (track) => {
|
| 653 |
-
return fullBox("trex", 0, 0, [
|
| 654 |
-
u32(track.id),
|
| 655 |
-
// Track ID
|
| 656 |
-
u32(1),
|
| 657 |
-
// Default sample description index
|
| 658 |
-
u32(0),
|
| 659 |
-
// Default sample duration
|
| 660 |
-
u32(0),
|
| 661 |
-
// Default sample size
|
| 662 |
-
u32(0)
|
| 663 |
-
// Default sample flags
|
| 664 |
-
]);
|
| 665 |
-
};
|
| 666 |
-
var moof = (sequenceNumber, tracks) => {
|
| 667 |
-
return box("moof", null, [
|
| 668 |
-
mfhd(sequenceNumber),
|
| 669 |
-
...tracks.map(traf)
|
| 670 |
-
]);
|
| 671 |
-
};
|
| 672 |
-
var mfhd = (sequenceNumber) => {
|
| 673 |
-
return fullBox("mfhd", 0, 0, [
|
| 674 |
-
u32(sequenceNumber)
|
| 675 |
-
// Sequence number
|
| 676 |
-
]);
|
| 677 |
-
};
|
| 678 |
-
var fragmentSampleFlags = (sample) => {
|
| 679 |
-
let byte1 = 0;
|
| 680 |
-
let byte2 = 0;
|
| 681 |
-
let byte3 = 0;
|
| 682 |
-
let byte4 = 0;
|
| 683 |
-
let sampleIsDifferenceSample = sample.type === "delta";
|
| 684 |
-
byte2 |= +sampleIsDifferenceSample;
|
| 685 |
-
if (sampleIsDifferenceSample) {
|
| 686 |
-
byte1 |= 1;
|
| 687 |
-
} else {
|
| 688 |
-
byte1 |= 2;
|
| 689 |
-
}
|
| 690 |
-
return byte1 << 24 | byte2 << 16 | byte3 << 8 | byte4;
|
| 691 |
-
};
|
| 692 |
-
var traf = (track) => {
|
| 693 |
-
return box("traf", null, [
|
| 694 |
-
tfhd(track),
|
| 695 |
-
tfdt(track),
|
| 696 |
-
trun(track)
|
| 697 |
-
]);
|
| 698 |
-
};
|
| 699 |
-
var tfhd = (track) => {
|
| 700 |
-
let tfFlags = 0;
|
| 701 |
-
tfFlags |= 8;
|
| 702 |
-
tfFlags |= 16;
|
| 703 |
-
tfFlags |= 32;
|
| 704 |
-
tfFlags |= 131072;
|
| 705 |
-
let referenceSample = track.currentChunk.samples[1] ?? track.currentChunk.samples[0];
|
| 706 |
-
let referenceSampleInfo = {
|
| 707 |
-
duration: referenceSample.timescaleUnitsToNextSample,
|
| 708 |
-
size: referenceSample.size,
|
| 709 |
-
flags: fragmentSampleFlags(referenceSample)
|
| 710 |
-
};
|
| 711 |
-
return fullBox("tfhd", 0, tfFlags, [
|
| 712 |
-
u32(track.id),
|
| 713 |
-
// Track ID
|
| 714 |
-
u32(referenceSampleInfo.duration),
|
| 715 |
-
// Default sample duration
|
| 716 |
-
u32(referenceSampleInfo.size),
|
| 717 |
-
// Default sample size
|
| 718 |
-
u32(referenceSampleInfo.flags)
|
| 719 |
-
// Default sample flags
|
| 720 |
-
]);
|
| 721 |
-
};
|
| 722 |
-
var tfdt = (track) => {
|
| 723 |
-
return fullBox("tfdt", 1, 0, [
|
| 724 |
-
u64(intoTimescale(track.currentChunk.startTimestamp, track.timescale))
|
| 725 |
-
// Base Media Decode Time
|
| 726 |
-
]);
|
| 727 |
-
};
|
| 728 |
-
var trun = (track) => {
|
| 729 |
-
let allSampleDurations = track.currentChunk.samples.map((x) => x.timescaleUnitsToNextSample);
|
| 730 |
-
let allSampleSizes = track.currentChunk.samples.map((x) => x.size);
|
| 731 |
-
let allSampleFlags = track.currentChunk.samples.map(fragmentSampleFlags);
|
| 732 |
-
let allSampleCompositionTimeOffsets = track.currentChunk.samples.map((x) => intoTimescale(x.presentationTimestamp - x.decodeTimestamp, track.timescale));
|
| 733 |
-
let uniqueSampleDurations = new Set(allSampleDurations);
|
| 734 |
-
let uniqueSampleSizes = new Set(allSampleSizes);
|
| 735 |
-
let uniqueSampleFlags = new Set(allSampleFlags);
|
| 736 |
-
let uniqueSampleCompositionTimeOffsets = new Set(allSampleCompositionTimeOffsets);
|
| 737 |
-
let firstSampleFlagsPresent = uniqueSampleFlags.size === 2 && allSampleFlags[0] !== allSampleFlags[1];
|
| 738 |
-
let sampleDurationPresent = uniqueSampleDurations.size > 1;
|
| 739 |
-
let sampleSizePresent = uniqueSampleSizes.size > 1;
|
| 740 |
-
let sampleFlagsPresent = !firstSampleFlagsPresent && uniqueSampleFlags.size > 1;
|
| 741 |
-
let sampleCompositionTimeOffsetsPresent = uniqueSampleCompositionTimeOffsets.size > 1 || [...uniqueSampleCompositionTimeOffsets].some((x) => x !== 0);
|
| 742 |
-
let flags = 0;
|
| 743 |
-
flags |= 1;
|
| 744 |
-
flags |= 4 * +firstSampleFlagsPresent;
|
| 745 |
-
flags |= 256 * +sampleDurationPresent;
|
| 746 |
-
flags |= 512 * +sampleSizePresent;
|
| 747 |
-
flags |= 1024 * +sampleFlagsPresent;
|
| 748 |
-
flags |= 2048 * +sampleCompositionTimeOffsetsPresent;
|
| 749 |
-
return fullBox("trun", 1, flags, [
|
| 750 |
-
u32(track.currentChunk.samples.length),
|
| 751 |
-
// Sample count
|
| 752 |
-
u32(track.currentChunk.offset - track.currentChunk.moofOffset || 0),
|
| 753 |
-
// Data offset
|
| 754 |
-
firstSampleFlagsPresent ? u32(allSampleFlags[0]) : [],
|
| 755 |
-
track.currentChunk.samples.map((_, i) => [
|
| 756 |
-
sampleDurationPresent ? u32(allSampleDurations[i]) : [],
|
| 757 |
-
// Sample duration
|
| 758 |
-
sampleSizePresent ? u32(allSampleSizes[i]) : [],
|
| 759 |
-
// Sample size
|
| 760 |
-
sampleFlagsPresent ? u32(allSampleFlags[i]) : [],
|
| 761 |
-
// Sample flags
|
| 762 |
-
// Sample composition time offsets
|
| 763 |
-
sampleCompositionTimeOffsetsPresent ? i32(allSampleCompositionTimeOffsets[i]) : []
|
| 764 |
-
])
|
| 765 |
-
]);
|
| 766 |
-
};
|
| 767 |
-
var mfra = (tracks) => {
|
| 768 |
-
return box("mfra", null, [
|
| 769 |
-
...tracks.map(tfra),
|
| 770 |
-
mfro()
|
| 771 |
-
]);
|
| 772 |
-
};
|
| 773 |
-
var tfra = (track, trackIndex) => {
|
| 774 |
-
let version = 1;
|
| 775 |
-
return fullBox("tfra", version, 0, [
|
| 776 |
-
u32(track.id),
|
| 777 |
-
// Track ID
|
| 778 |
-
u32(63),
|
| 779 |
-
// This specifies that traf number, trun number and sample number are 32-bit ints
|
| 780 |
-
u32(track.finalizedChunks.length),
|
| 781 |
-
// Number of entries
|
| 782 |
-
track.finalizedChunks.map((chunk) => [
|
| 783 |
-
u64(intoTimescale(chunk.startTimestamp, track.timescale)),
|
| 784 |
-
// Time
|
| 785 |
-
u64(chunk.moofOffset),
|
| 786 |
-
// moof offset
|
| 787 |
-
u32(trackIndex + 1),
|
| 788 |
-
// traf number
|
| 789 |
-
u32(1),
|
| 790 |
-
// trun number
|
| 791 |
-
u32(1)
|
| 792 |
-
// Sample number
|
| 793 |
-
])
|
| 794 |
-
]);
|
| 795 |
-
};
|
| 796 |
-
var mfro = () => {
|
| 797 |
-
return fullBox("mfro", 0, 0, [
|
| 798 |
-
// This value needs to be overwritten manually from the outside, where the actual size of the enclosing mfra box
|
| 799 |
-
// is known
|
| 800 |
-
u32(0)
|
| 801 |
-
// Size
|
| 802 |
-
]);
|
| 803 |
-
};
|
| 804 |
-
var VIDEO_CODEC_TO_BOX_NAME = {
|
| 805 |
-
"avc": "avc1",
|
| 806 |
-
"hevc": "hvc1",
|
| 807 |
-
"vp9": "vp09",
|
| 808 |
-
"av1": "av01"
|
| 809 |
-
};
|
| 810 |
-
var VIDEO_CODEC_TO_CONFIGURATION_BOX = {
|
| 811 |
-
"avc": avcC,
|
| 812 |
-
"hevc": hvcC,
|
| 813 |
-
"vp9": vpcC,
|
| 814 |
-
"av1": av1C
|
| 815 |
-
};
|
| 816 |
-
var AUDIO_CODEC_TO_BOX_NAME = {
|
| 817 |
-
"aac": "mp4a",
|
| 818 |
-
"opus": "Opus"
|
| 819 |
-
};
|
| 820 |
-
var AUDIO_CODEC_TO_CONFIGURATION_BOX = {
|
| 821 |
-
"aac": esds,
|
| 822 |
-
"opus": dOps
|
| 823 |
-
};
|
| 824 |
-
|
| 825 |
-
// src/target.ts
|
| 826 |
-
var isTarget = Symbol("isTarget");
|
| 827 |
-
var Target = class {
|
| 828 |
-
};
|
| 829 |
-
isTarget;
|
| 830 |
-
var ArrayBufferTarget = class extends Target {
|
| 831 |
-
constructor() {
|
| 832 |
-
super(...arguments);
|
| 833 |
-
this.buffer = null;
|
| 834 |
-
}
|
| 835 |
-
};
|
| 836 |
-
var StreamTarget = class extends Target {
|
| 837 |
-
constructor(options) {
|
| 838 |
-
super();
|
| 839 |
-
this.options = options;
|
| 840 |
-
if (typeof options !== "object") {
|
| 841 |
-
throw new TypeError("StreamTarget requires an options object to be passed to its constructor.");
|
| 842 |
-
}
|
| 843 |
-
if (options.onData) {
|
| 844 |
-
if (typeof options.onData !== "function") {
|
| 845 |
-
throw new TypeError("options.onData, when provided, must be a function.");
|
| 846 |
-
}
|
| 847 |
-
if (options.onData.length < 2) {
|
| 848 |
-
throw new TypeError(
|
| 849 |
-
"options.onData, when provided, must be a function that takes in at least two arguments (data and position). Ignoring the position argument, which specifies the byte offset at which the data is to be written, can lead to broken outputs."
|
| 850 |
-
);
|
| 851 |
-
}
|
| 852 |
-
}
|
| 853 |
-
if (options.chunked !== void 0 && typeof options.chunked !== "boolean") {
|
| 854 |
-
throw new TypeError("options.chunked, when provided, must be a boolean.");
|
| 855 |
-
}
|
| 856 |
-
if (options.chunkSize !== void 0 && (!Number.isInteger(options.chunkSize) || options.chunkSize < 1024)) {
|
| 857 |
-
throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");
|
| 858 |
-
}
|
| 859 |
-
}
|
| 860 |
-
};
|
| 861 |
-
var FileSystemWritableFileStreamTarget = class extends Target {
|
| 862 |
-
constructor(stream, options) {
|
| 863 |
-
super();
|
| 864 |
-
this.stream = stream;
|
| 865 |
-
this.options = options;
|
| 866 |
-
if (!(stream instanceof FileSystemWritableFileStream)) {
|
| 867 |
-
throw new TypeError("FileSystemWritableFileStreamTarget requires a FileSystemWritableFileStream instance.");
|
| 868 |
-
}
|
| 869 |
-
if (options !== void 0 && typeof options !== "object") {
|
| 870 |
-
throw new TypeError("FileSystemWritableFileStreamTarget's options, when provided, must be an object.");
|
| 871 |
-
}
|
| 872 |
-
if (options) {
|
| 873 |
-
if (options.chunkSize !== void 0 && (!Number.isInteger(options.chunkSize) || options.chunkSize <= 0)) {
|
| 874 |
-
throw new TypeError("options.chunkSize, when provided, must be a positive integer");
|
| 875 |
-
}
|
| 876 |
-
}
|
| 877 |
-
}
|
| 878 |
-
};
|
| 879 |
-
|
| 880 |
-
// src/writer.ts
|
| 881 |
-
var _helper, _helperView;
|
| 882 |
-
var Writer = class {
|
| 883 |
-
constructor() {
|
| 884 |
-
this.pos = 0;
|
| 885 |
-
__privateAdd(this, _helper, new Uint8Array(8));
|
| 886 |
-
__privateAdd(this, _helperView, new DataView(__privateGet(this, _helper).buffer));
|
| 887 |
-
/**
|
| 888 |
-
* Stores the position from the start of the file to where boxes elements have been written. This is used to
|
| 889 |
-
* rewrite/edit elements that were already added before, and to measure sizes of things.
|
| 890 |
-
*/
|
| 891 |
-
this.offsets = /* @__PURE__ */ new WeakMap();
|
| 892 |
-
}
|
| 893 |
-
/** Sets the current position for future writes to a new one. */
|
| 894 |
-
seek(newPos) {
|
| 895 |
-
this.pos = newPos;
|
| 896 |
-
}
|
| 897 |
-
writeU32(value) {
|
| 898 |
-
__privateGet(this, _helperView).setUint32(0, value, false);
|
| 899 |
-
this.write(__privateGet(this, _helper).subarray(0, 4));
|
| 900 |
-
}
|
| 901 |
-
writeU64(value) {
|
| 902 |
-
__privateGet(this, _helperView).setUint32(0, Math.floor(value / 2 ** 32), false);
|
| 903 |
-
__privateGet(this, _helperView).setUint32(4, value, false);
|
| 904 |
-
this.write(__privateGet(this, _helper).subarray(0, 8));
|
| 905 |
-
}
|
| 906 |
-
writeAscii(text) {
|
| 907 |
-
for (let i = 0; i < text.length; i++) {
|
| 908 |
-
__privateGet(this, _helperView).setUint8(i % 8, text.charCodeAt(i));
|
| 909 |
-
if (i % 8 === 7)
|
| 910 |
-
this.write(__privateGet(this, _helper));
|
| 911 |
-
}
|
| 912 |
-
if (text.length % 8 !== 0) {
|
| 913 |
-
this.write(__privateGet(this, _helper).subarray(0, text.length % 8));
|
| 914 |
-
}
|
| 915 |
-
}
|
| 916 |
-
writeBox(box2) {
|
| 917 |
-
this.offsets.set(box2, this.pos);
|
| 918 |
-
if (box2.contents && !box2.children) {
|
| 919 |
-
this.writeBoxHeader(box2, box2.size ?? box2.contents.byteLength + 8);
|
| 920 |
-
this.write(box2.contents);
|
| 921 |
-
} else {
|
| 922 |
-
let startPos = this.pos;
|
| 923 |
-
this.writeBoxHeader(box2, 0);
|
| 924 |
-
if (box2.contents)
|
| 925 |
-
this.write(box2.contents);
|
| 926 |
-
if (box2.children) {
|
| 927 |
-
for (let child of box2.children)
|
| 928 |
-
if (child)
|
| 929 |
-
this.writeBox(child);
|
| 930 |
-
}
|
| 931 |
-
let endPos = this.pos;
|
| 932 |
-
let size = box2.size ?? endPos - startPos;
|
| 933 |
-
this.seek(startPos);
|
| 934 |
-
this.writeBoxHeader(box2, size);
|
| 935 |
-
this.seek(endPos);
|
| 936 |
-
}
|
| 937 |
-
}
|
| 938 |
-
writeBoxHeader(box2, size) {
|
| 939 |
-
this.writeU32(box2.largeSize ? 1 : size);
|
| 940 |
-
this.writeAscii(box2.type);
|
| 941 |
-
if (box2.largeSize)
|
| 942 |
-
this.writeU64(size);
|
| 943 |
-
}
|
| 944 |
-
measureBoxHeader(box2) {
|
| 945 |
-
return 8 + (box2.largeSize ? 8 : 0);
|
| 946 |
-
}
|
| 947 |
-
patchBox(box2) {
|
| 948 |
-
let endPos = this.pos;
|
| 949 |
-
this.seek(this.offsets.get(box2));
|
| 950 |
-
this.writeBox(box2);
|
| 951 |
-
this.seek(endPos);
|
| 952 |
-
}
|
| 953 |
-
measureBox(box2) {
|
| 954 |
-
if (box2.contents && !box2.children) {
|
| 955 |
-
let headerSize = this.measureBoxHeader(box2);
|
| 956 |
-
return headerSize + box2.contents.byteLength;
|
| 957 |
-
} else {
|
| 958 |
-
let result = this.measureBoxHeader(box2);
|
| 959 |
-
if (box2.contents)
|
| 960 |
-
result += box2.contents.byteLength;
|
| 961 |
-
if (box2.children) {
|
| 962 |
-
for (let child of box2.children)
|
| 963 |
-
if (child)
|
| 964 |
-
result += this.measureBox(child);
|
| 965 |
-
}
|
| 966 |
-
return result;
|
| 967 |
-
}
|
| 968 |
-
}
|
| 969 |
-
};
|
| 970 |
-
_helper = new WeakMap();
|
| 971 |
-
_helperView = new WeakMap();
|
| 972 |
-
var _target, _buffer, _bytes, _maxPos, _ensureSize, ensureSize_fn;
|
| 973 |
-
var ArrayBufferTargetWriter = class extends Writer {
|
| 974 |
-
constructor(target) {
|
| 975 |
-
super();
|
| 976 |
-
__privateAdd(this, _ensureSize);
|
| 977 |
-
__privateAdd(this, _target, void 0);
|
| 978 |
-
__privateAdd(this, _buffer, new ArrayBuffer(2 ** 16));
|
| 979 |
-
__privateAdd(this, _bytes, new Uint8Array(__privateGet(this, _buffer)));
|
| 980 |
-
__privateAdd(this, _maxPos, 0);
|
| 981 |
-
__privateSet(this, _target, target);
|
| 982 |
-
}
|
| 983 |
-
write(data) {
|
| 984 |
-
__privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos + data.byteLength);
|
| 985 |
-
__privateGet(this, _bytes).set(data, this.pos);
|
| 986 |
-
this.pos += data.byteLength;
|
| 987 |
-
__privateSet(this, _maxPos, Math.max(__privateGet(this, _maxPos), this.pos));
|
| 988 |
-
}
|
| 989 |
-
finalize() {
|
| 990 |
-
__privateMethod(this, _ensureSize, ensureSize_fn).call(this, this.pos);
|
| 991 |
-
__privateGet(this, _target).buffer = __privateGet(this, _buffer).slice(0, Math.max(__privateGet(this, _maxPos), this.pos));
|
| 992 |
-
}
|
| 993 |
-
};
|
| 994 |
-
_target = new WeakMap();
|
| 995 |
-
_buffer = new WeakMap();
|
| 996 |
-
_bytes = new WeakMap();
|
| 997 |
-
_maxPos = new WeakMap();
|
| 998 |
-
_ensureSize = new WeakSet();
|
| 999 |
-
ensureSize_fn = function(size) {
|
| 1000 |
-
let newLength = __privateGet(this, _buffer).byteLength;
|
| 1001 |
-
while (newLength < size)
|
| 1002 |
-
newLength *= 2;
|
| 1003 |
-
if (newLength === __privateGet(this, _buffer).byteLength)
|
| 1004 |
-
return;
|
| 1005 |
-
let newBuffer = new ArrayBuffer(newLength);
|
| 1006 |
-
let newBytes = new Uint8Array(newBuffer);
|
| 1007 |
-
newBytes.set(__privateGet(this, _bytes), 0);
|
| 1008 |
-
__privateSet(this, _buffer, newBuffer);
|
| 1009 |
-
__privateSet(this, _bytes, newBytes);
|
| 1010 |
-
};
|
| 1011 |
-
var DEFAULT_CHUNK_SIZE = 2 ** 24;
|
| 1012 |
-
var MAX_CHUNKS_AT_ONCE = 2;
|
| 1013 |
-
var _target2, _sections, _chunked, _chunkSize, _chunks, _writeDataIntoChunks, writeDataIntoChunks_fn, _insertSectionIntoChunk, insertSectionIntoChunk_fn, _createChunk, createChunk_fn, _flushChunks, flushChunks_fn;
|
| 1014 |
-
var StreamTargetWriter = class extends Writer {
|
| 1015 |
-
constructor(target) {
|
| 1016 |
-
super();
|
| 1017 |
-
__privateAdd(this, _writeDataIntoChunks);
|
| 1018 |
-
__privateAdd(this, _insertSectionIntoChunk);
|
| 1019 |
-
__privateAdd(this, _createChunk);
|
| 1020 |
-
__privateAdd(this, _flushChunks);
|
| 1021 |
-
__privateAdd(this, _target2, void 0);
|
| 1022 |
-
__privateAdd(this, _sections, []);
|
| 1023 |
-
__privateAdd(this, _chunked, void 0);
|
| 1024 |
-
__privateAdd(this, _chunkSize, void 0);
|
| 1025 |
-
/**
|
| 1026 |
-
* The data is divided up into fixed-size chunks, whose contents are first filled in RAM and then flushed out.
|
| 1027 |
-
* A chunk is flushed if all of its contents have been written.
|
| 1028 |
-
*/
|
| 1029 |
-
__privateAdd(this, _chunks, []);
|
| 1030 |
-
__privateSet(this, _target2, target);
|
| 1031 |
-
__privateSet(this, _chunked, target.options?.chunked ?? false);
|
| 1032 |
-
__privateSet(this, _chunkSize, target.options?.chunkSize ?? DEFAULT_CHUNK_SIZE);
|
| 1033 |
-
}
|
| 1034 |
-
write(data) {
|
| 1035 |
-
__privateGet(this, _sections).push({
|
| 1036 |
-
data: data.slice(),
|
| 1037 |
-
start: this.pos
|
| 1038 |
-
});
|
| 1039 |
-
this.pos += data.byteLength;
|
| 1040 |
-
}
|
| 1041 |
-
flush() {
|
| 1042 |
-
if (__privateGet(this, _sections).length === 0)
|
| 1043 |
-
return;
|
| 1044 |
-
let chunks = [];
|
| 1045 |
-
let sorted = [...__privateGet(this, _sections)].sort((a, b) => a.start - b.start);
|
| 1046 |
-
chunks.push({
|
| 1047 |
-
start: sorted[0].start,
|
| 1048 |
-
size: sorted[0].data.byteLength
|
| 1049 |
-
});
|
| 1050 |
-
for (let i = 1; i < sorted.length; i++) {
|
| 1051 |
-
let lastChunk = chunks[chunks.length - 1];
|
| 1052 |
-
let section = sorted[i];
|
| 1053 |
-
if (section.start <= lastChunk.start + lastChunk.size) {
|
| 1054 |
-
lastChunk.size = Math.max(lastChunk.size, section.start + section.data.byteLength - lastChunk.start);
|
| 1055 |
-
} else {
|
| 1056 |
-
chunks.push({
|
| 1057 |
-
start: section.start,
|
| 1058 |
-
size: section.data.byteLength
|
| 1059 |
-
});
|
| 1060 |
-
}
|
| 1061 |
-
}
|
| 1062 |
-
for (let chunk of chunks) {
|
| 1063 |
-
chunk.data = new Uint8Array(chunk.size);
|
| 1064 |
-
for (let section of __privateGet(this, _sections)) {
|
| 1065 |
-
if (chunk.start <= section.start && section.start < chunk.start + chunk.size) {
|
| 1066 |
-
chunk.data.set(section.data, section.start - chunk.start);
|
| 1067 |
-
}
|
| 1068 |
-
}
|
| 1069 |
-
if (__privateGet(this, _chunked)) {
|
| 1070 |
-
__privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, chunk.data, chunk.start);
|
| 1071 |
-
__privateMethod(this, _flushChunks, flushChunks_fn).call(this);
|
| 1072 |
-
} else {
|
| 1073 |
-
__privateGet(this, _target2).options.onData?.(chunk.data, chunk.start);
|
| 1074 |
-
}
|
| 1075 |
-
}
|
| 1076 |
-
__privateGet(this, _sections).length = 0;
|
| 1077 |
-
}
|
| 1078 |
-
finalize() {
|
| 1079 |
-
if (__privateGet(this, _chunked)) {
|
| 1080 |
-
__privateMethod(this, _flushChunks, flushChunks_fn).call(this, true);
|
| 1081 |
-
}
|
| 1082 |
-
}
|
| 1083 |
-
};
|
| 1084 |
-
_target2 = new WeakMap();
|
| 1085 |
-
_sections = new WeakMap();
|
| 1086 |
-
_chunked = new WeakMap();
|
| 1087 |
-
_chunkSize = new WeakMap();
|
| 1088 |
-
_chunks = new WeakMap();
|
| 1089 |
-
_writeDataIntoChunks = new WeakSet();
|
| 1090 |
-
writeDataIntoChunks_fn = function(data, position) {
|
| 1091 |
-
let chunkIndex = __privateGet(this, _chunks).findIndex((x) => x.start <= position && position < x.start + __privateGet(this, _chunkSize));
|
| 1092 |
-
if (chunkIndex === -1)
|
| 1093 |
-
chunkIndex = __privateMethod(this, _createChunk, createChunk_fn).call(this, position);
|
| 1094 |
-
let chunk = __privateGet(this, _chunks)[chunkIndex];
|
| 1095 |
-
let relativePosition = position - chunk.start;
|
| 1096 |
-
let toWrite = data.subarray(0, Math.min(__privateGet(this, _chunkSize) - relativePosition, data.byteLength));
|
| 1097 |
-
chunk.data.set(toWrite, relativePosition);
|
| 1098 |
-
let section = {
|
| 1099 |
-
start: relativePosition,
|
| 1100 |
-
end: relativePosition + toWrite.byteLength
|
| 1101 |
-
};
|
| 1102 |
-
__privateMethod(this, _insertSectionIntoChunk, insertSectionIntoChunk_fn).call(this, chunk, section);
|
| 1103 |
-
if (chunk.written[0].start === 0 && chunk.written[0].end === __privateGet(this, _chunkSize)) {
|
| 1104 |
-
chunk.shouldFlush = true;
|
| 1105 |
-
}
|
| 1106 |
-
if (__privateGet(this, _chunks).length > MAX_CHUNKS_AT_ONCE) {
|
| 1107 |
-
for (let i = 0; i < __privateGet(this, _chunks).length - 1; i++) {
|
| 1108 |
-
__privateGet(this, _chunks)[i].shouldFlush = true;
|
| 1109 |
-
}
|
| 1110 |
-
__privateMethod(this, _flushChunks, flushChunks_fn).call(this);
|
| 1111 |
-
}
|
| 1112 |
-
if (toWrite.byteLength < data.byteLength) {
|
| 1113 |
-
__privateMethod(this, _writeDataIntoChunks, writeDataIntoChunks_fn).call(this, data.subarray(toWrite.byteLength), position + toWrite.byteLength);
|
| 1114 |
-
}
|
| 1115 |
-
};
|
| 1116 |
-
_insertSectionIntoChunk = new WeakSet();
|
| 1117 |
-
insertSectionIntoChunk_fn = function(chunk, section) {
|
| 1118 |
-
let low = 0;
|
| 1119 |
-
let high = chunk.written.length - 1;
|
| 1120 |
-
let index = -1;
|
| 1121 |
-
while (low <= high) {
|
| 1122 |
-
let mid = Math.floor(low + (high - low + 1) / 2);
|
| 1123 |
-
if (chunk.written[mid].start <= section.start) {
|
| 1124 |
-
low = mid + 1;
|
| 1125 |
-
index = mid;
|
| 1126 |
-
} else {
|
| 1127 |
-
high = mid - 1;
|
| 1128 |
-
}
|
| 1129 |
-
}
|
| 1130 |
-
chunk.written.splice(index + 1, 0, section);
|
| 1131 |
-
if (index === -1 || chunk.written[index].end < section.start)
|
| 1132 |
-
index++;
|
| 1133 |
-
while (index < chunk.written.length - 1 && chunk.written[index].end >= chunk.written[index + 1].start) {
|
| 1134 |
-
chunk.written[index].end = Math.max(chunk.written[index].end, chunk.written[index + 1].end);
|
| 1135 |
-
chunk.written.splice(index + 1, 1);
|
| 1136 |
-
}
|
| 1137 |
-
};
|
| 1138 |
-
_createChunk = new WeakSet();
|
| 1139 |
-
createChunk_fn = function(includesPosition) {
|
| 1140 |
-
let start = Math.floor(includesPosition / __privateGet(this, _chunkSize)) * __privateGet(this, _chunkSize);
|
| 1141 |
-
let chunk = {
|
| 1142 |
-
start,
|
| 1143 |
-
data: new Uint8Array(__privateGet(this, _chunkSize)),
|
| 1144 |
-
written: [],
|
| 1145 |
-
shouldFlush: false
|
| 1146 |
-
};
|
| 1147 |
-
__privateGet(this, _chunks).push(chunk);
|
| 1148 |
-
__privateGet(this, _chunks).sort((a, b) => a.start - b.start);
|
| 1149 |
-
return __privateGet(this, _chunks).indexOf(chunk);
|
| 1150 |
-
};
|
| 1151 |
-
_flushChunks = new WeakSet();
|
| 1152 |
-
flushChunks_fn = function(force = false) {
|
| 1153 |
-
for (let i = 0; i < __privateGet(this, _chunks).length; i++) {
|
| 1154 |
-
let chunk = __privateGet(this, _chunks)[i];
|
| 1155 |
-
if (!chunk.shouldFlush && !force)
|
| 1156 |
-
continue;
|
| 1157 |
-
for (let section of chunk.written) {
|
| 1158 |
-
__privateGet(this, _target2).options.onData?.(
|
| 1159 |
-
chunk.data.subarray(section.start, section.end),
|
| 1160 |
-
chunk.start + section.start
|
| 1161 |
-
);
|
| 1162 |
-
}
|
| 1163 |
-
__privateGet(this, _chunks).splice(i--, 1);
|
| 1164 |
-
}
|
| 1165 |
-
};
|
| 1166 |
-
var FileSystemWritableFileStreamTargetWriter = class extends StreamTargetWriter {
|
| 1167 |
-
constructor(target) {
|
| 1168 |
-
super(new StreamTarget({
|
| 1169 |
-
onData: (data, position) => target.stream.write({
|
| 1170 |
-
type: "write",
|
| 1171 |
-
data,
|
| 1172 |
-
position
|
| 1173 |
-
}),
|
| 1174 |
-
chunked: true,
|
| 1175 |
-
chunkSize: target.options?.chunkSize
|
| 1176 |
-
}));
|
| 1177 |
-
}
|
| 1178 |
-
};
|
| 1179 |
-
|
| 1180 |
-
// src/muxer.ts
|
| 1181 |
-
var GLOBAL_TIMESCALE = 1e3;
|
| 1182 |
-
var SUPPORTED_VIDEO_CODECS = ["avc", "hevc", "vp9", "av1"];
|
| 1183 |
-
var SUPPORTED_AUDIO_CODECS = ["aac", "opus"];
|
| 1184 |
-
var TIMESTAMP_OFFSET = 2082844800;
|
| 1185 |
-
var FIRST_TIMESTAMP_BEHAVIORS = ["strict", "offset", "cross-track-offset"];
|
| 1186 |
-
var _options, _writer, _ftypSize, _mdat, _videoTrack, _audioTrack, _creationTime, _finalizedChunks, _nextFragmentNumber, _videoSampleQueue, _audioSampleQueue, _finalized, _validateOptions, validateOptions_fn, _writeHeader, writeHeader_fn, _computeMoovSizeUpperBound, computeMoovSizeUpperBound_fn, _prepareTracks, prepareTracks_fn, _generateMpeg4AudioSpecificConfig, generateMpeg4AudioSpecificConfig_fn, _createSampleForTrack, createSampleForTrack_fn, _addSampleToTrack, addSampleToTrack_fn, _validateTimestamp, validateTimestamp_fn, _finalizeCurrentChunk, finalizeCurrentChunk_fn, _finalizeFragment, finalizeFragment_fn, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn, _ensureNotFinalized, ensureNotFinalized_fn;
|
| 1187 |
-
var Muxer = class {
|
| 1188 |
-
constructor(options) {
|
| 1189 |
-
__privateAdd(this, _validateOptions);
|
| 1190 |
-
__privateAdd(this, _writeHeader);
|
| 1191 |
-
__privateAdd(this, _computeMoovSizeUpperBound);
|
| 1192 |
-
__privateAdd(this, _prepareTracks);
|
| 1193 |
-
// https://wiki.multimedia.cx/index.php/MPEG-4_Audio
|
| 1194 |
-
__privateAdd(this, _generateMpeg4AudioSpecificConfig);
|
| 1195 |
-
__privateAdd(this, _createSampleForTrack);
|
| 1196 |
-
__privateAdd(this, _addSampleToTrack);
|
| 1197 |
-
__privateAdd(this, _validateTimestamp);
|
| 1198 |
-
__privateAdd(this, _finalizeCurrentChunk);
|
| 1199 |
-
__privateAdd(this, _finalizeFragment);
|
| 1200 |
-
__privateAdd(this, _maybeFlushStreamingTargetWriter);
|
| 1201 |
-
__privateAdd(this, _ensureNotFinalized);
|
| 1202 |
-
__privateAdd(this, _options, void 0);
|
| 1203 |
-
__privateAdd(this, _writer, void 0);
|
| 1204 |
-
__privateAdd(this, _ftypSize, void 0);
|
| 1205 |
-
__privateAdd(this, _mdat, void 0);
|
| 1206 |
-
__privateAdd(this, _videoTrack, null);
|
| 1207 |
-
__privateAdd(this, _audioTrack, null);
|
| 1208 |
-
__privateAdd(this, _creationTime, Math.floor(Date.now() / 1e3) + TIMESTAMP_OFFSET);
|
| 1209 |
-
__privateAdd(this, _finalizedChunks, []);
|
| 1210 |
-
// Fields for fragmented MP4:
|
| 1211 |
-
__privateAdd(this, _nextFragmentNumber, 1);
|
| 1212 |
-
__privateAdd(this, _videoSampleQueue, []);
|
| 1213 |
-
__privateAdd(this, _audioSampleQueue, []);
|
| 1214 |
-
__privateAdd(this, _finalized, false);
|
| 1215 |
-
__privateMethod(this, _validateOptions, validateOptions_fn).call(this, options);
|
| 1216 |
-
options.video = deepClone(options.video);
|
| 1217 |
-
options.audio = deepClone(options.audio);
|
| 1218 |
-
options.fastStart = deepClone(options.fastStart);
|
| 1219 |
-
this.target = options.target;
|
| 1220 |
-
__privateSet(this, _options, {
|
| 1221 |
-
firstTimestampBehavior: "strict",
|
| 1222 |
-
...options
|
| 1223 |
-
});
|
| 1224 |
-
if (options.target instanceof ArrayBufferTarget) {
|
| 1225 |
-
__privateSet(this, _writer, new ArrayBufferTargetWriter(options.target));
|
| 1226 |
-
} else if (options.target instanceof StreamTarget) {
|
| 1227 |
-
__privateSet(this, _writer, new StreamTargetWriter(options.target));
|
| 1228 |
-
} else if (options.target instanceof FileSystemWritableFileStreamTarget) {
|
| 1229 |
-
__privateSet(this, _writer, new FileSystemWritableFileStreamTargetWriter(options.target));
|
| 1230 |
-
} else {
|
| 1231 |
-
throw new Error(`Invalid target: ${options.target}`);
|
| 1232 |
-
}
|
| 1233 |
-
__privateMethod(this, _prepareTracks, prepareTracks_fn).call(this);
|
| 1234 |
-
__privateMethod(this, _writeHeader, writeHeader_fn).call(this);
|
| 1235 |
-
}
|
| 1236 |
-
addVideoChunk(sample, meta, timestamp, compositionTimeOffset) {
|
| 1237 |
-
if (!(sample instanceof EncodedVideoChunk)) {
|
| 1238 |
-
throw new TypeError("addVideoChunk's first argument (sample) must be of type EncodedVideoChunk.");
|
| 1239 |
-
}
|
| 1240 |
-
if (meta && typeof meta !== "object") {
|
| 1241 |
-
throw new TypeError("addVideoChunk's second argument (meta), when provided, must be an object.");
|
| 1242 |
-
}
|
| 1243 |
-
if (timestamp !== void 0 && (!Number.isFinite(timestamp) || timestamp < 0)) {
|
| 1244 |
-
throw new TypeError(
|
| 1245 |
-
"addVideoChunk's third argument (timestamp), when provided, must be a non-negative real number."
|
| 1246 |
-
);
|
| 1247 |
-
}
|
| 1248 |
-
if (compositionTimeOffset !== void 0 && !Number.isFinite(compositionTimeOffset)) {
|
| 1249 |
-
throw new TypeError(
|
| 1250 |
-
"addVideoChunk's fourth argument (compositionTimeOffset), when provided, must be a real number."
|
| 1251 |
-
);
|
| 1252 |
-
}
|
| 1253 |
-
let data = new Uint8Array(sample.byteLength);
|
| 1254 |
-
sample.copyTo(data);
|
| 1255 |
-
this.addVideoChunkRaw(
|
| 1256 |
-
data,
|
| 1257 |
-
sample.type,
|
| 1258 |
-
timestamp ?? sample.timestamp,
|
| 1259 |
-
sample.duration,
|
| 1260 |
-
meta,
|
| 1261 |
-
compositionTimeOffset
|
| 1262 |
-
);
|
| 1263 |
-
}
|
| 1264 |
-
addVideoChunkRaw(data, type, timestamp, duration, meta, compositionTimeOffset) {
|
| 1265 |
-
if (!(data instanceof Uint8Array)) {
|
| 1266 |
-
throw new TypeError("addVideoChunkRaw's first argument (data) must be an instance of Uint8Array.");
|
| 1267 |
-
}
|
| 1268 |
-
if (type !== "key" && type !== "delta") {
|
| 1269 |
-
throw new TypeError("addVideoChunkRaw's second argument (type) must be either 'key' or 'delta'.");
|
| 1270 |
-
}
|
| 1271 |
-
if (!Number.isFinite(timestamp) || timestamp < 0) {
|
| 1272 |
-
throw new TypeError("addVideoChunkRaw's third argument (timestamp) must be a non-negative real number.");
|
| 1273 |
-
}
|
| 1274 |
-
if (!Number.isFinite(duration) || duration < 0) {
|
| 1275 |
-
throw new TypeError("addVideoChunkRaw's fourth argument (duration) must be a non-negative real number.");
|
| 1276 |
-
}
|
| 1277 |
-
if (meta && typeof meta !== "object") {
|
| 1278 |
-
throw new TypeError("addVideoChunkRaw's fifth argument (meta), when provided, must be an object.");
|
| 1279 |
-
}
|
| 1280 |
-
if (compositionTimeOffset !== void 0 && !Number.isFinite(compositionTimeOffset)) {
|
| 1281 |
-
throw new TypeError(
|
| 1282 |
-
"addVideoChunkRaw's sixth argument (compositionTimeOffset), when provided, must be a real number."
|
| 1283 |
-
);
|
| 1284 |
-
}
|
| 1285 |
-
__privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
|
| 1286 |
-
if (!__privateGet(this, _options).video)
|
| 1287 |
-
throw new Error("No video track declared.");
|
| 1288 |
-
if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _videoTrack).samples.length === __privateGet(this, _options).fastStart.expectedVideoChunks) {
|
| 1289 |
-
throw new Error(`Cannot add more video chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedVideoChunks}).`);
|
| 1290 |
-
}
|
| 1291 |
-
let videoSample = __privateMethod(this, _createSampleForTrack, createSampleForTrack_fn).call(this, __privateGet(this, _videoTrack), data, type, timestamp, duration, meta, compositionTimeOffset);
|
| 1292 |
-
if (__privateGet(this, _options).fastStart === "fragmented" && __privateGet(this, _audioTrack)) {
|
| 1293 |
-
while (__privateGet(this, _audioSampleQueue).length > 0 && __privateGet(this, _audioSampleQueue)[0].decodeTimestamp <= videoSample.decodeTimestamp) {
|
| 1294 |
-
let audioSample = __privateGet(this, _audioSampleQueue).shift();
|
| 1295 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
|
| 1296 |
-
}
|
| 1297 |
-
if (videoSample.decodeTimestamp <= __privateGet(this, _audioTrack).lastDecodeTimestamp) {
|
| 1298 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
|
| 1299 |
-
} else {
|
| 1300 |
-
__privateGet(this, _videoSampleQueue).push(videoSample);
|
| 1301 |
-
}
|
| 1302 |
-
} else {
|
| 1303 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
|
| 1304 |
-
}
|
| 1305 |
-
}
|
| 1306 |
-
addAudioChunk(sample, meta, timestamp) {
|
| 1307 |
-
if (!(sample instanceof EncodedAudioChunk)) {
|
| 1308 |
-
throw new TypeError("addAudioChunk's first argument (sample) must be of type EncodedAudioChunk.");
|
| 1309 |
-
}
|
| 1310 |
-
if (meta && typeof meta !== "object") {
|
| 1311 |
-
throw new TypeError("addAudioChunk's second argument (meta), when provided, must be an object.");
|
| 1312 |
-
}
|
| 1313 |
-
if (timestamp !== void 0 && (!Number.isFinite(timestamp) || timestamp < 0)) {
|
| 1314 |
-
throw new TypeError(
|
| 1315 |
-
"addAudioChunk's third argument (timestamp), when provided, must be a non-negative real number."
|
| 1316 |
-
);
|
| 1317 |
-
}
|
| 1318 |
-
let data = new Uint8Array(sample.byteLength);
|
| 1319 |
-
sample.copyTo(data);
|
| 1320 |
-
this.addAudioChunkRaw(data, sample.type, timestamp ?? sample.timestamp, sample.duration, meta);
|
| 1321 |
-
}
|
| 1322 |
-
addAudioChunkRaw(data, type, timestamp, duration, meta) {
|
| 1323 |
-
if (!(data instanceof Uint8Array)) {
|
| 1324 |
-
throw new TypeError("addAudioChunkRaw's first argument (data) must be an instance of Uint8Array.");
|
| 1325 |
-
}
|
| 1326 |
-
if (type !== "key" && type !== "delta") {
|
| 1327 |
-
throw new TypeError("addAudioChunkRaw's second argument (type) must be either 'key' or 'delta'.");
|
| 1328 |
-
}
|
| 1329 |
-
if (!Number.isFinite(timestamp) || timestamp < 0) {
|
| 1330 |
-
throw new TypeError("addAudioChunkRaw's third argument (timestamp) must be a non-negative real number.");
|
| 1331 |
-
}
|
| 1332 |
-
if (!Number.isFinite(duration) || duration < 0) {
|
| 1333 |
-
throw new TypeError("addAudioChunkRaw's fourth argument (duration) must be a non-negative real number.");
|
| 1334 |
-
}
|
| 1335 |
-
if (meta && typeof meta !== "object") {
|
| 1336 |
-
throw new TypeError("addAudioChunkRaw's fifth argument (meta), when provided, must be an object.");
|
| 1337 |
-
}
|
| 1338 |
-
__privateMethod(this, _ensureNotFinalized, ensureNotFinalized_fn).call(this);
|
| 1339 |
-
if (!__privateGet(this, _options).audio)
|
| 1340 |
-
throw new Error("No audio track declared.");
|
| 1341 |
-
if (typeof __privateGet(this, _options).fastStart === "object" && __privateGet(this, _audioTrack).samples.length === __privateGet(this, _options).fastStart.expectedAudioChunks) {
|
| 1342 |
-
throw new Error(`Cannot add more audio chunks than specified in 'fastStart' (${__privateGet(this, _options).fastStart.expectedAudioChunks}).`);
|
| 1343 |
-
}
|
| 1344 |
-
let audioSample = __privateMethod(this, _createSampleForTrack, createSampleForTrack_fn).call(this, __privateGet(this, _audioTrack), data, type, timestamp, duration, meta);
|
| 1345 |
-
if (__privateGet(this, _options).fastStart === "fragmented" && __privateGet(this, _videoTrack)) {
|
| 1346 |
-
while (__privateGet(this, _videoSampleQueue).length > 0 && __privateGet(this, _videoSampleQueue)[0].decodeTimestamp <= audioSample.decodeTimestamp) {
|
| 1347 |
-
let videoSample = __privateGet(this, _videoSampleQueue).shift();
|
| 1348 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
|
| 1349 |
-
}
|
| 1350 |
-
if (audioSample.decodeTimestamp <= __privateGet(this, _videoTrack).lastDecodeTimestamp) {
|
| 1351 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
|
| 1352 |
-
} else {
|
| 1353 |
-
__privateGet(this, _audioSampleQueue).push(audioSample);
|
| 1354 |
-
}
|
| 1355 |
-
} else {
|
| 1356 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
|
| 1357 |
-
}
|
| 1358 |
-
}
|
| 1359 |
-
/** Finalizes the file, making it ready for use. Must be called after all video and audio chunks have been added. */
|
| 1360 |
-
finalize() {
|
| 1361 |
-
if (__privateGet(this, _finalized)) {
|
| 1362 |
-
throw new Error("Cannot finalize a muxer more than once.");
|
| 1363 |
-
}
|
| 1364 |
-
if (__privateGet(this, _options).fastStart === "fragmented") {
|
| 1365 |
-
for (let videoSample of __privateGet(this, _videoSampleQueue))
|
| 1366 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _videoTrack), videoSample);
|
| 1367 |
-
for (let audioSample of __privateGet(this, _audioSampleQueue))
|
| 1368 |
-
__privateMethod(this, _addSampleToTrack, addSampleToTrack_fn).call(this, __privateGet(this, _audioTrack), audioSample);
|
| 1369 |
-
__privateMethod(this, _finalizeFragment, finalizeFragment_fn).call(this, false);
|
| 1370 |
-
} else {
|
| 1371 |
-
if (__privateGet(this, _videoTrack))
|
| 1372 |
-
__privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _videoTrack));
|
| 1373 |
-
if (__privateGet(this, _audioTrack))
|
| 1374 |
-
__privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, __privateGet(this, _audioTrack));
|
| 1375 |
-
}
|
| 1376 |
-
let tracks = [__privateGet(this, _videoTrack), __privateGet(this, _audioTrack)].filter(Boolean);
|
| 1377 |
-
if (__privateGet(this, _options).fastStart === "in-memory") {
|
| 1378 |
-
let mdatSize;
|
| 1379 |
-
for (let i = 0; i < 2; i++) {
|
| 1380 |
-
let movieBox2 = moov(tracks, __privateGet(this, _creationTime));
|
| 1381 |
-
let movieBoxSize = __privateGet(this, _writer).measureBox(movieBox2);
|
| 1382 |
-
mdatSize = __privateGet(this, _writer).measureBox(__privateGet(this, _mdat));
|
| 1383 |
-
let currentChunkPos = __privateGet(this, _writer).pos + movieBoxSize + mdatSize;
|
| 1384 |
-
for (let chunk of __privateGet(this, _finalizedChunks)) {
|
| 1385 |
-
chunk.offset = currentChunkPos;
|
| 1386 |
-
for (let { data } of chunk.samples) {
|
| 1387 |
-
currentChunkPos += data.byteLength;
|
| 1388 |
-
mdatSize += data.byteLength;
|
| 1389 |
-
}
|
| 1390 |
-
}
|
| 1391 |
-
if (currentChunkPos < 2 ** 32)
|
| 1392 |
-
break;
|
| 1393 |
-
if (mdatSize >= 2 ** 32)
|
| 1394 |
-
__privateGet(this, _mdat).largeSize = true;
|
| 1395 |
-
}
|
| 1396 |
-
let movieBox = moov(tracks, __privateGet(this, _creationTime));
|
| 1397 |
-
__privateGet(this, _writer).writeBox(movieBox);
|
| 1398 |
-
__privateGet(this, _mdat).size = mdatSize;
|
| 1399 |
-
__privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
|
| 1400 |
-
for (let chunk of __privateGet(this, _finalizedChunks)) {
|
| 1401 |
-
for (let sample of chunk.samples) {
|
| 1402 |
-
__privateGet(this, _writer).write(sample.data);
|
| 1403 |
-
sample.data = null;
|
| 1404 |
-
}
|
| 1405 |
-
}
|
| 1406 |
-
} else if (__privateGet(this, _options).fastStart === "fragmented") {
|
| 1407 |
-
let startPos = __privateGet(this, _writer).pos;
|
| 1408 |
-
let mfraBox = mfra(tracks);
|
| 1409 |
-
__privateGet(this, _writer).writeBox(mfraBox);
|
| 1410 |
-
let mfraBoxSize = __privateGet(this, _writer).pos - startPos;
|
| 1411 |
-
__privateGet(this, _writer).seek(__privateGet(this, _writer).pos - 4);
|
| 1412 |
-
__privateGet(this, _writer).writeU32(mfraBoxSize);
|
| 1413 |
-
} else {
|
| 1414 |
-
let mdatPos = __privateGet(this, _writer).offsets.get(__privateGet(this, _mdat));
|
| 1415 |
-
let mdatSize = __privateGet(this, _writer).pos - mdatPos;
|
| 1416 |
-
__privateGet(this, _mdat).size = mdatSize;
|
| 1417 |
-
__privateGet(this, _mdat).largeSize = mdatSize >= 2 ** 32;
|
| 1418 |
-
__privateGet(this, _writer).patchBox(__privateGet(this, _mdat));
|
| 1419 |
-
let movieBox = moov(tracks, __privateGet(this, _creationTime));
|
| 1420 |
-
if (typeof __privateGet(this, _options).fastStart === "object") {
|
| 1421 |
-
__privateGet(this, _writer).seek(__privateGet(this, _ftypSize));
|
| 1422 |
-
__privateGet(this, _writer).writeBox(movieBox);
|
| 1423 |
-
let remainingBytes = mdatPos - __privateGet(this, _writer).pos;
|
| 1424 |
-
__privateGet(this, _writer).writeBox(free(remainingBytes));
|
| 1425 |
-
} else {
|
| 1426 |
-
__privateGet(this, _writer).writeBox(movieBox);
|
| 1427 |
-
}
|
| 1428 |
-
}
|
| 1429 |
-
__privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
|
| 1430 |
-
__privateGet(this, _writer).finalize();
|
| 1431 |
-
__privateSet(this, _finalized, true);
|
| 1432 |
-
}
|
| 1433 |
-
};
|
| 1434 |
-
_options = new WeakMap();
|
| 1435 |
-
_writer = new WeakMap();
|
| 1436 |
-
_ftypSize = new WeakMap();
|
| 1437 |
-
_mdat = new WeakMap();
|
| 1438 |
-
_videoTrack = new WeakMap();
|
| 1439 |
-
_audioTrack = new WeakMap();
|
| 1440 |
-
_creationTime = new WeakMap();
|
| 1441 |
-
_finalizedChunks = new WeakMap();
|
| 1442 |
-
_nextFragmentNumber = new WeakMap();
|
| 1443 |
-
_videoSampleQueue = new WeakMap();
|
| 1444 |
-
_audioSampleQueue = new WeakMap();
|
| 1445 |
-
_finalized = new WeakMap();
|
| 1446 |
-
_validateOptions = new WeakSet();
|
| 1447 |
-
validateOptions_fn = function(options) {
|
| 1448 |
-
if (typeof options !== "object") {
|
| 1449 |
-
throw new TypeError("The muxer requires an options object to be passed to its constructor.");
|
| 1450 |
-
}
|
| 1451 |
-
if (!(options.target instanceof Target)) {
|
| 1452 |
-
throw new TypeError("The target must be provided and an instance of Target.");
|
| 1453 |
-
}
|
| 1454 |
-
if (options.video) {
|
| 1455 |
-
if (!SUPPORTED_VIDEO_CODECS.includes(options.video.codec)) {
|
| 1456 |
-
throw new TypeError(`Unsupported video codec: ${options.video.codec}`);
|
| 1457 |
-
}
|
| 1458 |
-
if (!Number.isInteger(options.video.width) || options.video.width <= 0) {
|
| 1459 |
-
throw new TypeError(`Invalid video width: ${options.video.width}. Must be a positive integer.`);
|
| 1460 |
-
}
|
| 1461 |
-
if (!Number.isInteger(options.video.height) || options.video.height <= 0) {
|
| 1462 |
-
throw new TypeError(`Invalid video height: ${options.video.height}. Must be a positive integer.`);
|
| 1463 |
-
}
|
| 1464 |
-
const videoRotation = options.video.rotation;
|
| 1465 |
-
if (typeof videoRotation === "number" && ![0, 90, 180, 270].includes(videoRotation)) {
|
| 1466 |
-
throw new TypeError(`Invalid video rotation: ${videoRotation}. Has to be 0, 90, 180 or 270.`);
|
| 1467 |
-
} else if (Array.isArray(videoRotation) && (videoRotation.length !== 9 || videoRotation.some((value) => typeof value !== "number"))) {
|
| 1468 |
-
throw new TypeError(`Invalid video transformation matrix: ${videoRotation.join()}`);
|
| 1469 |
-
}
|
| 1470 |
-
if (options.video.frameRate !== void 0 && (!Number.isInteger(options.video.frameRate) || options.video.frameRate <= 0)) {
|
| 1471 |
-
throw new TypeError(
|
| 1472 |
-
`Invalid video frame rate: ${options.video.frameRate}. Must be a positive integer.`
|
| 1473 |
-
);
|
| 1474 |
-
}
|
| 1475 |
-
}
|
| 1476 |
-
if (options.audio) {
|
| 1477 |
-
if (!SUPPORTED_AUDIO_CODECS.includes(options.audio.codec)) {
|
| 1478 |
-
throw new TypeError(`Unsupported audio codec: ${options.audio.codec}`);
|
| 1479 |
-
}
|
| 1480 |
-
if (!Number.isInteger(options.audio.numberOfChannels) || options.audio.numberOfChannels <= 0) {
|
| 1481 |
-
throw new TypeError(
|
| 1482 |
-
`Invalid number of audio channels: ${options.audio.numberOfChannels}. Must be a positive integer.`
|
| 1483 |
-
);
|
| 1484 |
-
}
|
| 1485 |
-
if (!Number.isInteger(options.audio.sampleRate) || options.audio.sampleRate <= 0) {
|
| 1486 |
-
throw new TypeError(
|
| 1487 |
-
`Invalid audio sample rate: ${options.audio.sampleRate}. Must be a positive integer.`
|
| 1488 |
-
);
|
| 1489 |
-
}
|
| 1490 |
-
}
|
| 1491 |
-
if (options.firstTimestampBehavior && !FIRST_TIMESTAMP_BEHAVIORS.includes(options.firstTimestampBehavior)) {
|
| 1492 |
-
throw new TypeError(`Invalid first timestamp behavior: ${options.firstTimestampBehavior}`);
|
| 1493 |
-
}
|
| 1494 |
-
if (typeof options.fastStart === "object") {
|
| 1495 |
-
if (options.video) {
|
| 1496 |
-
if (options.fastStart.expectedVideoChunks === void 0) {
|
| 1497 |
-
throw new TypeError(`'fastStart' is an object but is missing property 'expectedVideoChunks'.`);
|
| 1498 |
-
} else if (!Number.isInteger(options.fastStart.expectedVideoChunks) || options.fastStart.expectedVideoChunks < 0) {
|
| 1499 |
-
throw new TypeError(`'expectedVideoChunks' must be a non-negative integer.`);
|
| 1500 |
-
}
|
| 1501 |
-
}
|
| 1502 |
-
if (options.audio) {
|
| 1503 |
-
if (options.fastStart.expectedAudioChunks === void 0) {
|
| 1504 |
-
throw new TypeError(`'fastStart' is an object but is missing property 'expectedAudioChunks'.`);
|
| 1505 |
-
} else if (!Number.isInteger(options.fastStart.expectedAudioChunks) || options.fastStart.expectedAudioChunks < 0) {
|
| 1506 |
-
throw new TypeError(`'expectedAudioChunks' must be a non-negative integer.`);
|
| 1507 |
-
}
|
| 1508 |
-
}
|
| 1509 |
-
} else if (![false, "in-memory", "fragmented"].includes(options.fastStart)) {
|
| 1510 |
-
throw new TypeError(`'fastStart' option must be false, 'in-memory', 'fragmented' or an object.`);
|
| 1511 |
-
}
|
| 1512 |
-
if (options.minFragmentDuration !== void 0 && (!Number.isFinite(options.minFragmentDuration) || options.minFragmentDuration < 0)) {
|
| 1513 |
-
throw new TypeError(`'minFragmentDuration' must be a non-negative number.`);
|
| 1514 |
-
}
|
| 1515 |
-
};
|
| 1516 |
-
_writeHeader = new WeakSet();
|
| 1517 |
-
writeHeader_fn = function() {
|
| 1518 |
-
__privateGet(this, _writer).writeBox(ftyp({
|
| 1519 |
-
holdsAvc: __privateGet(this, _options).video?.codec === "avc",
|
| 1520 |
-
fragmented: __privateGet(this, _options).fastStart === "fragmented"
|
| 1521 |
-
}));
|
| 1522 |
-
__privateSet(this, _ftypSize, __privateGet(this, _writer).pos);
|
| 1523 |
-
if (__privateGet(this, _options).fastStart === "in-memory") {
|
| 1524 |
-
__privateSet(this, _mdat, mdat(false));
|
| 1525 |
-
} else if (__privateGet(this, _options).fastStart === "fragmented") {
|
| 1526 |
-
} else {
|
| 1527 |
-
if (typeof __privateGet(this, _options).fastStart === "object") {
|
| 1528 |
-
let moovSizeUpperBound = __privateMethod(this, _computeMoovSizeUpperBound, computeMoovSizeUpperBound_fn).call(this);
|
| 1529 |
-
__privateGet(this, _writer).seek(__privateGet(this, _writer).pos + moovSizeUpperBound);
|
| 1530 |
-
}
|
| 1531 |
-
__privateSet(this, _mdat, mdat(true));
|
| 1532 |
-
__privateGet(this, _writer).writeBox(__privateGet(this, _mdat));
|
| 1533 |
-
}
|
| 1534 |
-
__privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
|
| 1535 |
-
};
|
| 1536 |
-
_computeMoovSizeUpperBound = new WeakSet();
|
| 1537 |
-
computeMoovSizeUpperBound_fn = function() {
|
| 1538 |
-
if (typeof __privateGet(this, _options).fastStart !== "object")
|
| 1539 |
-
return;
|
| 1540 |
-
let upperBound = 0;
|
| 1541 |
-
let sampleCounts = [
|
| 1542 |
-
__privateGet(this, _options).fastStart.expectedVideoChunks,
|
| 1543 |
-
__privateGet(this, _options).fastStart.expectedAudioChunks
|
| 1544 |
-
];
|
| 1545 |
-
for (let n of sampleCounts) {
|
| 1546 |
-
if (!n)
|
| 1547 |
-
continue;
|
| 1548 |
-
upperBound += (4 + 4) * Math.ceil(2 / 3 * n);
|
| 1549 |
-
upperBound += 4 * n;
|
| 1550 |
-
upperBound += (4 + 4 + 4) * Math.ceil(2 / 3 * n);
|
| 1551 |
-
upperBound += 4 * n;
|
| 1552 |
-
upperBound += 8 * n;
|
| 1553 |
-
}
|
| 1554 |
-
upperBound += 4096;
|
| 1555 |
-
return upperBound;
|
| 1556 |
-
};
|
| 1557 |
-
_prepareTracks = new WeakSet();
|
| 1558 |
-
prepareTracks_fn = function() {
|
| 1559 |
-
if (__privateGet(this, _options).video) {
|
| 1560 |
-
__privateSet(this, _videoTrack, {
|
| 1561 |
-
id: 1,
|
| 1562 |
-
info: {
|
| 1563 |
-
type: "video",
|
| 1564 |
-
codec: __privateGet(this, _options).video.codec,
|
| 1565 |
-
width: __privateGet(this, _options).video.width,
|
| 1566 |
-
height: __privateGet(this, _options).video.height,
|
| 1567 |
-
rotation: __privateGet(this, _options).video.rotation ?? 0,
|
| 1568 |
-
decoderConfig: null
|
| 1569 |
-
},
|
| 1570 |
-
// The fallback contains many common frame rates as factors
|
| 1571 |
-
timescale: __privateGet(this, _options).video.frameRate ?? 57600,
|
| 1572 |
-
samples: [],
|
| 1573 |
-
finalizedChunks: [],
|
| 1574 |
-
currentChunk: null,
|
| 1575 |
-
firstDecodeTimestamp: void 0,
|
| 1576 |
-
lastDecodeTimestamp: -1,
|
| 1577 |
-
timeToSampleTable: [],
|
| 1578 |
-
compositionTimeOffsetTable: [],
|
| 1579 |
-
lastTimescaleUnits: null,
|
| 1580 |
-
lastSample: null,
|
| 1581 |
-
compactlyCodedChunkTable: []
|
| 1582 |
-
});
|
| 1583 |
-
}
|
| 1584 |
-
if (__privateGet(this, _options).audio) {
|
| 1585 |
-
__privateSet(this, _audioTrack, {
|
| 1586 |
-
id: __privateGet(this, _options).video ? 2 : 1,
|
| 1587 |
-
info: {
|
| 1588 |
-
type: "audio",
|
| 1589 |
-
codec: __privateGet(this, _options).audio.codec,
|
| 1590 |
-
numberOfChannels: __privateGet(this, _options).audio.numberOfChannels,
|
| 1591 |
-
sampleRate: __privateGet(this, _options).audio.sampleRate,
|
| 1592 |
-
decoderConfig: null
|
| 1593 |
-
},
|
| 1594 |
-
timescale: __privateGet(this, _options).audio.sampleRate,
|
| 1595 |
-
samples: [],
|
| 1596 |
-
finalizedChunks: [],
|
| 1597 |
-
currentChunk: null,
|
| 1598 |
-
firstDecodeTimestamp: void 0,
|
| 1599 |
-
lastDecodeTimestamp: -1,
|
| 1600 |
-
timeToSampleTable: [],
|
| 1601 |
-
compositionTimeOffsetTable: [],
|
| 1602 |
-
lastTimescaleUnits: null,
|
| 1603 |
-
lastSample: null,
|
| 1604 |
-
compactlyCodedChunkTable: []
|
| 1605 |
-
});
|
| 1606 |
-
if (__privateGet(this, _options).audio.codec === "aac") {
|
| 1607 |
-
let guessedCodecPrivate = __privateMethod(this, _generateMpeg4AudioSpecificConfig, generateMpeg4AudioSpecificConfig_fn).call(
|
| 1608 |
-
this,
|
| 1609 |
-
2,
|
| 1610 |
-
// Object type for AAC-LC, since it's the most common
|
| 1611 |
-
__privateGet(this, _options).audio.sampleRate,
|
| 1612 |
-
__privateGet(this, _options).audio.numberOfChannels
|
| 1613 |
-
);
|
| 1614 |
-
__privateGet(this, _audioTrack).info.decoderConfig = {
|
| 1615 |
-
codec: __privateGet(this, _options).audio.codec,
|
| 1616 |
-
description: guessedCodecPrivate,
|
| 1617 |
-
numberOfChannels: __privateGet(this, _options).audio.numberOfChannels,
|
| 1618 |
-
sampleRate: __privateGet(this, _options).audio.sampleRate
|
| 1619 |
-
};
|
| 1620 |
-
}
|
| 1621 |
-
}
|
| 1622 |
-
};
|
| 1623 |
-
_generateMpeg4AudioSpecificConfig = new WeakSet();
|
| 1624 |
-
generateMpeg4AudioSpecificConfig_fn = function(objectType, sampleRate, numberOfChannels) {
|
| 1625 |
-
let frequencyIndices = [96e3, 88200, 64e3, 48e3, 44100, 32e3, 24e3, 22050, 16e3, 12e3, 11025, 8e3, 7350];
|
| 1626 |
-
let frequencyIndex = frequencyIndices.indexOf(sampleRate);
|
| 1627 |
-
let channelConfig = numberOfChannels;
|
| 1628 |
-
let configBits = "";
|
| 1629 |
-
configBits += objectType.toString(2).padStart(5, "0");
|
| 1630 |
-
configBits += frequencyIndex.toString(2).padStart(4, "0");
|
| 1631 |
-
if (frequencyIndex === 15)
|
| 1632 |
-
configBits += sampleRate.toString(2).padStart(24, "0");
|
| 1633 |
-
configBits += channelConfig.toString(2).padStart(4, "0");
|
| 1634 |
-
let paddingLength = Math.ceil(configBits.length / 8) * 8;
|
| 1635 |
-
configBits = configBits.padEnd(paddingLength, "0");
|
| 1636 |
-
let configBytes = new Uint8Array(configBits.length / 8);
|
| 1637 |
-
for (let i = 0; i < configBits.length; i += 8) {
|
| 1638 |
-
configBytes[i / 8] = parseInt(configBits.slice(i, i + 8), 2);
|
| 1639 |
-
}
|
| 1640 |
-
return configBytes;
|
| 1641 |
-
};
|
| 1642 |
-
_createSampleForTrack = new WeakSet();
|
| 1643 |
-
createSampleForTrack_fn = function(track, data, type, timestamp, duration, meta, compositionTimeOffset) {
|
| 1644 |
-
let presentationTimestampInSeconds = timestamp / 1e6;
|
| 1645 |
-
let decodeTimestampInSeconds = (timestamp - (compositionTimeOffset ?? 0)) / 1e6;
|
| 1646 |
-
let durationInSeconds = duration / 1e6;
|
| 1647 |
-
let adjusted = __privateMethod(this, _validateTimestamp, validateTimestamp_fn).call(this, presentationTimestampInSeconds, decodeTimestampInSeconds, track);
|
| 1648 |
-
presentationTimestampInSeconds = adjusted.presentationTimestamp;
|
| 1649 |
-
decodeTimestampInSeconds = adjusted.decodeTimestamp;
|
| 1650 |
-
if (meta?.decoderConfig) {
|
| 1651 |
-
if (track.info.decoderConfig === null) {
|
| 1652 |
-
track.info.decoderConfig = meta.decoderConfig;
|
| 1653 |
-
} else {
|
| 1654 |
-
Object.assign(track.info.decoderConfig, meta.decoderConfig);
|
| 1655 |
-
}
|
| 1656 |
-
}
|
| 1657 |
-
let sample = {
|
| 1658 |
-
presentationTimestamp: presentationTimestampInSeconds,
|
| 1659 |
-
decodeTimestamp: decodeTimestampInSeconds,
|
| 1660 |
-
duration: durationInSeconds,
|
| 1661 |
-
data,
|
| 1662 |
-
size: data.byteLength,
|
| 1663 |
-
type,
|
| 1664 |
-
// Will be refined once the next sample comes in
|
| 1665 |
-
timescaleUnitsToNextSample: intoTimescale(durationInSeconds, track.timescale)
|
| 1666 |
-
};
|
| 1667 |
-
return sample;
|
| 1668 |
-
};
|
| 1669 |
-
_addSampleToTrack = new WeakSet();
|
| 1670 |
-
addSampleToTrack_fn = function(track, sample) {
|
| 1671 |
-
if (__privateGet(this, _options).fastStart !== "fragmented") {
|
| 1672 |
-
track.samples.push(sample);
|
| 1673 |
-
}
|
| 1674 |
-
const sampleCompositionTimeOffset = intoTimescale(sample.presentationTimestamp - sample.decodeTimestamp, track.timescale);
|
| 1675 |
-
if (track.lastTimescaleUnits !== null) {
|
| 1676 |
-
let timescaleUnits = intoTimescale(sample.decodeTimestamp, track.timescale, false);
|
| 1677 |
-
let delta = Math.round(timescaleUnits - track.lastTimescaleUnits);
|
| 1678 |
-
track.lastTimescaleUnits += delta;
|
| 1679 |
-
track.lastSample.timescaleUnitsToNextSample = delta;
|
| 1680 |
-
if (__privateGet(this, _options).fastStart !== "fragmented") {
|
| 1681 |
-
let lastTableEntry = last(track.timeToSampleTable);
|
| 1682 |
-
if (lastTableEntry.sampleCount === 1) {
|
| 1683 |
-
lastTableEntry.sampleDelta = delta;
|
| 1684 |
-
lastTableEntry.sampleCount++;
|
| 1685 |
-
} else if (lastTableEntry.sampleDelta === delta) {
|
| 1686 |
-
lastTableEntry.sampleCount++;
|
| 1687 |
-
} else {
|
| 1688 |
-
lastTableEntry.sampleCount--;
|
| 1689 |
-
track.timeToSampleTable.push({
|
| 1690 |
-
sampleCount: 2,
|
| 1691 |
-
sampleDelta: delta
|
| 1692 |
-
});
|
| 1693 |
-
}
|
| 1694 |
-
const lastCompositionTimeOffsetTableEntry = last(track.compositionTimeOffsetTable);
|
| 1695 |
-
if (lastCompositionTimeOffsetTableEntry.sampleCompositionTimeOffset === sampleCompositionTimeOffset) {
|
| 1696 |
-
lastCompositionTimeOffsetTableEntry.sampleCount++;
|
| 1697 |
-
} else {
|
| 1698 |
-
track.compositionTimeOffsetTable.push({
|
| 1699 |
-
sampleCount: 1,
|
| 1700 |
-
sampleCompositionTimeOffset
|
| 1701 |
-
});
|
| 1702 |
-
}
|
| 1703 |
-
}
|
| 1704 |
-
} else {
|
| 1705 |
-
track.lastTimescaleUnits = 0;
|
| 1706 |
-
if (__privateGet(this, _options).fastStart !== "fragmented") {
|
| 1707 |
-
track.timeToSampleTable.push({
|
| 1708 |
-
sampleCount: 1,
|
| 1709 |
-
sampleDelta: intoTimescale(sample.duration, track.timescale)
|
| 1710 |
-
});
|
| 1711 |
-
track.compositionTimeOffsetTable.push({
|
| 1712 |
-
sampleCount: 1,
|
| 1713 |
-
sampleCompositionTimeOffset
|
| 1714 |
-
});
|
| 1715 |
-
}
|
| 1716 |
-
}
|
| 1717 |
-
track.lastSample = sample;
|
| 1718 |
-
let beginNewChunk = false;
|
| 1719 |
-
if (!track.currentChunk) {
|
| 1720 |
-
beginNewChunk = true;
|
| 1721 |
-
} else {
|
| 1722 |
-
let currentChunkDuration = sample.presentationTimestamp - track.currentChunk.startTimestamp;
|
| 1723 |
-
if (__privateGet(this, _options).fastStart === "fragmented") {
|
| 1724 |
-
let mostImportantTrack = __privateGet(this, _videoTrack) ?? __privateGet(this, _audioTrack);
|
| 1725 |
-
const chunkDuration = __privateGet(this, _options).minFragmentDuration ?? 1;
|
| 1726 |
-
if (track === mostImportantTrack && sample.type === "key" && currentChunkDuration >= chunkDuration) {
|
| 1727 |
-
beginNewChunk = true;
|
| 1728 |
-
__privateMethod(this, _finalizeFragment, finalizeFragment_fn).call(this);
|
| 1729 |
-
}
|
| 1730 |
-
} else {
|
| 1731 |
-
beginNewChunk = currentChunkDuration >= 0.5;
|
| 1732 |
-
}
|
| 1733 |
-
}
|
| 1734 |
-
if (beginNewChunk) {
|
| 1735 |
-
if (track.currentChunk) {
|
| 1736 |
-
__privateMethod(this, _finalizeCurrentChunk, finalizeCurrentChunk_fn).call(this, track);
|
| 1737 |
-
}
|
| 1738 |
-
track.currentChunk = {
|
| 1739 |
-
startTimestamp: sample.presentationTimestamp,
|
| 1740 |
-
samples: []
|
| 1741 |
-
};
|
| 1742 |
-
}
|
| 1743 |
-
track.currentChunk.samples.push(sample);
|
| 1744 |
-
};
|
| 1745 |
-
_validateTimestamp = new WeakSet();
|
| 1746 |
-
validateTimestamp_fn = function(presentationTimestamp, decodeTimestamp, track) {
|
| 1747 |
-
const strictTimestampBehavior = __privateGet(this, _options).firstTimestampBehavior === "strict";
|
| 1748 |
-
const noLastDecodeTimestamp = track.lastDecodeTimestamp === -1;
|
| 1749 |
-
const timestampNonZero = decodeTimestamp !== 0;
|
| 1750 |
-
if (strictTimestampBehavior && noLastDecodeTimestamp && timestampNonZero) {
|
| 1751 |
-
throw new Error(
|
| 1752 |
-
`The first chunk for your media track must have a timestamp of 0 (received DTS=${decodeTimestamp}).Non-zero first timestamps are often caused by directly piping frames or audio data from a MediaStreamTrack into the encoder. Their timestamps are typically relative to the age of thedocument, which is probably what you want.
|
| 1753 |
-
|
| 1754 |
-
If you want to offset all timestamps of a track such that the first one is zero, set firstTimestampBehavior: 'offset' in the options.
|
| 1755 |
-
`
|
| 1756 |
-
);
|
| 1757 |
-
} else if (__privateGet(this, _options).firstTimestampBehavior === "offset" || __privateGet(this, _options).firstTimestampBehavior === "cross-track-offset") {
|
| 1758 |
-
if (track.firstDecodeTimestamp === void 0) {
|
| 1759 |
-
track.firstDecodeTimestamp = decodeTimestamp;
|
| 1760 |
-
}
|
| 1761 |
-
let baseDecodeTimestamp;
|
| 1762 |
-
if (__privateGet(this, _options).firstTimestampBehavior === "offset") {
|
| 1763 |
-
baseDecodeTimestamp = track.firstDecodeTimestamp;
|
| 1764 |
-
} else {
|
| 1765 |
-
baseDecodeTimestamp = Math.min(
|
| 1766 |
-
__privateGet(this, _videoTrack)?.firstDecodeTimestamp ?? Infinity,
|
| 1767 |
-
__privateGet(this, _audioTrack)?.firstDecodeTimestamp ?? Infinity
|
| 1768 |
-
);
|
| 1769 |
-
}
|
| 1770 |
-
decodeTimestamp -= baseDecodeTimestamp;
|
| 1771 |
-
presentationTimestamp -= baseDecodeTimestamp;
|
| 1772 |
-
}
|
| 1773 |
-
if (decodeTimestamp < track.lastDecodeTimestamp) {
|
| 1774 |
-
throw new Error(
|
| 1775 |
-
`Timestamps must be monotonically increasing (DTS went from ${track.lastDecodeTimestamp * 1e6} to ${decodeTimestamp * 1e6}).`
|
| 1776 |
-
);
|
| 1777 |
-
}
|
| 1778 |
-
track.lastDecodeTimestamp = decodeTimestamp;
|
| 1779 |
-
return { presentationTimestamp, decodeTimestamp };
|
| 1780 |
-
};
|
| 1781 |
-
_finalizeCurrentChunk = new WeakSet();
|
| 1782 |
-
finalizeCurrentChunk_fn = function(track) {
|
| 1783 |
-
if (__privateGet(this, _options).fastStart === "fragmented") {
|
| 1784 |
-
throw new Error("Can't finalize individual chunks if 'fastStart' is set to 'fragmented'.");
|
| 1785 |
-
}
|
| 1786 |
-
if (!track.currentChunk)
|
| 1787 |
-
return;
|
| 1788 |
-
track.finalizedChunks.push(track.currentChunk);
|
| 1789 |
-
__privateGet(this, _finalizedChunks).push(track.currentChunk);
|
| 1790 |
-
if (track.compactlyCodedChunkTable.length === 0 || last(track.compactlyCodedChunkTable).samplesPerChunk !== track.currentChunk.samples.length) {
|
| 1791 |
-
track.compactlyCodedChunkTable.push({
|
| 1792 |
-
firstChunk: track.finalizedChunks.length,
|
| 1793 |
-
// 1-indexed
|
| 1794 |
-
samplesPerChunk: track.currentChunk.samples.length
|
| 1795 |
-
});
|
| 1796 |
-
}
|
| 1797 |
-
if (__privateGet(this, _options).fastStart === "in-memory") {
|
| 1798 |
-
track.currentChunk.offset = 0;
|
| 1799 |
-
return;
|
| 1800 |
-
}
|
| 1801 |
-
track.currentChunk.offset = __privateGet(this, _writer).pos;
|
| 1802 |
-
for (let sample of track.currentChunk.samples) {
|
| 1803 |
-
__privateGet(this, _writer).write(sample.data);
|
| 1804 |
-
sample.data = null;
|
| 1805 |
-
}
|
| 1806 |
-
__privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
|
| 1807 |
-
};
|
| 1808 |
-
_finalizeFragment = new WeakSet();
|
| 1809 |
-
finalizeFragment_fn = function(flushStreamingWriter = true) {
|
| 1810 |
-
if (__privateGet(this, _options).fastStart !== "fragmented") {
|
| 1811 |
-
throw new Error("Can't finalize a fragment unless 'fastStart' is set to 'fragmented'.");
|
| 1812 |
-
}
|
| 1813 |
-
let tracks = [__privateGet(this, _videoTrack), __privateGet(this, _audioTrack)].filter((track) => track && track.currentChunk);
|
| 1814 |
-
if (tracks.length === 0)
|
| 1815 |
-
return;
|
| 1816 |
-
let fragmentNumber = __privateWrapper(this, _nextFragmentNumber)._++;
|
| 1817 |
-
if (fragmentNumber === 1) {
|
| 1818 |
-
let movieBox = moov(tracks, __privateGet(this, _creationTime), true);
|
| 1819 |
-
__privateGet(this, _writer).writeBox(movieBox);
|
| 1820 |
-
}
|
| 1821 |
-
let moofOffset = __privateGet(this, _writer).pos;
|
| 1822 |
-
let moofBox = moof(fragmentNumber, tracks);
|
| 1823 |
-
__privateGet(this, _writer).writeBox(moofBox);
|
| 1824 |
-
{
|
| 1825 |
-
let mdatBox = mdat(false);
|
| 1826 |
-
let totalTrackSampleSize = 0;
|
| 1827 |
-
for (let track of tracks) {
|
| 1828 |
-
for (let sample of track.currentChunk.samples) {
|
| 1829 |
-
totalTrackSampleSize += sample.size;
|
| 1830 |
-
}
|
| 1831 |
-
}
|
| 1832 |
-
let mdatSize = __privateGet(this, _writer).measureBox(mdatBox) + totalTrackSampleSize;
|
| 1833 |
-
if (mdatSize >= 2 ** 32) {
|
| 1834 |
-
mdatBox.largeSize = true;
|
| 1835 |
-
mdatSize = __privateGet(this, _writer).measureBox(mdatBox) + totalTrackSampleSize;
|
| 1836 |
-
}
|
| 1837 |
-
mdatBox.size = mdatSize;
|
| 1838 |
-
__privateGet(this, _writer).writeBox(mdatBox);
|
| 1839 |
-
}
|
| 1840 |
-
for (let track of tracks) {
|
| 1841 |
-
track.currentChunk.offset = __privateGet(this, _writer).pos;
|
| 1842 |
-
track.currentChunk.moofOffset = moofOffset;
|
| 1843 |
-
for (let sample of track.currentChunk.samples) {
|
| 1844 |
-
__privateGet(this, _writer).write(sample.data);
|
| 1845 |
-
sample.data = null;
|
| 1846 |
-
}
|
| 1847 |
-
}
|
| 1848 |
-
let endPos = __privateGet(this, _writer).pos;
|
| 1849 |
-
__privateGet(this, _writer).seek(__privateGet(this, _writer).offsets.get(moofBox));
|
| 1850 |
-
let newMoofBox = moof(fragmentNumber, tracks);
|
| 1851 |
-
__privateGet(this, _writer).writeBox(newMoofBox);
|
| 1852 |
-
__privateGet(this, _writer).seek(endPos);
|
| 1853 |
-
for (let track of tracks) {
|
| 1854 |
-
track.finalizedChunks.push(track.currentChunk);
|
| 1855 |
-
__privateGet(this, _finalizedChunks).push(track.currentChunk);
|
| 1856 |
-
track.currentChunk = null;
|
| 1857 |
-
}
|
| 1858 |
-
if (flushStreamingWriter) {
|
| 1859 |
-
__privateMethod(this, _maybeFlushStreamingTargetWriter, maybeFlushStreamingTargetWriter_fn).call(this);
|
| 1860 |
-
}
|
| 1861 |
-
};
|
| 1862 |
-
_maybeFlushStreamingTargetWriter = new WeakSet();
|
| 1863 |
-
maybeFlushStreamingTargetWriter_fn = function() {
|
| 1864 |
-
if (__privateGet(this, _writer) instanceof StreamTargetWriter) {
|
| 1865 |
-
__privateGet(this, _writer).flush();
|
| 1866 |
-
}
|
| 1867 |
-
};
|
| 1868 |
-
_ensureNotFinalized = new WeakSet();
|
| 1869 |
-
ensureNotFinalized_fn = function() {
|
| 1870 |
-
if (__privateGet(this, _finalized)) {
|
| 1871 |
-
throw new Error("Cannot add new video or audio chunks after the file has been finalized.");
|
| 1872 |
-
}
|
| 1873 |
-
};
|
| 1874 |
-
export {
|
| 1875 |
-
ArrayBufferTarget,
|
| 1876 |
-
FileSystemWritableFileStreamTarget,
|
| 1877 |
-
Muxer,
|
| 1878 |
-
StreamTarget
|
| 1879 |
-
};
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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