@xinmark/media-core 0.0.0-stage → 0.1.0

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Xin Mark
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,598 @@
1
- # Temporary Holding Version
2
1
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
2
+ # @xinmark/media-core
3
+
4
+ **A lightweight TypeScript core library for browser-based media processing.**
5
+
6
+ `@xinmark/media-core` 是 AI Media Studio 的底层媒体基础库,提供媒体类型识别、音视频元数据读取,以及可靠的异步任务管理能力。
7
+
8
+ 它旨在为浏览器端音视频处理应用提供统一的基础能力,包括任务生命周期管理、并发控制、取消、超时和资源清理。
9
+
10
+ ## Features
11
+
12
+ - **Media Detection**:识别视频、音频、图片及未知文件类型。
13
+ - **Media Metadata**:读取音视频文件的基本元数据。
14
+ - **Task Management**:统一管理异步媒体处理任务。
15
+ - **Concurrency Control**:限制任务最大并发执行数量。
16
+ - **Task Cancellation**:通过 AbortSignal 通知执行器取消任务。
17
+ - **Timeout Control**:支持管理器默认超时和单任务超时。
18
+ - **Resource Cleanup**:支持注册清理函数,并按照注册顺序的逆序执行。
19
+ - **Progress Tracking**:跟踪任务执行进度。
20
+ - **Task Subscription**:监听任务状态变化。
21
+ - **TypeScript Support**:提供完整的 TypeScript 类型声明。
22
+
23
+ ## Installation
24
+
25
+ 使用 npm:
26
+
27
+ ```bash
28
+ npm install @xinmark/media-core
29
+ ```
30
+
31
+ 使用 pnpm:
32
+
33
+ ```bash
34
+ pnpm add @xinmark/media-core
35
+ ```
36
+
37
+ 使用 yarn:
38
+
39
+ ```bash
40
+ yarn add @xinmark/media-core
41
+ ```
42
+
43
+ ## Quick Start
44
+
45
+ ```ts
46
+ import {
47
+ getMediaKind,
48
+ getMediaFileInfo,
49
+ readMediaMetadata,
50
+ MediaTaskManager,
51
+ } from '@xinmark/media-core';
52
+
53
+ // 创建媒体任务管理器
54
+ const manager = new MediaTaskManager({
55
+ maxConcurrent: 2,
56
+ defaultTimeout: 30000,
57
+ });
58
+
59
+ // 监听任务变化
60
+ const unsubscribe = manager.subscribe((tasks) => {
61
+ console.log('任务列表:', tasks);
62
+ });
63
+
64
+ // 获取文件输入
65
+ const input = document.querySelector<HTMLInputElement>('#file');
66
+
67
+ input?.addEventListener('change', async () => {
68
+ const file = input.files?.[0];
69
+
70
+ if (!file) return;
71
+
72
+ // 识别媒体类型
73
+ console.log(getMediaKind(file));
74
+
75
+ // 获取文件基本信息
76
+ console.log(getMediaFileInfo(file));
77
+
78
+ // 读取媒体元数据
79
+ const metadata = await readMediaMetadata(file);
80
+
81
+ console.log(metadata);
82
+
83
+ // 创建任务
84
+ const task = manager.create({
85
+ type: 'video-processing',
86
+ });
87
+
88
+ // 执行任务
89
+ const result = await manager.run(task.id, async ({
90
+ signal,
91
+ onProgress,
92
+ onCleanup,
93
+ }) => {
94
+ onProgress(30);
95
+
96
+ // 在这里执行实际媒体处理
97
+ onCleanup(() => {
98
+ console.log('释放任务资源');
99
+ });
100
+
101
+ if (signal.aborted) {
102
+ throw new Error('任务已取消');
103
+ }
104
+
105
+ onProgress(100);
106
+
107
+ return '处理完成';
108
+ });
109
+
110
+ console.log(result);
111
+ });
112
+
113
+ // 不再需要监听时取消订阅
114
+ // unsubscribe();
115
+ ```
116
+
117
+ ## Media APIs
118
+
119
+ ### 1. getMediaKind(file)
120
+
121
+ 根据文件 MIME 类型识别媒体类别。
122
+
123
+ ```ts
124
+ import { getMediaKind } from '@xinmark/media-core';
125
+
126
+ const kind = getMediaKind(file);
127
+ ```
128
+
129
+ 返回类型:
130
+
131
+ ```ts
132
+ type MediaKind = 'video' | 'audio' | 'image' | 'unknown';
133
+ ```
134
+
135
+ | MIME 类型 | 返回值 |
136
+ | --------------- | ------- |
137
+ | video/mp4 | video |
138
+ | audio/mpeg | audio |
139
+ | image/png | image |
140
+ | application/pdf | unknown |
141
+
142
+ 注意:该方法根据 MIME 类型判断,不会读取文件实际内容,也不负责验证文件真实性。
143
+
144
+ ### 2. getMediaFileInfo(file)
145
+
146
+ 获取媒体文件的基本信息。
147
+
148
+ ```ts
149
+ import { getMediaFileInfo } from '@xinmark/media-core';
150
+
151
+ const info = getMediaFileInfo(file);
152
+
153
+ console.log(info);
154
+ ```
155
+
156
+ 返回类型:
157
+
158
+ ```ts
159
+ interface MediaFileInfo {
160
+ name: string;
161
+ size: number;
162
+ type: string;
163
+ kind: MediaKind;
164
+ }
165
+ ```
166
+
167
+ ### 3. readMediaMetadata(file, options?)
168
+
169
+ 读取视频或音频文件的基础元数据。
170
+
171
+ ```ts
172
+ import { readMediaMetadata } from '@xinmark/media-core';
173
+
174
+ const metadata = await readMediaMetadata(file, {
175
+ timeout: 15000,
176
+ });
177
+
178
+ console.log(metadata);
179
+ ```
180
+
181
+ 参数:
182
+
183
+ | 参数 | 类型 | 默认值 | 说明 |
184
+ | --------------- | ------ | ------ | ---------------------- |
185
+ | file | File | 必填 | 浏览器 File 对象 |
186
+ | options.timeout | number | 15000 | 读取超时时间,单位毫秒 |
187
+
188
+ 返回类型:
189
+
190
+ ```ts
191
+ interface MediaMetadata {
192
+ name: string;
193
+ size: number;
194
+ mimeType: string;
195
+ kind: 'video' | 'audio';
196
+ duration: number;
197
+ width?: number;
198
+ height?: number;
199
+ }
200
+ ```
201
+
202
+ 视频文件返回宽度和高度,音频文件不返回这两个字段。
203
+
204
+ 异常情况:
205
+
206
+ - 不支持的文件类型:抛出错误。
207
+ - 媒体文件解析失败:抛出错误。
208
+ - 读取超时:抛出错误。
209
+
210
+ 注意:该 API 使用浏览器的 HTMLMediaElement 和 URL.createObjectURL,因此需要在浏览器环境中调用。
211
+
212
+ ## Task Manager
213
+
214
+ `MediaTaskManager` 负责管理异步任务的创建、执行、取消、超时、进度和资源清理。
215
+
216
+ ### 1. 创建管理器
217
+
218
+ ```ts
219
+ import { MediaTaskManager } from '@xinmark/media-core';
220
+
221
+ const manager = new MediaTaskManager({
222
+ maxConcurrent: 2,
223
+ defaultTimeout: 30000,
224
+ });
225
+ ```
226
+
227
+ 配置:
228
+
229
+ | 参数 | 类型 | 默认值 | 说明 |
230
+ | -------------- | ------ | ------ | -------------------------- |
231
+ | maxConcurrent | number | 2 | 最大并发执行数量 |
232
+ | defaultTimeout | number | 不限制 | 默认任务超时时间,单位毫秒 |
233
+
234
+ `maxConcurrent` 必须是大于 0 的整数。
235
+
236
+ `defaultTimeout` 必须是大于 0 且不超过 2147483647 的有限数字。
237
+
238
+ ### 2. 创建任务
239
+
240
+ ```ts
241
+ const task = manager.create({
242
+ type: 'video-processing',
243
+ timeout: 10000,
244
+ });
245
+
246
+ console.log(task.id);
247
+ console.log(task.status);
248
+ ```
249
+
250
+ 参数:
251
+
252
+ ```ts
253
+ interface CreateTaskOptions {
254
+ type: string;
255
+ timeout?: number;
256
+ }
257
+ ```
258
+
259
+ 初始任务状态:
260
+
261
+ ```ts
262
+ type MediaTaskStatus =
263
+ | 'pending'
264
+ | 'processing'
265
+ | 'completed'
266
+ | 'failed'
267
+ | 'cancelled';
268
+ ```
269
+
270
+ 任务信息:
271
+
272
+ ```ts
273
+ interface MediaTask {
274
+ id: string;
275
+ type: string;
276
+ status: MediaTaskStatus;
277
+ progress: number;
278
+ error?: string;
279
+ createdAt: number;
280
+ updatedAt: number;
281
+ }
282
+ ```
283
+
284
+ 任务创建成功后,初始状态为 `pending`,进度为 `0`。
285
+
286
+ 单任务的 `timeout` 优先于管理器的 `defaultTimeout`。
287
+
288
+ ### 3. 执行任务
289
+
290
+ ```ts
291
+ const result = await manager.run(task.id, async ({
292
+ signal,
293
+ onProgress,
294
+ onCleanup,
295
+ }) => {
296
+ onProgress(20);
297
+
298
+ // 执行处理逻辑
299
+ onProgress(60);
300
+
301
+ // 注册资源清理函数
302
+ onCleanup(() => {
303
+ console.log('清理资源');
304
+ });
305
+
306
+ if (signal.aborted) {
307
+ throw new Error('任务已取消');
308
+ }
309
+
310
+ onProgress(100);
311
+
312
+ return {
313
+ success: true,
314
+ };
315
+ });
316
+ ```
317
+
318
+ `run()` 接收:
319
+
320
+ - `id`:任务 ID。
321
+ - `executor`:异步任务执行函数。
322
+
323
+ 返回:
324
+
325
+ ```ts
326
+ Promise<T>
327
+ ```
328
+
329
+ 任务执行器必须返回 Promise。
330
+
331
+ ### 4. 更新任务进度
332
+
333
+ ```ts
334
+ onProgress(50);
335
+ ```
336
+
337
+ 进度范围为 `0–100`。
338
+
339
+ 只有处于 `processing` 状态的任务才能更新进度。
340
+
341
+ 任务成功完成后,进度自动更新为 `100`。
342
+
343
+ 任务被取消后,执行器继续报告的进度不会再更新任务状态。
344
+
345
+ ### 5. 任务取消
346
+
347
+ ```ts
348
+ manager.cancel(task.id);
349
+ ```
350
+
351
+ 取消任务后:
352
+
353
+ - 任务状态变为 `cancelled`。
354
+ - 触发对应的 AbortSignal。
355
+ - `run()` 返回的 Promise 会以 `AbortError` 拒绝。
356
+ - 等待队列中的任务会被移除。
357
+ - 正在运行的执行器如果没有响应取消信号,会继续运行。
358
+ - 执行器真正结束后才执行资源清理并释放并发名额。
359
+
360
+ 因此,业务代码应主动监听 `signal`,并在适当时机停止工作。
361
+
362
+ ```ts
363
+ const result = await manager.run(task.id, async ({
364
+ signal,
365
+ onProgress,
366
+ }) => {
367
+ if (signal.aborted) {
368
+ throw new Error('任务已取消');
369
+ }
370
+
371
+ onProgress(30);
372
+
373
+ // 执行可中断的异步操作
374
+ await someAsyncOperation();
375
+
376
+ if (signal.aborted) {
377
+ throw new Error('任务已取消');
378
+ }
379
+
380
+ onProgress(100);
381
+
382
+ return 'success';
383
+ });
384
+ ```
385
+
386
+ 注意:示例中的 `someAsyncOperation()` 代表业务自己的异步操作,并非本库提供的 API。
387
+
388
+ ### 6. 任务超时
389
+
390
+ 可以在管理器级别设置默认超时:
391
+
392
+ ```ts
393
+ const manager = new MediaTaskManager({
394
+ defaultTimeout: 30000,
395
+ });
396
+ ```
397
+
398
+ 也可以为单个任务设置超时:
399
+
400
+ ```ts
401
+ const task = manager.create({
402
+ type: 'video-export',
403
+ timeout: 10000,
404
+ });
405
+ ```
406
+
407
+ 超时规则:
408
+
409
+ - 超时时间从执行器真正开始运行时计算。
410
+ - 等待队列的时间不计入超时。
411
+ - 资源清理时间不计入超时。
412
+ - 超时后任务状态变为 `failed`。
413
+ - 执行器收到 AbortSignal。
414
+ - 调用方收到名称为 `TimeoutError` 的错误。
415
+ - 执行器真正结束后才释放并发名额。
416
+
417
+ 主动取消和超时的状态不同:
418
+
419
+ | 场景 | 任务状态 | 错误名称 |
420
+ | -------- | --------- | ---------------------- |
421
+ | 主动取消 | cancelled | AbortError |
422
+ | 执行超时 | failed | TimeoutError |
423
+ | 执行异常 | failed | 原始错误或清理聚合错误 |
424
+
425
+ ### 7. 资源清理
426
+
427
+ 通过 `onCleanup()` 注册资源清理函数:
428
+
429
+ ```ts
430
+ const task = manager.create({
431
+ type: 'video-processing',
432
+ });
433
+
434
+ await manager.run(task.id, async ({ onCleanup }) => {
435
+ const url = URL.createObjectURL(file);
436
+
437
+ onCleanup(() => {
438
+ URL.revokeObjectURL(url);
439
+ });
440
+
441
+ return 'done';
442
+ });
443
+ ```
444
+
445
+ 资源清理规则:
446
+
447
+ - 任务成功、失败或取消后都会尝试执行清理。
448
+ - 清理函数按照注册顺序的逆序执行。
449
+ - 清理函数只执行一次。
450
+ - 一个清理函数失败,不会阻止其他清理函数执行。
451
+ - 多个清理错误会通过 `AggregateError` 聚合。
452
+
453
+ ### 8. 查询任务
454
+
455
+ 查询单个任务:
456
+
457
+ ```ts
458
+ const task = manager.get(taskId);
459
+ ```
460
+
461
+ 查询所有任务:
462
+
463
+ ```ts
464
+ const tasks = manager.getAll();
465
+ ```
466
+
467
+ 两个方法都返回任务数据副本,外部修改不会直接影响管理器内部状态。
468
+
469
+ ### 9. 获取取消信号
470
+
471
+ ```ts
472
+ const signal = manager.getSignal(taskId);
473
+ ```
474
+
475
+ 返回类型:
476
+
477
+ ```ts
478
+ AbortSignal | undefined
479
+ ```
480
+
481
+ 任务进入终态后,其控制器会被清理,因此可能返回 `undefined`。
482
+
483
+ ### 10. 订阅任务变化
484
+
485
+ ```ts
486
+ const unsubscribe = manager.subscribe((tasks) => {
487
+ console.log('任务发生变化:', tasks);
488
+ });
489
+ ```
490
+
491
+ 订阅后会立即收到一次当前任务列表,后续任务发生变化时继续通知。
492
+
493
+ 每个监听器收到独立的数据快照。
494
+
495
+ 监听器发生异常时,不会阻止其他监听器执行。
496
+
497
+ 取消订阅:
498
+
499
+ ```ts
500
+ unsubscribe();
501
+ ```
502
+
503
+ ## Task Lifecycle
504
+
505
+ ```text
506
+ pending
507
+ |
508
+ v
509
+ processing
510
+ |
511
+ +-------> completed
512
+ |
513
+ +-------> failed
514
+ |
515
+ +-------> cancelled
516
+ ```
517
+
518
+ 终态包括:
519
+
520
+ - completed
521
+ - failed
522
+ - cancelled
523
+
524
+ 终态任务不能再次执行,也不能继续更新。
525
+
526
+ ## Browser Requirements
527
+
528
+ 当前版本依赖浏览器环境中的部分 Web API:
529
+
530
+ - File
531
+ - AbortController / AbortSignal
532
+ - crypto.randomUUID()
533
+ - HTMLMediaElement
534
+ - URL.createObjectURL()
535
+ - URL.revokeObjectURL()
536
+ - document.createElement()
537
+
538
+ 其中,媒体元数据读取功能需要 DOM 环境。
539
+
540
+ 本库当前面向浏览器端媒体处理场景,不承诺所有 API 均可在纯 Node.js 环境中直接使用。
541
+
542
+ ## Development
543
+
544
+ 克隆项目:
545
+
546
+ ```bash
547
+ git clone https://github.com/strongbreezeboy/ai-media-studio.git
548
+ cd ai-media-studio
549
+ ```
550
+
551
+ 安装依赖:
552
+
553
+ ```bash
554
+ pnpm install
555
+ ```
556
+
557
+ 运行测试:
558
+
559
+ ```bash
560
+ pnpm --filter @xinmark/media-core test
561
+ ```
562
+
563
+ 构建:
564
+
565
+ ```bash
566
+ pnpm --filter @xinmark/media-core build
567
+ ```
568
+
569
+ ## Project Status
570
+
571
+ 当前版本:`0.1.0`
572
+
573
+ 目前已实现:
574
+
575
+ - 媒体类型识别
576
+ - 媒体基本信息读取
577
+ - 音视频元数据读取
578
+ - 任务生命周期管理
579
+ - 并发队列
580
+ - 任务取消
581
+ - 任务超时
582
+ - 进度跟踪
583
+ - 资源清理
584
+ - 任务订阅
585
+
586
+ 后续规划:
587
+
588
+ - 更完善的媒体处理抽象
589
+ - Worker 任务调度
590
+ - 媒体解码和编码能力
591
+ - 音视频处理流水线
592
+ - 更丰富的媒体工具接口
593
+
594
+ 以上规划不代表当前版本已经实现。
595
+
596
+ ## License
597
+
598
+ MIT