forked from wulkano/Kap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.js
194 lines (161 loc) · 5.35 KB
/
convert.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
/* eslint-disable array-element-newline */
'use strict';
const os = require('os');
const path = require('path');
const execa = require('execa');
const moment = require('moment');
const tmp = require('tmp');
const ffmpeg = require('@ffmpeg-installer/ffmpeg');
const util = require('electron-util');
const PCancelable = require('p-cancelable');
const tempy = require('tempy');
const {track} = require('./common/analytics');
const ffmpegPath = util.fixPathForAsarUnpack(ffmpeg.path);
const durationRegex = /Duration: (\d\d:\d\d:\d\d.\d\d)/gm;
const frameRegex = /frame=\s+(\d+)/gm;
// https://trac.ffmpeg.org/ticket/309
const makeEven = n => 2 * Math.round(n / 2);
const convert = (outputPath, opts, args) => {
track(`file/export/fps/${opts.fps}`);
return new PCancelable((resolve, reject, onCancel) => {
const converter = execa(ffmpegPath, args);
let amountOfFrames;
onCancel(() => {
track('file/export/convert/canceled');
converter.kill();
});
let stderr = '';
converter.stderr.setEncoding('utf8');
converter.stderr.on('data', data => {
stderr += data;
data = data.trim();
const matchesDuration = durationRegex.exec(data);
const matchesFrame = frameRegex.exec(data);
if (matchesDuration) {
amountOfFrames = Math.ceil(moment.duration(matchesDuration[1]).asSeconds() * 30);
} else if (matchesFrame) {
const currentFrame = matchesFrame[1];
opts.onProgress(currentFrame / amountOfFrames);
}
});
converter.on('error', reject);
converter.on('exit', code => {
if (code === 0) {
track('file/export/convert/completed');
resolve(outputPath);
} else {
track('file/export/convert/failed');
reject(new Error(`ffmpeg exited with code: ${code}\n\n${stderr}`));
}
});
converter.catch(reject);
});
};
const mute = PCancelable.fn(async (inputPath, onCancel) => {
const mutedPath = tmp.tmpNameSync({postfix: path.extname(inputPath)});
const converter = execa(ffmpegPath, [
'-i', inputPath,
'-an',
'-vcodec', 'copy',
mutedPath
]);
onCancel(() => {
converter.kill();
});
await converter;
return mutedPath;
});
const convertToMp4 = PCancelable.fn(async (opts, onCancel) => {
if (opts.isMuted) {
const muteProcess = mute(opts.inputPath);
onCancel(() => {
muteProcess.cancel();
});
opts.inputPath = await muteProcess;
}
return convert(opts.outputPath, opts, [
'-i', opts.inputPath,
'-r', opts.fps,
'-s', `${makeEven(opts.width)}x${makeEven(opts.height)}`,
'-ss', opts.startTime,
'-to', opts.endTime,
opts.outputPath
]);
});
const convertToWebm = PCancelable.fn(async (opts, onCancel) => {
if (opts.isMuted) {
const muteProcess = mute(opts.inputPath);
onCancel(() => {
muteProcess.cancel();
});
opts.inputPath = await muteProcess;
}
return convert(opts.outputPath, opts, [
'-i', opts.inputPath,
// http://wiki.webmproject.org/ffmpeg
// https://trac.ffmpeg.org/wiki/Encode/VP9
'-threads', Math.max(os.cpus().length - 1, 1),
'-deadline', 'good', // `best` is twice as slow and only slighty better
'-b:v', '1M', // Bitrate (same as the MP4)
'-codec:v', 'vp9',
'-codec:a', 'vorbis',
'-strict', '-2', // Needed because `vorbis` is experimental
'-r', opts.fps,
'-s', `${opts.width}x${opts.height}`,
'-ss', opts.startTime,
'-to', opts.endTime,
opts.outputPath
]);
});
// Should be similiar to the Gif generation
const convertToApng = opts => {
return convert(opts.outputPath, opts, [
'-i', opts.inputPath,
'-vf', `fps=${opts.fps},scale=${opts.width}:${opts.height}:flags=lanczos[x]`,
// Strange for APNG instead of -loop it uses -plays see: https://stackoverflow.com/questions/43795518/using-ffmpeg-to-create-looping-apng
'-plays', opts.loop === true ? '0' : '1', // 0 == forever; 1 == no loop
'-ss', opts.startTime,
'-to', opts.endTime,
opts.outputPath
]);
};
// `time ffmpeg -i original.mp4 -vf fps=30,scale=480:-1::flags=lanczos,palettegen palette.png`
// `time ffmpeg -i original.mp4 -i palette.png -filter_complex 'fps=30,scale=-1:-1:flags=lanczos[x]; [x][1:v]paletteuse' palette.gif`
const convertToGif = PCancelable.fn(async (opts, onCancel) => {
const palettePath = tmp.tmpNameSync({postfix: '.png'});
const paletteProcessor = execa(ffmpegPath, [
'-i', opts.inputPath,
'-vf', `fps=${opts.fps},scale=${opts.width}:${opts.height}:flags=lanczos,palettegen`,
palettePath
]);
onCancel(() => {
paletteProcessor.kill();
});
await paletteProcessor;
return convert(opts.outputPath, opts, [
'-i', opts.inputPath,
'-i', palettePath,
'-filter_complex', `fps=${opts.fps},scale=${opts.width}:${opts.height}:flags=lanczos[x]; [x][1:v]paletteuse`,
'-loop', opts.loop === true ? '0' : '-1', // 0 == forever; -1 == no loop
'-ss', opts.startTime,
'-to', opts.endTime,
opts.outputPath
]);
});
const converters = new Map([
['gif', convertToGif],
['mp4', convertToMp4],
['webm', convertToWebm],
['apng', convertToApng]
]);
const convertTo = (opts, format) => {
const outputPath = path.join(tempy.directory(), opts.defaultFileName);
const converter = converters.get(format);
opts.onProgress(0);
track(`file/export/format/${format}`);
return converter({outputPath, ...opts});
};
module.exports = {
convertTo,
converters
};