merge.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. import childProcess = require('child_process');
  3. import fs = require('fs');
  4. import os = require('os');
  5. import path = require('path');
  6. import subtitle from '../subtitle/index';
  7. /**
  8. * Merges the subtitle and video files into a Matroska Multimedia Container.
  9. */
  10. export default function(config: IConfig, isSubtitled: boolean, videoFileExtention: string, filePath: string,
  11. verbose: boolean, done: (err: Error) => void)
  12. {
  13. const subtitlePath = filePath + '.' + (subtitle.formats[config.format] ? config.format : 'ass');
  14. let videoPath = filePath;
  15. let cp;
  16. videoPath += videoFileExtention;
  17. cp = childProcess.exec(command() + ' ' +
  18. '-o "' + filePath + '.mkv" ' +
  19. '"' + videoPath + '" ' +
  20. (isSubtitled ? '"' + subtitlePath + '"' : ''), {
  21. maxBuffer: Infinity,
  22. }, (err) =>
  23. {
  24. if (err)
  25. {
  26. return done(err);
  27. }
  28. unlink(videoPath, subtitlePath, (errin) =>
  29. {
  30. if (errin)
  31. {
  32. unlinkTimeout(videoPath, subtitlePath, 5000);
  33. }
  34. done(null);
  35. });
  36. });
  37. if (verbose === true)
  38. {
  39. cp.stdin.pipe(process.stdin);
  40. cp.stdout.pipe(process.stdout);
  41. cp.stderr.pipe(process.stderr);
  42. }
  43. }
  44. /**
  45. * Determines the command for the operating system.
  46. */
  47. function command(): string
  48. {
  49. if (os.platform() !== 'win32')
  50. {
  51. return 'mkvmerge';
  52. }
  53. return '"' + path.join(__dirname, '../../bin/mkvmerge.exe') + '"';
  54. }
  55. /**
  56. * Unlinks the video and subtitle.
  57. * @private
  58. */
  59. function unlink(videoPath: string, subtitlePath: string, done: (err: Error) => void)
  60. {
  61. fs.unlink(videoPath, (err) =>
  62. {
  63. if (err)
  64. {
  65. return done(err);
  66. }
  67. fs.unlink(subtitlePath, done);
  68. });
  69. }
  70. /**
  71. * Attempts to unlink the video and subtitle with a timeout between each try.
  72. */
  73. function unlinkTimeout(videoPath: string, subtitlePath: string, timeout: number)
  74. {
  75. setTimeout(() =>
  76. {
  77. unlink(videoPath, subtitlePath, (err) =>
  78. {
  79. if (err)
  80. {
  81. unlinkTimeout(videoPath, subtitlePath, timeout);
  82. }
  83. });
  84. }, timeout);
  85. }