gifski.js 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. "use strict";
  2. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  3. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  4. return new (P || (P = Promise))(function (resolve, reject) {
  5. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  6. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  7. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  8. step((generator = generator.apply(thisArg, _arguments || [])).next());
  9. });
  10. };
  11. Object.defineProperty(exports, "__esModule", { value: true });
  12. const child_process_1 = require("child_process");
  13. const fs_1 = require("fs");
  14. const loggers_1 = require("./loggers");
  15. const logger = (0, loggers_1.getLogger)('gifski');
  16. const sizeLimit = 10 * Math.pow(2, 20);
  17. const roundToEven = (n) => Math.ceil(n / 2) * 2;
  18. exports.default = (inputFilePath, targetWidth) => __awaiter(void 0, void 0, void 0, function* () {
  19. const outputFilePath = inputFilePath.replace(/(?:\.[^.]*)?$/, '.gif');
  20. try {
  21. const args = [
  22. inputFilePath,
  23. '-o',
  24. outputFilePath,
  25. '--fps',
  26. '12.5',
  27. '--quiet',
  28. '--quality',
  29. '90',
  30. ];
  31. if (typeof (targetWidth) === 'number') {
  32. args.push('--width', roundToEven(targetWidth).toString());
  33. }
  34. logger.info(` gifski ${args.join(' ')}`);
  35. const gifskiSpawn = (0, child_process_1.spawn)('gifski', args);
  36. const gifskiResult = new Promise((resolve, reject) => {
  37. const sizeChecker = setInterval(() => {
  38. if ((0, fs_1.existsSync)(outputFilePath) && (0, fs_1.statSync)(outputFilePath).size > sizeLimit)
  39. gifskiSpawn.kill();
  40. }, 5000);
  41. gifskiSpawn.on('exit', () => {
  42. clearInterval(sizeChecker);
  43. if (!(0, fs_1.existsSync)(outputFilePath) || (0, fs_1.statSync)(outputFilePath).size === 0)
  44. return reject('no file was created on exit');
  45. logger.info(`gif conversion succeeded, file path: ${outputFilePath}`);
  46. resolve(outputFilePath);
  47. });
  48. });
  49. const stderr = [];
  50. gifskiSpawn.stderr.on('data', errdata => stderr.push(errdata));
  51. gifskiSpawn.stderr.on('end', () => {
  52. if (stderr.length !== 0) {
  53. if (!gifskiSpawn.killed)
  54. gifskiSpawn.kill();
  55. throw Error(Buffer.concat(stderr).toString());
  56. }
  57. });
  58. return yield gifskiResult;
  59. }
  60. catch (error) {
  61. logger.error(`error converting video to gif ${error ? `message: ${error}` : ''}`);
  62. throw Error('error converting video to gif');
  63. }
  64. });