Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GIF compression #748

Merged
merged 10 commits into from
Jul 17, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions main/common/settings.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ const store = new Store({
default: '5'
}
}
},
lossyCompression: {
type: 'boolean',
default: false
}
}
});
Expand Down
55 changes: 38 additions & 17 deletions main/convert.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,10 @@ const ffmpeg = require('@ffmpeg-installer/ffmpeg');
const util = require('electron-util');
const PCancelable = require('p-cancelable');
const tempy = require('tempy');
const gifsicle = require('gifsicle');
const {track} = require('./common/analytics');
const {EditServiceContext} = require('./service-context');
const settings = require('./common/settings');

const ffmpegPath = util.fixPathForAsarUnpack(ffmpeg.path);
const timeRegex = /time=\s*(\d\d:\d\d:\d\d.\d\d)/gm;
Expand All @@ -21,13 +23,15 @@ const speedRegex = /speed=\s*(-?\d+(,\d+)*(\.\d+(e\d+)?)?)/gm;
// https://trac.ffmpeg.org/ticket/309
const makeEven = n => 2 * Math.round(n / 2);

const getConvertFunction = shouldTrack => (outputPath, options, args) => {
if (shouldTrack) {
track(`file/export/fps/${options.fps}`);
}
const getRunFunction = (shouldTrack, mode = 'convert') => (outputPath, options, args) => {
const modes = new Map([
['convert', ffmpegPath],
['compress', gifsicle]
]);
const program = modes.get(mode);

return new PCancelable((resolve, reject, onCancel) => {
const converter = execa(ffmpegPath, args);
const runner = execa(program, args);
const durationMs = moment.duration(options.endTime - options.startTime, 'seconds').asMilliseconds();
let speed;

Expand All @@ -36,12 +40,12 @@ const getConvertFunction = shouldTrack => (outputPath, options, args) => {
track('file/export/convert/canceled');
}

converter.kill();
runner.kill();
});

let stderr = '';
converter.stderr.setEncoding('utf8');
converter.stderr.on('data', data => {
runner.stderr.setEncoding('utf8');
runner.stderr.on('data', data => {
stderr += data;

data = data.trim();
Expand All @@ -68,25 +72,25 @@ const getConvertFunction = shouldTrack => (outputPath, options, args) => {
}
});

converter.on('error', reject);
runner.on('error', reject);

converter.on('exit', code => {
runner.on('exit', code => {
if (code === 0) {
if (shouldTrack) {
track('file/export/convert/completed');
track(`file/export/${mode}/completed`);
}

resolve(outputPath);
} else {
if (shouldTrack) {
track('file/export/convert/failed');
track(`file/export/${mode}/failed`);
}

reject(new Error(`ffmpeg exited with code: ${code}\n\n${stderr}`));
reject(new Error(`${program} exited with code: ${code}\n\n${stderr}`));
}
});

converter.catch(reject);
runner.catch(reject);
});
};

Expand All @@ -108,7 +112,19 @@ const mute = PCancelable.fn(async (inputPath, onCancel) => {
return mutedPath;
});

const convert = getConvertFunction(true);
const convert = getRunFunction(true);
const compress = (outputPath, options, args) => {
options.onProgress(0, '', 'Compressing');

if (settings.get('lossyCompression')) {
args = [
'--lossy=50',
...args
];
}

return getRunFunction(true, 'compress')(outputPath, options, args);
};

const convertToMp4 = PCancelable.fn(async (options, onCancel) => {
if (options.isMuted) {
Expand Down Expand Up @@ -208,7 +224,7 @@ const convertToGif = PCancelable.fn(async (options, onCancel) => {

await paletteProcessor;

return convert(options.outputPath, options, [
await convert(options.outputPath, options, [
'-i', options.inputPath,
'-i', palettePath,
'-filter_complex', `fps=${options.fps}${options.shouldCrop ? `,scale=${options.width}:${options.height}:flags=lanczos` : ''}[x]; [x][1:v]paletteuse`,
Expand All @@ -221,6 +237,11 @@ const convertToGif = PCancelable.fn(async (options, onCancel) => {
),
options.outputPath
]);

return compress(options.outputPath, options, [
karaggeorge marked this conversation as resolved.
Show resolved Hide resolved
'--batch',
options.outputPath
]);
});

const converters = new Map([
Expand Down Expand Up @@ -274,7 +295,7 @@ const convertUsingPlugin = PCancelable.fn(async ({editService, converter, ...opt
}

let canceled = false;
const convertFunction = getConvertFunction(false);
const convertFunction = getRunFunction(false);

const editPath = tmp.tmpNameSync({postfix: path.extname(croppedPath)});

Expand Down
2 changes: 1 addition & 1 deletion main/export.js
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ class Export {
...this.exportOptions,
defaultFileName: fileType ? `${path.parse(this.defaultFileName).name}.${fileType}` : this.defaultFileName,
inputPath: this.inputPath,
onProgress: (percentage, estimate) => this.setProgress(estimate ? `Converting — ${estimate} remaining` : 'Converting…', percentage),
onProgress: (percentage, estimate, action = 'Converting') => this.setProgress(estimate ? `${action} — ${estimate} remaining` : `${action}…`, percentage),
editService: this.editService ? {
service: this.editService,
config: this.editConfig,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"execa": "4.0.0",
"file-icon": "^3.0.0",
"first-run": "^2.0.0",
"gifsicle": "^5.0.0",
"got": "^9.6.0",
"insight": "^0.10.3",
"is-online": "^8.4.0",
Expand Down
24 changes: 20 additions & 4 deletions renderer/components/preferences/categories/general.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ class General extends React.Component {
cropperShortcut,
updateShortcut,
toggleShortcuts,
category
category,
lossyCompression
} = this.props;

const {showCursorSupported} = this.state;
Expand Down Expand Up @@ -184,6 +185,18 @@ class General extends React.Component {
>
<Button tabIndex={tabIndex} title="Choose" onClick={pickKapturesDir}/>
</Item>
<Item
key="lossyCompression"
parentItem
title="Lossy GIF compression"
subtitle="Smaller file size for a minor quality degradation."
>
<Switch
tabIndex={tabIndex}
checked={lossyCompression}
onClick={() => toggleSetting('lossyCompression')}
/>
</Item>
</Category>
);
}
Expand Down Expand Up @@ -215,7 +228,8 @@ General.propTypes = {
ctrlKey: PropTypes.bool.isRequired,
shiftKey: PropTypes.bool.isRequired,
character: PropTypes.string.isRequired
})
}),
lossyCompression: PropTypes.bool
};

export default connect(
Expand All @@ -233,7 +247,8 @@ export default connect(
allowAnalytics,
loopExports,
cropperShortcut,
category
category,
lossyCompression
}) => ({
showCursor,
highlightClicks,
Expand All @@ -247,7 +262,8 @@ export default connect(
allowAnalytics,
loopExports,
cropperShortcut,
category
category,
lossyCompression
}),
({
toggleSetting,
Expand Down
1 change: 1 addition & 0 deletions test/convert.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ const {mockImport} = require('./helpers/mocks');

mockImport('./common/analytics', 'analytics');
mockImport('./service-context', 'service-context');
mockImport('./common/settings', 'settings');

const {convertTo} = require('../main/convert');

Expand Down
5 changes: 5 additions & 0 deletions test/mocks/settings.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
'use strict';

module.exports = {
get: () => {}
};
Loading