@hackbuild/media 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 Moheeb Zara
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,48 @@
1
- # Temporary Holding Version
1
+ # @hackbuild/media
2
2
 
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.
3
+ Media in a tab, from earlier builds: decode a file's audio to a target
4
+ rate, pick keyframes by scene change, and record a canvas or stream. Code
5
+ MIT; this README CC-BY-4.0 with the code samples also MIT. No models.
6
+
7
+ # not on npm yet: the @hackbuild scope is unpublished; build from this repository
8
+ npm install @hackbuild/media
9
+
10
+ import { decodeAudio, lumaHistogram, pickKeyframes, record } from "@hackbuild/media";
11
+ const { channels } = await decodeAudio(file, 16000); // for transcribe; 44100 for stems
12
+ const keys = pickKeyframes(frames.map((f) => ({ t: f.t, hist: lumaHistogram(f.rgba) })), { threshold: 0.3, maxGap: 10, max: 12 });
13
+ const rec = record(canvas.captureStream(30)); // first supported webm or mp4 type
14
+ const blob = await rec.stop();
15
+
16
+ - `decodeAudio` uses the browser's decoder through an OfflineAudioContext
17
+ and resamples by rendering; it names the failure when the container is
18
+ refused (mkv and avi usually are). Pages cannot fetch YouTube audio
19
+ (CORS); that needs an extension or a proxy.
20
+ - `pickKeyframes` keeps the first frame, each frame whose 32 bin luma
21
+ histogram moved more than the threshold from the last keyframe, one per
22
+ `maxGap` seconds, and the biggest changes under a cap.
23
+ - `record` tries vp9, vp8, plain webm, then mp4 with `MediaRecorder`.
24
+
25
+ ## What is verified, and what is not
26
+
27
+ ### Verified on this machine
28
+
29
+ - 2026-11-22: `npx vitest run packages/media` passes 3 tests under Node
30
+ 22.18.0 with fake browser objects: decode and resample flow and the
31
+ refused container message, histogram distance and keyframe picking
32
+ with gap and cap, MIME picking and chunk collection.
33
+
34
+ ### Not verified by anything
35
+
36
+ - Real decoding of mp4, mov, webm and mkv files in Chrome, Safari and
37
+ Firefox; real recording; ffmpeg.wasm or WebCodecs paths (not built).
38
+
39
+ ## Size budget
40
+
41
+ | file | gzip (measured) | ceiling |
42
+ |---|---|---|
43
+ | `dist/index.js` (main entry, imports external) | 2,033 bytes | 2,134 bytes |
44
+ | `dist/single/index.iife.js` (single file build) | 2,015 bytes | 2,115 bytes |
45
+
46
+ Measured 2026-11-24 by `node tools/lint-packages.mjs` (gzip level 9) from the packed
47
+ tarball. Generated from `tools/size-budget.json`; CI fails when a file moves more than
48
+ 5 percent from its row.
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Media helpers (as earlier builds did): decode a file's audio track at a target
3
+ * rate through an OfflineAudioContext, pick keyframes by scene change from
4
+ * small luminance histograms, and record a canvas or stream with the first
5
+ * MIME type the browser supports. Browser objects are injected so tests
6
+ * and workers can pass their own.
7
+ */
8
+ export interface DecodedAudio {
9
+ sampleRate: number;
10
+ channels: Float32Array[];
11
+ duration: number;
12
+ }
13
+ interface AudioBufferLike {
14
+ sampleRate: number;
15
+ duration: number;
16
+ numberOfChannels: number;
17
+ length: number;
18
+ getChannelData(c: number): Float32Array;
19
+ }
20
+ export interface OfflineCtxLike {
21
+ decodeAudioData(b: ArrayBuffer): Promise<AudioBufferLike>;
22
+ createBufferSource(): {
23
+ buffer: AudioBufferLike | null;
24
+ connect(d: unknown): void;
25
+ start(): void;
26
+ };
27
+ destination: unknown;
28
+ startRendering(): Promise<AudioBufferLike>;
29
+ }
30
+ export type OfflineCtor = new (channels: number, length: number, sampleRate: number) => OfflineCtxLike;
31
+ /** Decode and resample with the browser's decoder (as earlier builds did). Names the failure when the browser refuses the container. */
32
+ export declare function decodeAudio(data: ArrayBuffer | Blob, sampleRate?: number, Ctx?: OfflineCtor): Promise<DecodedAudio>;
33
+ /** A 32 bin luminance histogram of RGBA pixels, normalized to sum 1. */
34
+ export declare function lumaHistogram(rgba: ArrayLike<number>, bins?: number): Float32Array;
35
+ /** Half the L1 distance of two normalized histograms: 0 same, 1 disjoint. */
36
+ export declare function histDistance(a: Float32Array, b: Float32Array): number;
37
+ /**
38
+ * Keyframes from sampled frames: the first frame, every frame whose
39
+ * histogram moved more than `threshold` from the last keyframe, and at
40
+ * least one every `maxGap` seconds; at most `max` frames, the biggest
41
+ * changes kept.
42
+ */
43
+ export declare function pickKeyframes(frames: readonly {
44
+ t: number;
45
+ hist: Float32Array;
46
+ }[], o?: {
47
+ threshold?: number;
48
+ maxGap?: number;
49
+ max?: number;
50
+ }): number[];
51
+ /** Sample times for a video of `duration` seconds every `step` seconds, inside the clip. */
52
+ export declare function sampleTimes(duration: number, step?: number): number[];
53
+ export declare const RECORDER_TYPES: string[];
54
+ /** The first type the recorder supports, or "" for the browser default. */
55
+ export declare function pickMime(isSupported?: (t: string) => boolean, types?: string[]): string;
56
+ interface RecorderLike {
57
+ start(timeslice?: number): void;
58
+ stop(): void;
59
+ ondataavailable: ((e: {
60
+ data: Blob;
61
+ }) => void) | null;
62
+ onstop: (() => void) | null;
63
+ readonly mimeType?: string;
64
+ }
65
+ /** Record a MediaStream (canvas.captureStream() plus audio tracks) until `stop()`; resolves the Blob. */
66
+ export declare function record(stream: unknown, o?: {
67
+ mimeType?: string;
68
+ bitsPerSecond?: number;
69
+ Recorder?: new (s: unknown, opts: Record<string, unknown>) => RecorderLike;
70
+ timeslice?: number;
71
+ }): {
72
+ stop(): Promise<Blob>;
73
+ mimeType: string;
74
+ };
75
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Media helpers (as earlier builds did): decode a file's audio track at a target
3
+ * rate through an OfflineAudioContext, pick keyframes by scene change from
4
+ * small luminance histograms, and record a canvas or stream with the first
5
+ * MIME type the browser supports. Browser objects are injected so tests
6
+ * and workers can pass their own.
7
+ */
8
+ /** Decode and resample with the browser's decoder (as earlier builds did). Names the failure when the browser refuses the container. */
9
+ export async function decodeAudio(data, sampleRate = 16000, Ctx) {
10
+ const C = Ctx ?? globalThis.OfflineAudioContext;
11
+ if (!C)
12
+ throw new Error("no OfflineAudioContext here. decode on the page, not in a worker.");
13
+ // decodeAudioData detaches the buffer it is given, so the caller's stays usable
14
+ const ab = data instanceof ArrayBuffer ? data.slice(0) : await data.arrayBuffer();
15
+ let buf;
16
+ try {
17
+ buf = await new C(1, 1, sampleRate).decodeAudioData(ab);
18
+ }
19
+ catch (e) {
20
+ throw new Error(`this browser will not decode the audio track (${e instanceof Error ? e.message : String(e)}). if it plays in a video tag it should decode; mkv and avi usually will not.`);
21
+ }
22
+ if (buf.sampleRate !== sampleRate) {
23
+ const n = Math.max(1, Math.ceil(buf.duration * sampleRate));
24
+ const oc = new C(buf.numberOfChannels, n, sampleRate);
25
+ const s = oc.createBufferSource();
26
+ s.buffer = buf;
27
+ s.connect(oc.destination);
28
+ s.start();
29
+ buf = await oc.startRendering();
30
+ }
31
+ return { sampleRate: buf.sampleRate, duration: buf.duration, channels: Array.from({ length: buf.numberOfChannels }, (_, c) => buf.getChannelData(c).slice()) };
32
+ }
33
+ /** A 32 bin luminance histogram of RGBA pixels, normalized to sum 1. */
34
+ export function lumaHistogram(rgba, bins = 32) {
35
+ const h = new Float32Array(bins);
36
+ const n = Math.floor(rgba.length / 4);
37
+ for (let i = 0; i < n; i++) {
38
+ const y = 0.299 * rgba[i * 4] + 0.587 * rgba[i * 4 + 1] + 0.114 * rgba[i * 4 + 2];
39
+ h[Math.min(bins - 1, Math.floor((y / 256) * bins))] += 1;
40
+ }
41
+ for (let i = 0; i < bins; i++)
42
+ h[i] /= Math.max(1, n);
43
+ return h;
44
+ }
45
+ /** Half the L1 distance of two normalized histograms: 0 same, 1 disjoint. */
46
+ export function histDistance(a, b) {
47
+ let s = 0;
48
+ for (let i = 0; i < a.length; i++)
49
+ s += Math.abs(a[i] - b[i]);
50
+ return s / 2;
51
+ }
52
+ /**
53
+ * Keyframes from sampled frames: the first frame, every frame whose
54
+ * histogram moved more than `threshold` from the last keyframe, and at
55
+ * least one every `maxGap` seconds; at most `max` frames, the biggest
56
+ * changes kept.
57
+ */
58
+ export function pickKeyframes(frames, o = {}) {
59
+ const thr = o.threshold ?? 0.3;
60
+ const gap = o.maxGap ?? Infinity;
61
+ const keep = [];
62
+ let last = null;
63
+ frames.forEach((f, i) => {
64
+ if (!last) {
65
+ keep.push({ i, score: Infinity });
66
+ last = f;
67
+ return;
68
+ }
69
+ const d = histDistance(last.hist, f.hist);
70
+ if (d > thr || f.t - last.t >= gap) {
71
+ keep.push({ i, score: d });
72
+ last = f;
73
+ }
74
+ });
75
+ const max = o.max ?? Infinity;
76
+ return keep.length <= max
77
+ ? keep.map((k) => k.i)
78
+ : keep
79
+ .sort((a, b) => b.score - a.score)
80
+ .slice(0, max)
81
+ .map((k) => k.i)
82
+ .sort((a, b) => a - b);
83
+ }
84
+ /** Sample times for a video of `duration` seconds every `step` seconds, inside the clip. */
85
+ export function sampleTimes(duration, step = 1) {
86
+ const out = [];
87
+ for (let t = Math.min(0.05, duration / 2); t < duration; t += step)
88
+ out.push(+t.toFixed(3));
89
+ return out;
90
+ }
91
+ export const RECORDER_TYPES = ["video/webm;codecs=vp9,opus", "video/webm;codecs=vp8,opus", "video/webm", "video/mp4;codecs=avc1,mp4a", "video/mp4"];
92
+ /** The first type the recorder supports, or "" for the browser default. */
93
+ export function pickMime(isSupported = (t) => globalThis.MediaRecorder?.isTypeSupported(t) ?? false, types = RECORDER_TYPES) {
94
+ return types.find((t) => isSupported(t)) ?? "";
95
+ }
96
+ /** Record a MediaStream (canvas.captureStream() plus audio tracks) until `stop()`; resolves the Blob. */
97
+ export function record(stream, o = {}) {
98
+ const R = o.Recorder ?? globalThis.MediaRecorder;
99
+ if (!R)
100
+ throw new Error("no MediaRecorder in this browser. recording is off.");
101
+ const mimeType = o.mimeType ?? pickMime();
102
+ const rec = new R(stream, { ...(mimeType ? { mimeType } : {}), ...(o.bitsPerSecond ? { videoBitsPerSecond: o.bitsPerSecond } : {}) });
103
+ const parts = [];
104
+ rec.ondataavailable = (e) => {
105
+ if (e.data.size)
106
+ parts.push(e.data);
107
+ };
108
+ const done = new Promise((r) => (rec.onstop = () => r(new Blob(parts, { type: mimeType || rec.mimeType || "video/webm" }))));
109
+ rec.start(o.timeslice ?? 1000);
110
+ return {
111
+ mimeType,
112
+ stop: () => {
113
+ rec.stop();
114
+ return done;
115
+ },
116
+ };
117
+ }
@@ -0,0 +1,128 @@
1
+ var HackbuildMedia = (function(exports) {
2
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
3
+ // packages/media/src/index.ts
4
+ /** Decode and resample with the browser's decoder (as earlier builds did). Names the failure when the browser refuses the container. */
5
+ async function decodeAudio(data, sampleRate = 16e3, Ctx) {
6
+ const C = Ctx ?? globalThis.OfflineAudioContext;
7
+ if (!C) throw new Error("no OfflineAudioContext here. decode on the page, not in a worker.");
8
+ const ab = data instanceof ArrayBuffer ? data.slice(0) : await data.arrayBuffer();
9
+ let buf;
10
+ try {
11
+ buf = await new C(1, 1, sampleRate).decodeAudioData(ab);
12
+ } catch (e) {
13
+ throw new Error(`this browser will not decode the audio track (${e instanceof Error ? e.message : String(e)}). if it plays in a video tag it should decode; mkv and avi usually will not.`);
14
+ }
15
+ if (buf.sampleRate !== sampleRate) {
16
+ const n = Math.max(1, Math.ceil(buf.duration * sampleRate));
17
+ const oc = new C(buf.numberOfChannels, n, sampleRate);
18
+ const s = oc.createBufferSource();
19
+ s.buffer = buf;
20
+ s.connect(oc.destination);
21
+ s.start();
22
+ buf = await oc.startRendering();
23
+ }
24
+ return {
25
+ sampleRate: buf.sampleRate,
26
+ duration: buf.duration,
27
+ channels: Array.from({ length: buf.numberOfChannels }, (_, c) => buf.getChannelData(c).slice())
28
+ };
29
+ }
30
+ /** A 32 bin luminance histogram of RGBA pixels, normalized to sum 1. */
31
+ function lumaHistogram(rgba, bins = 32) {
32
+ const h = new Float32Array(bins);
33
+ const n = Math.floor(rgba.length / 4);
34
+ for (let i = 0; i < n; i++) {
35
+ const y = .299 * rgba[i * 4] + .587 * rgba[i * 4 + 1] + .114 * rgba[i * 4 + 2];
36
+ h[Math.min(bins - 1, Math.floor(y / 256 * bins))] += 1;
37
+ }
38
+ for (let i = 0; i < bins; i++) h[i] /= Math.max(1, n);
39
+ return h;
40
+ }
41
+ /** Half the L1 distance of two normalized histograms: 0 same, 1 disjoint. */
42
+ function histDistance(a, b) {
43
+ let s = 0;
44
+ for (let i = 0; i < a.length; i++) s += Math.abs(a[i] - b[i]);
45
+ return s / 2;
46
+ }
47
+ /**
48
+ * Keyframes from sampled frames: the first frame, every frame whose
49
+ * histogram moved more than `threshold` from the last keyframe, and at
50
+ * least one every `maxGap` seconds; at most `max` frames, the biggest
51
+ * changes kept.
52
+ */
53
+ function pickKeyframes(frames, o = {}) {
54
+ const thr = o.threshold ?? .3;
55
+ const gap = o.maxGap ?? Infinity;
56
+ const keep = [];
57
+ let last = null;
58
+ frames.forEach((f, i) => {
59
+ if (!last) {
60
+ keep.push({
61
+ i,
62
+ score: Infinity
63
+ });
64
+ last = f;
65
+ return;
66
+ }
67
+ const d = histDistance(last.hist, f.hist);
68
+ if (d > thr || f.t - last.t >= gap) {
69
+ keep.push({
70
+ i,
71
+ score: d
72
+ });
73
+ last = f;
74
+ }
75
+ });
76
+ const max = o.max ?? Infinity;
77
+ return keep.length <= max ? keep.map((k) => k.i) : keep.sort((a, b) => b.score - a.score).slice(0, max).map((k) => k.i).sort((a, b) => a - b);
78
+ }
79
+ /** Sample times for a video of `duration` seconds every `step` seconds, inside the clip. */
80
+ function sampleTimes(duration, step = 1) {
81
+ const out = [];
82
+ for (let t = Math.min(.05, duration / 2); t < duration; t += step) out.push(+t.toFixed(3));
83
+ return out;
84
+ }
85
+ const RECORDER_TYPES = [
86
+ "video/webm;codecs=vp9,opus",
87
+ "video/webm;codecs=vp8,opus",
88
+ "video/webm",
89
+ "video/mp4;codecs=avc1,mp4a",
90
+ "video/mp4"
91
+ ];
92
+ /** The first type the recorder supports, or "" for the browser default. */
93
+ function pickMime(isSupported = (t) => globalThis.MediaRecorder?.isTypeSupported(t) ?? false, types = RECORDER_TYPES) {
94
+ return types.find((t) => isSupported(t)) ?? "";
95
+ }
96
+ /** Record a MediaStream (canvas.captureStream() plus audio tracks) until `stop()`; resolves the Blob. */
97
+ function record(stream, o = {}) {
98
+ const R = o.Recorder ?? globalThis.MediaRecorder;
99
+ if (!R) throw new Error("no MediaRecorder in this browser. recording is off.");
100
+ const mimeType = o.mimeType ?? pickMime();
101
+ const rec = new R(stream, {
102
+ ...mimeType ? { mimeType } : {},
103
+ ...o.bitsPerSecond ? { videoBitsPerSecond: o.bitsPerSecond } : {}
104
+ });
105
+ const parts = [];
106
+ rec.ondataavailable = (e) => {
107
+ if (e.data.size) parts.push(e.data);
108
+ };
109
+ const done = new Promise((r) => rec.onstop = () => r(new Blob(parts, { type: mimeType || rec.mimeType || "video/webm" })));
110
+ rec.start(o.timeslice ?? 1e3);
111
+ return {
112
+ mimeType,
113
+ stop: () => {
114
+ rec.stop();
115
+ return done;
116
+ }
117
+ };
118
+ }
119
+ exports.RECORDER_TYPES = RECORDER_TYPES;
120
+ exports.decodeAudio = decodeAudio;
121
+ exports.histDistance = histDistance;
122
+ exports.lumaHistogram = lumaHistogram;
123
+ exports.pickKeyframes = pickKeyframes;
124
+ exports.pickMime = pickMime;
125
+ exports.record = record;
126
+ exports.sampleTimes = sampleTimes;
127
+ return exports;
128
+ })({});
@@ -0,0 +1,117 @@
1
+ // packages/media/src/index.ts
2
+ /** Decode and resample with the browser's decoder (as earlier builds did). Names the failure when the browser refuses the container. */
3
+ async function decodeAudio(data, sampleRate = 16e3, Ctx) {
4
+ const C = Ctx ?? globalThis.OfflineAudioContext;
5
+ if (!C) throw new Error("no OfflineAudioContext here. decode on the page, not in a worker.");
6
+ const ab = data instanceof ArrayBuffer ? data.slice(0) : await data.arrayBuffer();
7
+ let buf;
8
+ try {
9
+ buf = await new C(1, 1, sampleRate).decodeAudioData(ab);
10
+ } catch (e) {
11
+ throw new Error(`this browser will not decode the audio track (${e instanceof Error ? e.message : String(e)}). if it plays in a video tag it should decode; mkv and avi usually will not.`);
12
+ }
13
+ if (buf.sampleRate !== sampleRate) {
14
+ const n = Math.max(1, Math.ceil(buf.duration * sampleRate));
15
+ const oc = new C(buf.numberOfChannels, n, sampleRate);
16
+ const s = oc.createBufferSource();
17
+ s.buffer = buf;
18
+ s.connect(oc.destination);
19
+ s.start();
20
+ buf = await oc.startRendering();
21
+ }
22
+ return {
23
+ sampleRate: buf.sampleRate,
24
+ duration: buf.duration,
25
+ channels: Array.from({ length: buf.numberOfChannels }, (_, c) => buf.getChannelData(c).slice())
26
+ };
27
+ }
28
+ /** A 32 bin luminance histogram of RGBA pixels, normalized to sum 1. */
29
+ function lumaHistogram(rgba, bins = 32) {
30
+ const h = new Float32Array(bins);
31
+ const n = Math.floor(rgba.length / 4);
32
+ for (let i = 0; i < n; i++) {
33
+ const y = .299 * rgba[i * 4] + .587 * rgba[i * 4 + 1] + .114 * rgba[i * 4 + 2];
34
+ h[Math.min(bins - 1, Math.floor(y / 256 * bins))] += 1;
35
+ }
36
+ for (let i = 0; i < bins; i++) h[i] /= Math.max(1, n);
37
+ return h;
38
+ }
39
+ /** Half the L1 distance of two normalized histograms: 0 same, 1 disjoint. */
40
+ function histDistance(a, b) {
41
+ let s = 0;
42
+ for (let i = 0; i < a.length; i++) s += Math.abs(a[i] - b[i]);
43
+ return s / 2;
44
+ }
45
+ /**
46
+ * Keyframes from sampled frames: the first frame, every frame whose
47
+ * histogram moved more than `threshold` from the last keyframe, and at
48
+ * least one every `maxGap` seconds; at most `max` frames, the biggest
49
+ * changes kept.
50
+ */
51
+ function pickKeyframes(frames, o = {}) {
52
+ const thr = o.threshold ?? .3;
53
+ const gap = o.maxGap ?? Infinity;
54
+ const keep = [];
55
+ let last = null;
56
+ frames.forEach((f, i) => {
57
+ if (!last) {
58
+ keep.push({
59
+ i,
60
+ score: Infinity
61
+ });
62
+ last = f;
63
+ return;
64
+ }
65
+ const d = histDistance(last.hist, f.hist);
66
+ if (d > thr || f.t - last.t >= gap) {
67
+ keep.push({
68
+ i,
69
+ score: d
70
+ });
71
+ last = f;
72
+ }
73
+ });
74
+ const max = o.max ?? Infinity;
75
+ return keep.length <= max ? keep.map((k) => k.i) : keep.sort((a, b) => b.score - a.score).slice(0, max).map((k) => k.i).sort((a, b) => a - b);
76
+ }
77
+ /** Sample times for a video of `duration` seconds every `step` seconds, inside the clip. */
78
+ function sampleTimes(duration, step = 1) {
79
+ const out = [];
80
+ for (let t = Math.min(.05, duration / 2); t < duration; t += step) out.push(+t.toFixed(3));
81
+ return out;
82
+ }
83
+ const RECORDER_TYPES = [
84
+ "video/webm;codecs=vp9,opus",
85
+ "video/webm;codecs=vp8,opus",
86
+ "video/webm",
87
+ "video/mp4;codecs=avc1,mp4a",
88
+ "video/mp4"
89
+ ];
90
+ /** The first type the recorder supports, or "" for the browser default. */
91
+ function pickMime(isSupported = (t) => globalThis.MediaRecorder?.isTypeSupported(t) ?? false, types = RECORDER_TYPES) {
92
+ return types.find((t) => isSupported(t)) ?? "";
93
+ }
94
+ /** Record a MediaStream (canvas.captureStream() plus audio tracks) until `stop()`; resolves the Blob. */
95
+ function record(stream, o = {}) {
96
+ const R = o.Recorder ?? globalThis.MediaRecorder;
97
+ if (!R) throw new Error("no MediaRecorder in this browser. recording is off.");
98
+ const mimeType = o.mimeType ?? pickMime();
99
+ const rec = new R(stream, {
100
+ ...mimeType ? { mimeType } : {},
101
+ ...o.bitsPerSecond ? { videoBitsPerSecond: o.bitsPerSecond } : {}
102
+ });
103
+ const parts = [];
104
+ rec.ondataavailable = (e) => {
105
+ if (e.data.size) parts.push(e.data);
106
+ };
107
+ const done = new Promise((r) => rec.onstop = () => r(new Blob(parts, { type: mimeType || rec.mimeType || "video/webm" })));
108
+ rec.start(o.timeslice ?? 1e3);
109
+ return {
110
+ mimeType,
111
+ stop: () => {
112
+ rec.stop();
113
+ return done;
114
+ }
115
+ };
116
+ }
117
+ export { RECORDER_TYPES, decodeAudio, histDistance, lumaHistogram, pickKeyframes, pickMime, record, sampleTimes };
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@hackbuild/media",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Media in a tab: decode a file's audio at any rate (16 kHz by default) with every channel kept, keyframe sampling by scene change, and canvas and stream recording with a codec ladder.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "Moheeb Zara <hackbuildvideo@gmail.com>",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/hackbuild/hackbuild-browser-ai.git",
11
+ "directory": "packages/media"
12
+ },
13
+ "engines": {
14
+ "node": "^22.18.0 || >=24.11.0"
15
+ },
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md",
26
+ "LICENSE"
27
+ ],
28
+ "unpkg": "./dist/single/index.iife.js",
29
+ "jsdelivr": "./dist/single/index.iife.js",
30
+ "scripts": {
31
+ "build": "tsc -b"
32
+ }
33
+ }