1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
|
import {
Input,
ALL_FORMATS,
BlobSource,
VideoSampleSink,
type VideoCodec,
} from "mediabunny";
import { createTimelineAudioBuffer } from "@/media/audio";
import type { SceneTracks } from "@/timeline";
import type { MediaAsset } from "@/media/types";
import { TICKS_PER_SECOND } from "@/wasm";
import { renderThumbnailDataUrl } from "./thumbnail";
export type VideoFileData = {
duration: number;
width: number;
height: number;
fps: number;
hasAudio: boolean;
codec: VideoCodec | null;
canDecode: boolean;
thumbnailUrl: string | null;
};
export async function readVideoFile({
file,
}: {
file: File;
}): Promise<VideoFileData> {
const input = new Input({
source: new BlobSource(file),
formats: ALL_FORMATS,
});
try {
const duration = await input.computeDuration();
const videoTrack = await input.getPrimaryVideoTrack();
if (!videoTrack) {
throw new Error("No video track found in the file");
}
const canDecode = await videoTrack.canDecode();
const packetStats = await videoTrack.computePacketStats(100);
const audioTrack = await input.getPrimaryAudioTrack();
let thumbnailUrl: string | null = null;
if (canDecode) {
const sink = new VideoSampleSink(videoTrack);
const frame = await sink.getSample(1);
if (frame) {
try {
thumbnailUrl = renderThumbnailDataUrl({
width: videoTrack.displayWidth,
height: videoTrack.displayHeight,
draw: ({ context, width, height }) => {
frame.draw(context, 0, 0, width, height);
},
});
} finally {
frame.close();
}
}
}
return {
duration,
width: videoTrack.displayWidth,
height: videoTrack.displayHeight,
fps: packetStats.averagePacketRate,
hasAudio: audioTrack !== null,
codec: videoTrack.codec,
canDecode,
thumbnailUrl,
};
} finally {
input.dispose();
}
}
const SAMPLE_RATE = 44100;
const NUM_CHANNELS = 2;
const EMPTY_TIMELINE_SILENT_DURATION_SECONDS = 0.1;
const MIN_SILENT_DURATION_SECONDS = 0.001;
export const extractTimelineAudio = async ({
tracks,
mediaAssets,
totalDuration,
onProgress,
}: {
tracks: SceneTracks;
mediaAssets: MediaAsset[];
totalDuration: number;
onProgress?: (progress: number) => void;
}): Promise<Blob> => {
if (totalDuration === 0) {
return createWavBlob({
samples: new Float32Array(
SAMPLE_RATE * EMPTY_TIMELINE_SILENT_DURATION_SECONDS,
),
});
}
onProgress?.(10);
const audioBuffer = await createTimelineAudioBuffer({
tracks,
mediaAssets,
duration: totalDuration,
sampleRate: SAMPLE_RATE,
});
if (!audioBuffer) {
const silentDurationSeconds = Math.max(
MIN_SILENT_DURATION_SECONDS,
totalDuration / TICKS_PER_SECOND,
);
const silentSamples = new Float32Array(
Math.ceil(silentDurationSeconds * SAMPLE_RATE) * NUM_CHANNELS,
);
return createWavBlob({ samples: silentSamples });
}
onProgress?.(90);
const interleavedSamples = interleaveAudioBuffer({ audioBuffer });
onProgress?.(100);
return createWavBlob({ samples: interleavedSamples });
};
function interleaveAudioBuffer({
audioBuffer,
}: {
audioBuffer: AudioBuffer;
}): Float32Array {
const numChannels = Math.min(NUM_CHANNELS, audioBuffer.numberOfChannels);
const interleavedSamples = new Float32Array(
audioBuffer.length * NUM_CHANNELS,
);
for (let sampleIndex = 0; sampleIndex < audioBuffer.length; sampleIndex++) {
for (let channel = 0; channel < NUM_CHANNELS; channel++) {
const sourceChannel = Math.min(channel, Math.max(0, numChannels - 1));
interleavedSamples[sampleIndex * NUM_CHANNELS + channel] =
audioBuffer.getChannelData(sourceChannel)[sampleIndex] ?? 0;
}
}
return interleavedSamples;
}
function createWavBlob({ samples }: { samples: Float32Array }): Blob {
const numChannels = NUM_CHANNELS;
const bitsPerSample = 16;
const bytesPerSample = bitsPerSample / 8;
const numSamples = samples.length / numChannels;
const dataSize = numSamples * numChannels * bytesPerSample;
const buffer = new ArrayBuffer(44 + dataSize);
const view = new DataView(buffer);
// riff header
writeString({ view, offset: 0, str: "RIFF" });
view.setUint32(4, 36 + dataSize, true);
writeString({ view, offset: 8, str: "WAVE" });
// fmt chunk
writeString({ view, offset: 12, str: "fmt " });
view.setUint32(16, 16, true);
view.setUint16(20, 1, true);
view.setUint16(22, numChannels, true);
view.setUint32(24, SAMPLE_RATE, true);
view.setUint32(28, SAMPLE_RATE * numChannels * bytesPerSample, true);
view.setUint16(32, numChannels * bytesPerSample, true);
view.setUint16(34, bitsPerSample, true);
// data chunk
writeString({ view, offset: 36, str: "data" });
view.setUint32(40, dataSize, true);
// convert float32 to int16 and write
let offset = 44;
for (let i = 0; i < samples.length; i++) {
const sample = Math.max(-1, Math.min(1, samples[i]));
const int16 = sample < 0 ? sample * 0x8000 : sample * 0x7fff;
view.setInt16(offset, int16, true);
offset += 2;
}
return new Blob([buffer], { type: "audio/wav" });
}
function writeString({
view,
offset,
str,
}: {
view: DataView;
offset: number;
str: string;
}): void {
for (let i = 0; i < str.length; i++) {
view.setUint8(offset + i, str.charCodeAt(i));
}
}
|