srt.ts 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. 'use strict';
  2. import xml2js = require('xml2js');
  3. /**
  4. * Converts an input buffer to a SubRip subtitle.
  5. */
  6. export default function(input: Buffer|string, done: (err: Error, subtitle?: string) => void) {
  7. var options = {explicitArray: false, explicitRoot: false};
  8. xml2js.parseString(input.toString(), options, (err: Error, xml: ISubtitle) => {
  9. try {
  10. if (err) return done(err);
  11. done(null, xml.events.event.map((event, index) => {
  12. var attributes = event.$;
  13. return (index + 1) + '\n' +
  14. time(attributes.start) + ' --> ' + time(attributes.end) + '\n' +
  15. text(attributes.text) + '\n';
  16. }).join('\n'));
  17. } catch (err) {
  18. done(err);
  19. }
  20. });
  21. }
  22. /**
  23. * Prefixes a value.
  24. */
  25. function prefix(value: string, length: number): string {
  26. while (value.length < length) value = '0' + value;
  27. return value;
  28. }
  29. /**
  30. * Suffixes a value.
  31. */
  32. function suffix(value: string, length: number): string {
  33. while (value.length < length) value = value + '0';
  34. return value;
  35. }
  36. /**
  37. * Formats a text value.
  38. */
  39. function text(value: string): string {
  40. return value
  41. .replace(/{\\i1}/g, '<i>').replace(/{\\i0}/g, '</i>')
  42. .replace(/{\\b1}/g, '<b>').replace(/{\\b0}/g, '</b>')
  43. .replace(/{\\u1}/g, '<u>').replace(/{\\u0}/g, '</u>')
  44. .replace(/{[^}]+}/g, '')
  45. .replace(/(\s+)?\\n(\s+)?/ig, '\n')
  46. .trim();
  47. }
  48. /**
  49. * Formats a time stamp.
  50. */
  51. function time(value: string): string {
  52. var all = value.match(/^([0-9]+):([0-9]+):([0-9]+)\.([0-9]+)$/);
  53. if (!all) throw new Error('Invalid time.');
  54. var hours = prefix(all[1], 2);
  55. var minutes = prefix(all[2], 2);
  56. var seconds = prefix(all[3], 2);
  57. var milliseconds = suffix(all[4], 3);
  58. return hours + ':' + minutes + ':' + seconds + ',' + milliseconds;
  59. }