@file-viewer/renderer-media 2.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,160 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking systems
52
+ that are managed by, or on behalf of, the Licensor for the purpose of discussing
53
+ and improving the Work, but excluding communication that is conspicuously marked
54
+ or otherwise designated in writing by the copyright owner as "Not a
55
+ Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
62
+ License, each Contributor hereby grants to You a perpetual, worldwide,
63
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
64
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
65
+ sublicense, and distribute the Work and such Derivative Works in Source or
66
+ Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
69
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
70
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
71
+ license to make, have made, use, offer to sell, sell, import, and otherwise
72
+ transfer the Work, where such license applies only to those patent claims
73
+ licensable by such Contributor that are necessarily infringed by their
74
+ Contribution(s) alone or by combination of their Contribution(s) with the Work to
75
+ which such Contribution(s) was submitted. If You institute patent litigation
76
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
77
+ alleging that the Work or a Contribution incorporated within the Work
78
+ constitutes direct or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate as of the date
80
+ such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
83
+ Derivative Works thereof in any medium, with or without modifications, and in
84
+ Source or Object form, provided that You meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
87
+ this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices stating that
90
+ You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works that You
93
+ distribute, all copyright, patent, trademark, and attribution notices from the
94
+ Source form of the Work, excluding those notices that do not pertain to any part
95
+ of the Derivative Works; and
96
+
97
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
98
+ any Derivative Works that You distribute must include a readable copy of the
99
+ attribution notices contained within such NOTICE file, excluding those notices
100
+ that do not pertain to any part of the Derivative Works, in at least one of the
101
+ following places: within a NOTICE text file distributed as part of the Derivative
102
+ Works; within the Source form or documentation, if provided along with the
103
+ Derivative Works; or, within a display generated by the Derivative Works, if and
104
+ wherever such third-party notices normally appear. The contents of the NOTICE
105
+ file are for informational purposes only and do not modify the License. You may
106
+ add Your own attribution notices within Derivative Works that You distribute,
107
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
108
+ additional attribution notices cannot be construed as modifying the License.
109
+
110
+ You may add Your own copyright statement to Your modifications and may provide
111
+ additional or different license terms and conditions for use, reproduction, or
112
+ distribution of Your modifications, or for any such Derivative Works as a whole,
113
+ provided Your use, reproduction, and distribution of the Work otherwise complies
114
+ with the conditions stated in this License.
115
+
116
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
117
+ Contribution intentionally submitted for inclusion in the Work by You to the
118
+ Licensor shall be under the terms and conditions of this License, without any
119
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
120
+ supersede or modify the terms of any separate license agreement you may have
121
+ executed with Licensor regarding such Contributions.
122
+
123
+ 6. Trademarks. This License does not grant permission to use the trade names,
124
+ trademarks, service marks, or product names of the Licensor, except as required
125
+ for reasonable and customary use in describing the origin of the Work and
126
+ reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
129
+ writing, Licensor provides the Work (and each Contributor provides its
130
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
131
+ KIND, either express or implied, including, without limitation, any warranties or
132
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
133
+ PARTICULAR PURPOSE. You are solely responsible for determining the
134
+ appropriateness of using or redistributing the Work and assume any risks
135
+ associated with Your exercise of permissions under this License.
136
+
137
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
138
+ tort (including negligence), contract, or otherwise, unless required by
139
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
140
+ writing, shall any Contributor be liable to You for damages, including any
141
+ direct, indirect, special, incidental, or consequential damages of any character
142
+ arising as a result of this License or out of the use or inability to use the
143
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
144
+ computer failure or malfunction, or any and all other commercial damages or
145
+ losses), even if such Contributor has been advised of the possibility of such
146
+ damages.
147
+
148
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
150
+ acceptance of support, warranty, indemnity, or other liability obligations and/or
151
+ rights consistent with this License. However, in accepting such obligations, You
152
+ may act only on Your own behalf and on Your sole responsibility, not on behalf of
153
+ any other Contributor, and only if You agree to indemnify, defend, and hold each
154
+ Contributor harmless for any liability incurred by, or claims asserted against,
155
+ such Contributor by reason of your accepting any such warranty or additional
156
+ liability.
157
+
158
+ END OF TERMS AND CONDITIONS
159
+
160
+ Copyright 2026 Flyfish Viewer
package/README.en.md ADDED
@@ -0,0 +1,36 @@
1
+ # @file-viewer/renderer-media
2
+
3
+ Standalone audio and video renderer package for Flyfish File Viewer. It previews audio files, videos, HLS playlists, and MIDI files in the browser while loading `hls.js` and `@tonejs/midi` only for the formats that need them.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import { mediaRenderer } from '@file-viewer/renderer-media'
9
+
10
+ const options = {
11
+ builtinRenderers: 'none',
12
+ renderers: [mediaRenderer],
13
+ }
14
+ ```
15
+
16
+ Or compose it through the full preset:
17
+
18
+ ```ts
19
+ import { allRenderers } from '@file-viewer/preset-all'
20
+
21
+ const options = {
22
+ builtinRenderers: 'none',
23
+ renderers: allRenderers,
24
+ }
25
+ ```
26
+
27
+ ## Features
28
+
29
+ - MP4, WebM, and common audio formats use native browser `<video>` / `<audio>` controls first.
30
+ - HLS `.m3u8` uses native playback when available and dynamically imports `hls.js` only as a fallback.
31
+ - MIDI / MID dynamically imports `@tonejs/midi` only when opened, then renders name, duration, PPQ, tracks, and note summaries.
32
+ - Unmount cleanup revokes object URLs, resets media elements, and destroys the HLS instance for long-lived business applications.
33
+
34
+ ## Migration Note
35
+
36
+ `@file-viewer/core` no longer bundles media renderers and no longer depends directly on `hls.js` or `@tonejs/midi`. Install this package explicitly for audio, video, HLS, or MIDI preview, or use `@file-viewer/preset-all`, which aggregates this renderer automatically.
package/README.md ADDED
@@ -0,0 +1,36 @@
1
+ # @file-viewer/renderer-media
2
+
3
+ Flyfish File Viewer 的独立音视频 renderer 包。它负责音频、视频、HLS 清单和 MIDI 文件的浏览器端预览,并让 `hls.js`、`@tonejs/midi` 只在命中对应格式时加载。
4
+
5
+ ## 使用
6
+
7
+ ```ts
8
+ import { mediaRenderer } from '@file-viewer/renderer-media'
9
+
10
+ const options = {
11
+ builtinRenderers: 'none',
12
+ renderers: [mediaRenderer],
13
+ }
14
+ ```
15
+
16
+ 也可以通过全量 preset 自动装配:
17
+
18
+ ```ts
19
+ import { allRenderers } from '@file-viewer/preset-all'
20
+
21
+ const options = {
22
+ builtinRenderers: 'none',
23
+ renderers: allRenderers,
24
+ }
25
+ ```
26
+
27
+ ## 能力
28
+
29
+ - MP4、WebM 和常见音频格式优先使用浏览器原生 `<video>` / `<audio>` 控件。
30
+ - HLS `.m3u8` 优先使用浏览器原生能力,不支持时才按需加载 `hls.js`。
31
+ - MIDI / MID 只在命中格式时按需加载 `@tonejs/midi`,展示曲名、时长、PPQ、轨道和音符摘要。
32
+ - 所有资源在卸载时清理对象 URL、播放器状态和 HLS 实例,适合长时间运行的后台系统。
33
+
34
+ ## 迁移说明
35
+
36
+ `@file-viewer/core` 已不再内置 media renderer,也不再直接依赖 `hls.js` 和 `@tonejs/midi`。需要音频、视频、HLS 或 MIDI 预览时,请显式安装本包,或使用会自动聚合本包的 `@file-viewer/preset-all`。
@@ -0,0 +1,8 @@
1
+ import type { FileViewerRenderedInstance } from '@file-viewer/core';
2
+ /**
3
+ * Pure TypeScript audio renderer.
4
+ *
5
+ * Regular audio files use the browser's native `<audio>` element. MIDI stays in
6
+ * the same async chunk and lazily imports `@tonejs/midi` only for `.mid/.midi`.
7
+ */
8
+ export default function renderAudio(buffer: ArrayBuffer, target: HTMLDivElement, type?: string): Promise<FileViewerRenderedInstance>;
package/dist/audio.js ADDED
@@ -0,0 +1,219 @@
1
+ const AUDIO_MIME_MAP = {
2
+ aac: 'audio/aac',
3
+ flac: 'audio/flac',
4
+ m4a: 'audio/mp4',
5
+ mp3: 'audio/mpeg',
6
+ mpeg: 'audio/mpeg',
7
+ oga: 'audio/ogg',
8
+ ogg: 'audio/ogg',
9
+ opus: 'audio/ogg; codecs=opus',
10
+ wav: 'audio/wav',
11
+ weba: 'audio/webm'
12
+ };
13
+ const audioStyle = `
14
+ .fv-audio-viewer{width:100%;min-height:100%;display:flex;align-items:center;justify-content:center;padding:28px;background:linear-gradient(135deg,rgba(14,116,144,.1),transparent 34%),linear-gradient(180deg,#f5f8fb 0%,#edf2f7 100%);box-sizing:border-box}
15
+ .fv-audio-card{width:min(100%,640px);display:grid;grid-template-columns:86px minmax(0,1fr);gap:18px;align-items:center;padding:24px;border-radius:8px;border:1px solid rgba(15,23,42,.08);background:rgba(255,255,255,.92);box-shadow:0 20px 52px rgba(15,23,42,.13);box-sizing:border-box}
16
+ .fv-audio-art{position:relative;width:86px;height:86px;border-radius:8px;background:linear-gradient(135deg,#0f766e,#2dd4bf);box-shadow:inset 0 0 0 1px rgba(255,255,255,.24)}
17
+ .fv-audio-art span{position:absolute;inset:18px;border-radius:999px;border:8px solid rgba(255,255,255,.88)}
18
+ .fv-audio-art i{position:absolute;right:18px;bottom:20px;width:18px;height:36px;border-radius:10px 10px 4px 4px;background:rgba(255,255,255,.9)}
19
+ .fv-audio-copy{min-width:0}
20
+ .fv-audio-kicker{color:#0f766e;font-size:12px;font-weight:800;letter-spacing:0}
21
+ .fv-audio-copy strong{display:block;margin-top:5px;color:#132235;font-size:23px;line-height:1.15}
22
+ .fv-audio-copy p{margin:8px 0 0;color:#64748b;font-size:13px;line-height:1.7}
23
+ .fv-audio-meter{grid-column:1/-1;display:grid;grid-template-columns:48px minmax(0,1fr) 48px;align-items:center;gap:10px;color:#64748b;font-size:12px;font-variant-numeric:tabular-nums}
24
+ .fv-audio-progress{height:6px;overflow:hidden;border-radius:999px;background:rgba(15,118,110,.12)}
25
+ .fv-audio-progress i{display:block;height:100%;border-radius:inherit;background:linear-gradient(90deg,#0f766e,#2dd4bf);transition:width .18s ease}
26
+ .fv-audio-control{grid-column:1/-1;width:100%;height:42px}
27
+ .fv-midi-viewer{min-height:100%;padding:28px;background:#eef1f4;box-sizing:border-box}
28
+ .fv-midi-card{max-width:960px;margin:0 auto;border-radius:8px;border:1px solid rgba(15,23,42,.08);background:#fff;box-shadow:0 18px 48px rgba(15,23,42,.12);overflow:hidden}
29
+ .fv-midi-card header{padding:18px 22px;border-bottom:1px solid rgba(15,23,42,.08)}
30
+ .fv-midi-card header span{display:block;color:#0f766e;font-size:12px;font-weight:800}
31
+ .fv-midi-card header strong{display:block;margin-top:6px;color:#132235;font-size:22px}
32
+ .fv-midi-state{padding:28px 22px;color:#64748b}
33
+ .fv-midi-error{color:#b42318}
34
+ .fv-midi-stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:1px;background:rgba(15,23,42,.08)}
35
+ .fv-midi-stats div{padding:16px;background:#f8fafc}
36
+ .fv-midi-stats span{display:block;color:#64748b;font-size:12px}
37
+ .fv-midi-stats strong{display:block;margin-top:4px;color:#132235;font-size:20px}
38
+ .fv-midi-table-wrap{overflow:auto}
39
+ .fv-midi-table{width:100%;border-collapse:collapse;color:#132235;font-size:14px}
40
+ .fv-midi-table th,.fv-midi-table td{padding:12px 16px;border-top:1px solid rgba(15,23,42,.08);text-align:left}
41
+ .fv-midi-table th{color:#64748b;background:#f8fafc;font-weight:700}
42
+ @media (max-width:700px){.fv-midi-stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
43
+ `;
44
+ const createElement = (tagName, className, text) => {
45
+ const element = document.createElement(tagName);
46
+ if (className) {
47
+ element.className = className;
48
+ }
49
+ if (typeof text === 'string') {
50
+ element.textContent = text;
51
+ }
52
+ return element;
53
+ };
54
+ const formatDuration = (seconds) => {
55
+ if (!Number.isFinite(seconds) || seconds <= 0) {
56
+ return '00:00';
57
+ }
58
+ const minutes = Math.floor(seconds / 60);
59
+ const rest = Math.round(seconds % 60);
60
+ return `${String(minutes).padStart(2, '0')}:${String(rest).padStart(2, '0')}`;
61
+ };
62
+ const createStyle = () => {
63
+ const style = document.createElement('style');
64
+ style.textContent = audioStyle;
65
+ return style;
66
+ };
67
+ const clearTarget = (target) => {
68
+ target.replaceChildren();
69
+ };
70
+ const createRenderedInstance = (target, cleanup) => ({
71
+ $el: target,
72
+ unmount() {
73
+ cleanup();
74
+ clearTarget(target);
75
+ }
76
+ });
77
+ const renderAudioElement = (buffer, target, type) => {
78
+ const normalizedType = type.trim().toLowerCase() || 'mp3';
79
+ const mimeType = AUDIO_MIME_MAP[normalizedType] || 'audio/*';
80
+ const sourceUrl = URL.createObjectURL(new Blob([buffer], { type: mimeType }));
81
+ const root = createElement('div', 'fv-audio-viewer');
82
+ const card = createElement('section', 'fv-audio-card');
83
+ const art = createElement('div', 'fv-audio-art');
84
+ art.append(createElement('span'), createElement('i'));
85
+ const copy = createElement('div', 'fv-audio-copy');
86
+ copy.append(createElement('span', 'fv-audio-kicker', normalizedType.toUpperCase() || 'AUDIO'), createElement('strong', '', '音频预览'), createElement('p', '', '使用浏览器原生播放器打开,兼容性取决于当前浏览器支持的音频编码。'));
87
+ const currentTimeText = createElement('span', '', '00:00');
88
+ const durationText = createElement('span', '', '--:--');
89
+ const progressFill = createElement('i');
90
+ const progress = createElement('div', 'fv-audio-progress');
91
+ progress.setAttribute('aria-hidden', 'true');
92
+ progress.append(progressFill);
93
+ const meter = createElement('div', 'fv-audio-meter');
94
+ meter.append(currentTimeText, progress, durationText);
95
+ const audio = createElement('audio', 'fv-audio-control');
96
+ audio.src = sourceUrl;
97
+ audio.controls = true;
98
+ audio.preload = 'metadata';
99
+ audio.textContent = '当前浏览器不支持音频播放。';
100
+ const handleLoadedMetadata = () => {
101
+ durationText.textContent = Number.isFinite(audio.duration) && audio.duration > 0
102
+ ? formatDuration(audio.duration)
103
+ : '--:--';
104
+ };
105
+ const handleTimeUpdate = () => {
106
+ currentTimeText.textContent = formatDuration(audio.currentTime);
107
+ const percent = Number.isFinite(audio.duration) && audio.duration > 0
108
+ ? Math.min(100, Math.max(0, audio.currentTime / audio.duration * 100))
109
+ : 0;
110
+ progressFill.style.width = `${percent}%`;
111
+ };
112
+ audio.addEventListener('loadedmetadata', handleLoadedMetadata);
113
+ audio.addEventListener('timeupdate', handleTimeUpdate);
114
+ card.append(art, copy, meter, audio);
115
+ root.append(card);
116
+ target.replaceChildren(createStyle(), root);
117
+ return createRenderedInstance(target, () => {
118
+ audio.pause();
119
+ audio.removeEventListener('loadedmetadata', handleLoadedMetadata);
120
+ audio.removeEventListener('timeupdate', handleTimeUpdate);
121
+ URL.revokeObjectURL(sourceUrl);
122
+ });
123
+ };
124
+ const renderMidiElement = (buffer, target) => {
125
+ let disposed = false;
126
+ const root = createElement('div', 'fv-midi-viewer');
127
+ const card = createElement('section', 'fv-midi-card');
128
+ const header = document.createElement('header');
129
+ const title = createElement('strong', '', 'MIDI 文件');
130
+ header.append(createElement('span', '', 'MIDI'), title);
131
+ const body = createElement('div', 'fv-midi-state', '正在解析 MIDI 轨道...');
132
+ card.append(header, body);
133
+ root.append(card);
134
+ target.replaceChildren(createStyle(), root);
135
+ const renderError = (message) => {
136
+ body.className = 'fv-midi-state fv-midi-error';
137
+ body.textContent = message;
138
+ };
139
+ const renderTrackTable = (tracks) => {
140
+ const wrap = createElement('div', 'fv-midi-table-wrap');
141
+ const table = createElement('table', 'fv-midi-table');
142
+ const thead = document.createElement('thead');
143
+ const headerRow = document.createElement('tr');
144
+ for (const label of ['轨道', '乐器', '通道', '音符数', '时长']) {
145
+ headerRow.append(createElement('th', '', label));
146
+ }
147
+ thead.append(headerRow);
148
+ const tbody = document.createElement('tbody');
149
+ for (const track of tracks) {
150
+ const row = document.createElement('tr');
151
+ row.append(createElement('td', '', track.name), createElement('td', '', track.instrument), createElement('td', '', String(track.channel + 1)), createElement('td', '', String(track.notes)), createElement('td', '', formatDuration(track.duration)));
152
+ tbody.append(row);
153
+ }
154
+ table.append(thead, tbody);
155
+ wrap.append(table);
156
+ return wrap;
157
+ };
158
+ const renderSummary = (input) => {
159
+ title.textContent = input.name;
160
+ const totalNotes = input.tracks.reduce((sum, track) => sum + track.notes, 0);
161
+ const stats = createElement('div', 'fv-midi-stats');
162
+ for (const [label, value] of [
163
+ ['时长', formatDuration(input.duration)],
164
+ ['PPQ', String(input.ppq)],
165
+ ['轨道', String(input.tracks.length)],
166
+ ['音符', String(totalNotes)]
167
+ ]) {
168
+ const stat = document.createElement('div');
169
+ stat.append(createElement('span', '', label), createElement('strong', '', value));
170
+ stats.append(stat);
171
+ }
172
+ body.replaceWith(stats, renderTrackTable(input.tracks));
173
+ };
174
+ void (async () => {
175
+ try {
176
+ const { Midi } = await import('@tonejs/midi');
177
+ const midi = new Midi(buffer);
178
+ if (disposed) {
179
+ return;
180
+ }
181
+ renderSummary({
182
+ name: midi.name || 'MIDI 文件',
183
+ duration: midi.duration,
184
+ ppq: midi.header.ppq,
185
+ tracks: midi.tracks.map((track, index) => {
186
+ var _a, _b;
187
+ return ({
188
+ name: track.name || `Track ${index + 1}`,
189
+ instrument: ((_a = track.instrument) === null || _a === void 0 ? void 0 : _a.name) || ((_b = track.instrument) === null || _b === void 0 ? void 0 : _b.family) || 'Unknown',
190
+ channel: track.channel,
191
+ notes: track.notes.length,
192
+ duration: track.duration
193
+ });
194
+ })
195
+ });
196
+ }
197
+ catch (error) {
198
+ if (!disposed) {
199
+ renderError(error instanceof Error ? error.message : 'MIDI 解析失败');
200
+ }
201
+ }
202
+ })();
203
+ return createRenderedInstance(target, () => {
204
+ disposed = true;
205
+ });
206
+ };
207
+ /**
208
+ * Pure TypeScript audio renderer.
209
+ *
210
+ * Regular audio files use the browser's native `<audio>` element. MIDI stays in
211
+ * the same async chunk and lazily imports `@tonejs/midi` only for `.mid/.midi`.
212
+ */
213
+ export default async function renderAudio(buffer, target, type) {
214
+ const normalizedType = (type || 'mp3').toLowerCase();
215
+ if (normalizedType === 'midi' || normalizedType === 'mid') {
216
+ return renderMidiElement(buffer, target);
217
+ }
218
+ return renderAudioElement(buffer, target, normalizedType);
219
+ }
@@ -0,0 +1,6 @@
1
+ import { type FileRenderHandler, type FileViewerRenderedInstance, type FileViewerRendererPlugin, type RendererDefinition } from '@file-viewer/core';
2
+ export declare const mediaRendererDefinitions: RendererDefinition[];
3
+ export declare const renderFileViewerAudio: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
4
+ export declare const renderFileViewerVideo: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
5
+ export declare const mediaRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
6
+ export default mediaRenderer;
package/dist/index.js ADDED
@@ -0,0 +1,25 @@
1
+ import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
2
+ const mediaRendererIds = ['audio', 'video'];
3
+ const mediaDefinitions = DEFAULT_RENDERER_DEFINITIONS.filter(definition => mediaRendererIds.includes(definition.id));
4
+ if (mediaDefinitions.length !== mediaRendererIds.length) {
5
+ throw new Error('@file-viewer/renderer-media could not locate the shared audio/video format definitions.');
6
+ }
7
+ export const mediaRendererDefinitions = mediaDefinitions;
8
+ export const renderFileViewerAudio = (buffer, target, type) => import('./audio.js').then(({ default: renderAudio }) => renderAudio(buffer, target, type));
9
+ export const renderFileViewerVideo = (buffer, target, type, context) => import('./video.js').then(({ default: renderVideo }) => renderVideo(buffer, target, type, context));
10
+ export const mediaRenderer = {
11
+ id: 'file-viewer-renderer-media',
12
+ label: 'Flyfish File Viewer media renderer',
13
+ definitions: mediaRendererDefinitions,
14
+ handlers: [
15
+ {
16
+ rendererId: 'audio',
17
+ handler: renderFileViewerAudio,
18
+ },
19
+ {
20
+ rendererId: 'video',
21
+ handler: renderFileViewerVideo,
22
+ },
23
+ ],
24
+ };
25
+ export default mediaRenderer;
@@ -0,0 +1,8 @@
1
+ import type { FileRenderContext, FileViewerRenderedInstance } from '@file-viewer/core';
2
+ /**
3
+ * Pure TypeScript video renderer.
4
+ *
5
+ * MP4/WebM use the native `<video>` element. HLS uses native browser support
6
+ * first and imports `hls.js` only when the current browser needs it.
7
+ */
8
+ export default function renderVideo(buffer: ArrayBuffer, target: HTMLDivElement, type?: string, context?: FileRenderContext): Promise<FileViewerRenderedInstance>;
package/dist/video.js ADDED
@@ -0,0 +1,108 @@
1
+ const videoStyle = `
2
+ .fv-video-viewer{width:100%;min-height:100%;display:flex;align-items:center;justify-content:center;padding:28px;background:#eef1f4;box-sizing:border-box}
3
+ .fv-video-shell{width:min(100%,960px);border-radius:8px;border:1px solid rgba(15,23,42,.1);background:#fff;box-shadow:0 18px 48px rgba(15,23,42,.14);overflow:hidden}
4
+ .fv-video-heading{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:14px 18px;border-bottom:1px solid rgba(15,23,42,.08)}
5
+ .fv-video-heading span{color:#0f766e;font-size:12px;font-weight:800}
6
+ .fv-video-heading strong{color:#132235;font-size:16px}
7
+ .fv-video-player{display:block;width:100%;aspect-ratio:16/9;background:#05070a}
8
+ .fv-video-hint{margin:0;padding:12px 18px 16px;color:#64748b;font-size:13px;line-height:1.7}
9
+ `;
10
+ const VIDEO_MIME_MAP = {
11
+ m3u8: 'application/vnd.apple.mpegurl',
12
+ mp4: 'video/mp4',
13
+ webm: 'video/webm'
14
+ };
15
+ const createElement = (tagName, className, text) => {
16
+ const element = document.createElement(tagName);
17
+ if (className) {
18
+ element.className = className;
19
+ }
20
+ if (typeof text === 'string') {
21
+ element.textContent = text;
22
+ }
23
+ return element;
24
+ };
25
+ const createStyle = () => {
26
+ const style = document.createElement('style');
27
+ style.textContent = videoStyle;
28
+ return style;
29
+ };
30
+ const createRenderedInstance = (target, cleanup) => ({
31
+ $el: target,
32
+ unmount() {
33
+ cleanup();
34
+ target.replaceChildren();
35
+ }
36
+ });
37
+ const getMimeType = (type) => {
38
+ return VIDEO_MIME_MAP[type] || 'video/*';
39
+ };
40
+ const createLocalUrl = (buffer, type) => {
41
+ return URL.createObjectURL(new Blob([buffer], { type: getMimeType(type) }));
42
+ };
43
+ /**
44
+ * Pure TypeScript video renderer.
45
+ *
46
+ * MP4/WebM use the native `<video>` element. HLS uses native browser support
47
+ * first and imports `hls.js` only when the current browser needs it.
48
+ */
49
+ export default async function renderVideo(buffer, target, type, context) {
50
+ const normalizedType = (type || 'mp4').toLowerCase();
51
+ let disposed = false;
52
+ let objectUrl = '';
53
+ let hls = null;
54
+ const root = createElement('div', 'fv-video-viewer');
55
+ const shell = createElement('section', 'fv-video-shell');
56
+ const heading = createElement('div', 'fv-video-heading');
57
+ heading.append(createElement('span', '', normalizedType.toUpperCase() || 'VIDEO'), createElement('strong', '', '视频预览'));
58
+ const video = createElement('video', 'fv-video-player');
59
+ video.controls = true;
60
+ video.preload = 'metadata';
61
+ video.textContent = '当前浏览器不支持该视频格式。';
62
+ shell.append(heading, video);
63
+ if (normalizedType === 'm3u8') {
64
+ shell.append(createElement('p', 'fv-video-hint', 'HLS 会优先使用原始 URL 加载分片;如果传入的是本地单文件清单,请确保分片地址可被浏览器访问。'));
65
+ }
66
+ root.append(shell);
67
+ target.replaceChildren(createStyle(), root);
68
+ const resolveSource = () => {
69
+ if (normalizedType === 'm3u8' && (context === null || context === void 0 ? void 0 : context.url)) {
70
+ return context.url;
71
+ }
72
+ objectUrl = createLocalUrl(buffer, normalizedType);
73
+ return objectUrl;
74
+ };
75
+ const mountVideo = async () => {
76
+ const source = resolveSource();
77
+ if (normalizedType === 'm3u8') {
78
+ if (video.canPlayType('application/vnd.apple.mpegurl')) {
79
+ video.src = source;
80
+ return;
81
+ }
82
+ const { default: HlsConstructor } = await import('hls.js');
83
+ if (disposed) {
84
+ return;
85
+ }
86
+ if (HlsConstructor.isSupported()) {
87
+ hls = new HlsConstructor({ enableWorker: true, lowLatencyMode: false });
88
+ hls.loadSource(source);
89
+ hls.attachMedia(video);
90
+ return;
91
+ }
92
+ }
93
+ video.src = source;
94
+ };
95
+ void mountVideo();
96
+ return createRenderedInstance(target, () => {
97
+ disposed = true;
98
+ hls === null || hls === void 0 ? void 0 : hls.destroy();
99
+ hls = null;
100
+ video.pause();
101
+ video.removeAttribute('src');
102
+ video.load();
103
+ if (objectUrl) {
104
+ URL.revokeObjectURL(objectUrl);
105
+ objectUrl = '';
106
+ }
107
+ });
108
+ }
package/package.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "@file-viewer/renderer-media",
3
+ "version": "2.0.11",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Standalone audio and video renderer plugin for Flyfish File Viewer with native media playback, HLS fallback, MIDI parsing, and offline-friendly lazy loading.",
7
+ "keywords": [
8
+ "file-viewer",
9
+ "renderer",
10
+ "audio",
11
+ "video",
12
+ "hls",
13
+ "midi",
14
+ "document-preview",
15
+ "document-viewer",
16
+ "file-preview",
17
+ "self-hosted"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public",
21
+ "registry": "https://registry.npmjs.org/"
22
+ },
23
+ "author": {
24
+ "name": "Wangyu",
25
+ "email": "wybaby168@gmail.com"
26
+ },
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/flyfish-dev/file-viewer-renderer-media.git",
30
+ "directory": "packages/renderers/media"
31
+ },
32
+ "homepage": "https://doc.file-viewer.app/guide/on-demand-renderers",
33
+ "bugs": {
34
+ "url": "https://github.com/flyfish-dev/file-viewer-renderer-media/issues"
35
+ },
36
+ "funding": {
37
+ "type": "individual",
38
+ "url": "https://dev.flyfish.group/shop"
39
+ },
40
+ "main": "./dist/index.js",
41
+ "module": "./dist/index.js",
42
+ "types": "./dist/index.d.ts",
43
+ "exports": {
44
+ ".": {
45
+ "types": "./dist/index.d.ts",
46
+ "import": "./dist/index.js",
47
+ "default": "./dist/index.js"
48
+ },
49
+ "./package.json": "./package.json"
50
+ },
51
+ "files": [
52
+ "dist",
53
+ "README.md",
54
+ "README.en.md",
55
+ "LICENSE"
56
+ ],
57
+ "dependencies": {
58
+ "@file-viewer/core": "^2.0.11",
59
+ "@tonejs/midi": "^2.0.28",
60
+ "hls.js": "^1.6.16"
61
+ },
62
+ "devDependencies": {
63
+ "typescript": "^6.0.3"
64
+ },
65
+ "license": "Apache-2.0",
66
+ "scripts": {
67
+ "build": "tsc -b tsconfig.json",
68
+ "type-check": "tsc -b tsconfig.json"
69
+ }
70
+ }