forked from mifi/editly
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvideoFrameSource.js
222 lines (179 loc) · 7.12 KB
/
videoFrameSource.js
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
const execa = require('execa');
const assert = require('assert');
const { getFfmpegCommonArgs } = require('../ffmpeg');
const { readFileStreams } = require('../util');
const { rgbaToFabricImage, blurImage } = require('./fabric');
module.exports = async ({ width: canvasWidth, height: canvasHeight, channels, framerateStr, verbose, logTimes, ffmpegPath, ffprobePath, enableFfmpegLog, params }) => {
const { path, cutFrom, cutTo, resizeMode = 'contain-blur', speedFactor, inputWidth, inputHeight, width: requestedWidthRel, height: requestedHeightRel, left: leftRel = 0, top: topRel = 0, originX = 'left', originY = 'top' } = params;
const requestedWidth = requestedWidthRel ? Math.round(requestedWidthRel * canvasWidth) : canvasWidth;
const requestedHeight = requestedHeightRel ? Math.round(requestedHeightRel * canvasHeight) : canvasHeight;
const left = leftRel * canvasWidth;
const top = topRel * canvasHeight;
const ratioW = requestedWidth / inputWidth;
const ratioH = requestedHeight / inputHeight;
const inputAspectRatio = inputWidth / inputHeight;
let targetWidth = requestedWidth;
let targetHeight = requestedHeight;
let scaleFilter;
if (['contain', 'contain-blur'].includes(resizeMode)) {
if (ratioW > ratioH) {
targetHeight = requestedHeight;
targetWidth = Math.round(requestedHeight * inputAspectRatio);
} else {
targetWidth = requestedWidth;
targetHeight = Math.round(requestedWidth / inputAspectRatio);
}
scaleFilter = `scale=${targetWidth}:${targetHeight}`;
} else if (resizeMode === 'cover') {
let scaledWidth;
let scaledHeight;
if (ratioW > ratioH) {
scaledWidth = requestedWidth;
scaledHeight = Math.round(requestedWidth / inputAspectRatio);
} else {
scaledHeight = requestedHeight;
scaledWidth = Math.round(requestedHeight * inputAspectRatio);
}
// TODO improve performance by crop first, then scale?
scaleFilter = `scale=${scaledWidth}:${scaledHeight},crop=${targetWidth}:${targetHeight}`;
} else { // 'stretch'
scaleFilter = `scale=${targetWidth}:${targetHeight}`;
}
if (verbose) console.log(scaleFilter);
let ptsFilter = '';
if (speedFactor !== 1) {
if (verbose) console.log('speedFactor', speedFactor);
ptsFilter = `setpts=${speedFactor}*PTS,`;
}
const frameByteSize = targetWidth * targetHeight * channels;
// TODO assert that we have read the correct amount of frames
const buf = Buffer.allocUnsafe(frameByteSize);
let length = 0;
// let inFrameCount = 0;
// https://forum.unity.com/threads/settings-for-importing-a-video-with-an-alpha-channel.457657/
const streams = await readFileStreams(ffprobePath, path);
const firstVideoStream = streams.find((s) => s.codec_type === 'video');
// https://superuser.com/a/1116905/658247
let inputCodec;
if (firstVideoStream.codec_name === 'vp8') inputCodec = 'libvpx';
else if (firstVideoStream.codec_name === 'vp9') inputCodec = 'libvpx-vp9';
// http://zulko.github.io/blog/2013/09/27/read-and-write-video-frames-in-python-using-ffmpeg/
// Testing: ffmpeg -i 'vid.mov' -t 1 -vcodec rawvideo -pix_fmt rgba -f image2pipe - | ffmpeg -f rawvideo -vcodec rawvideo -pix_fmt rgba -s 2166x1650 -i - -vf format=yuv420p -vcodec libx264 -y out.mp4
// https://trac.ffmpeg.org/wiki/ChangingFrameRate
const args = [
...getFfmpegCommonArgs({ enableFfmpegLog }),
...(inputCodec ? ['-vcodec', inputCodec] : []),
...(cutFrom ? ['-ss', cutFrom] : []),
'-i', path,
...(cutTo ? ['-t', (cutTo - cutFrom) * speedFactor] : []),
'-vf', `${ptsFilter}fps=${framerateStr},${scaleFilter}`,
'-map', 'v:0',
'-vcodec', 'rawvideo',
'-pix_fmt', 'rgba',
'-f', 'image2pipe',
'-',
];
if (verbose) console.log(args.join(' '));
const ps = execa(ffmpegPath, args, { encoding: null, buffer: false, stdin: 'ignore', stdout: 'pipe', stderr: process.stderr });
const stream = ps.stdout;
let timeout;
let ended = false;
stream.once('end', () => {
clearTimeout(timeout);
if (verbose) console.log(path, 'ffmpeg video stream ended');
ended = true;
});
async function readNextFrame(progress, canvas) {
const rgba = await new Promise((resolve, reject) => {
if (ended) {
console.log(path, 'Tried to read next video frame after ffmpeg video stream ended');
resolve();
return;
}
// console.log('Reading new frame', path);
function onEnd() {
resolve();
}
function cleanup() {
stream.pause();
// eslint-disable-next-line no-use-before-define
stream.removeListener('data', handleChunk);
stream.removeListener('end', onEnd);
stream.removeListener('error', reject);
}
function handleChunk(chunk) {
// console.log('chunk', chunk.length);
const nCopied = length + chunk.length > frameByteSize ? frameByteSize - length : chunk.length;
chunk.copy(buf, length, 0, nCopied);
length += nCopied;
if (length > frameByteSize) console.error('Video data overflow', length);
if (length >= frameByteSize) {
// console.log('Finished reading frame', inFrameCount, path);
const out = Buffer.from(buf);
const restLength = chunk.length - nCopied;
if (restLength > 0) {
// if (verbose) console.log('Left over data', nCopied, chunk.length, restLength);
chunk.slice(nCopied).copy(buf, 0);
length = restLength;
} else {
length = 0;
}
// inFrameCount += 1;
clearTimeout(timeout);
cleanup();
resolve(out);
}
}
timeout = setTimeout(() => {
console.warn('Timeout on read video frame');
cleanup();
resolve();
}, 60000);
stream.on('data', handleChunk);
stream.on('end', onEnd);
stream.on('error', reject);
stream.resume();
});
if (!rgba) return;
assert(rgba.length === frameByteSize);
if (logTimes) console.time('rgbaToFabricImage');
const img = await rgbaToFabricImage({ width: targetWidth, height: targetHeight, rgba });
if (logTimes) console.timeEnd('rgbaToFabricImage');
img.setOptions({
originX,
originY,
});
let centerOffsetX = 0;
let centerOffsetY = 0;
if (resizeMode === 'contain' || resizeMode === 'contain-blur') {
const dirX = originX === 'left' ? 1 : -1;
const dirY = originY === 'top' ? 1 : -1;
centerOffsetX = (dirX * (requestedWidth - targetWidth)) / 2;
centerOffsetY = (dirY * (requestedHeight - targetHeight)) / 2;
}
img.setOptions({
left: left + centerOffsetX,
top: top + centerOffsetY,
});
if (resizeMode === 'contain-blur') {
const mutableImg = await new Promise((r) => img.cloneAsImage(r));
const blurredImg = await blurImage({ mutableImg, width: requestedWidth, height: requestedHeight });
blurredImg.setOptions({
left,
top,
originX,
originY,
});
canvas.add(blurredImg);
}
canvas.add(img);
}
const close = () => {
if (verbose) console.log('Close', path);
ps.cancel();
};
return {
readNextFrame,
close,
};
};