srt.ts 1.8 KB

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