merge.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. 'use strict';
  2. export = main;
  3. import childProcess = require('child_process');
  4. import fs = require('fs');
  5. import path = require('path');
  6. import os = require('os');
  7. import subtitle = require('../subtitle/index');
  8. import typings = require('../typings');
  9. /**
  10. * Merges the subtitle and video files into a Matroska Multimedia Container.
  11. */
  12. function main(config: typings.IConfig, rtmpInputPath: string, filePath: string, done: (err: Error) => void) {
  13. var subtitlePath = filePath + '.' + (subtitle.formats[config.format] ? config.format : 'ass');
  14. var videoPath = filePath + path.extname(rtmpInputPath);
  15. childProcess.exec(command() + ' ' +
  16. '-o "' + filePath + '.mkv" ' +
  17. '"' + videoPath + '" ' +
  18. '"' + subtitlePath + '"', {
  19. maxBuffer: Infinity
  20. }, err => {
  21. if (err) return done(err);
  22. unlink(videoPath, subtitlePath, err => {
  23. if (err) unlinkTimeout(videoPath, subtitlePath, 5000);
  24. done(null);
  25. });
  26. });
  27. }
  28. /**
  29. * Determines the command for the operating system.
  30. */
  31. function command(): string {
  32. if (os.platform() !== 'win32') return 'mkvmerge';
  33. return path.join(__dirname, '../../bin/mkvmerge.exe');
  34. }
  35. /**
  36. * Unlinks the video and subtitle.
  37. * @private
  38. */
  39. function unlink(videoPath: string, subtitlePath: string, done: (err: Error) => void) {
  40. fs.unlink(videoPath, err => {
  41. if (err) return done(err);
  42. fs.unlink(subtitlePath, done);
  43. });
  44. }
  45. /**
  46. * Attempts to unlink the video and subtitle with a timeout between each try.
  47. */
  48. function unlinkTimeout(videoPath: string, subtitlePath: string, timeout: number) {
  49. setTimeout(() => {
  50. unlink(videoPath, subtitlePath, err => {
  51. if (err) unlinkTimeout(videoPath, subtitlePath, timeout);
  52. });
  53. }, timeout);
  54. }