merge.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. 'use strict';
  2. import childProcess = require('child_process');
  3. import fs = require('fs');
  4. import path = require('path');
  5. import os = require('os');
  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, rtmpInputPath: string, filePath: string,
  11. streamMode: string, done: (err: Error) => void)
  12. {
  13. const subtitlePath = filePath + '.' + (subtitle.formats[config.format] ? config.format : 'ass');
  14. let videoPath = filePath;
  15. if (streamMode === 'RTMP')
  16. {
  17. videoPath += path.extname(rtmpInputPath);
  18. }
  19. else
  20. {
  21. videoPath += '.mp4';
  22. }
  23. childProcess.exec(command() + ' ' +
  24. '-o "' + filePath + '.mkv" ' +
  25. '"' + videoPath + '" ' +
  26. (isSubtitled ? '"' + subtitlePath + '"' : ''), {
  27. maxBuffer: Infinity,
  28. }, (err) =>
  29. {
  30. if (err)
  31. {
  32. return done(err);
  33. }
  34. unlink(videoPath, subtitlePath, (errin) =>
  35. {
  36. if (errin)
  37. {
  38. unlinkTimeout(videoPath, subtitlePath, 5000);
  39. }
  40. done(null);
  41. });
  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. }