Skip to content

Instantly share code, notes, and snippets.

@johan
Created December 21, 2016 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johan/5c631348b4bccd1dd8aba783a2b278d9 to your computer and use it in GitHub Desktop.
Save johan/5c631348b4bccd1dd8aba783a2b278d9 to your computer and use it in GitHub Desktop.
A little subtitle file tweaking class
class SRT {
constructor(s) { this.setSubs(typeof s === 'string' ? SRT.decode(s) : s); }
toString() { return SRT.encode(this.subs); }
timeShift(dt) {
return new SRT(this.subs.map(s => Object.assign({}, s, {t: s.t + dt})));
}
getSubs() { return this.subs.map(o => Object.assign({}, o)); }
setSubs(subs) { this.subs = subs; return this; }
static decode(s) { return s.split('\n\n').filter(i=>i).map(SRT.decodeItem); }
static encode(subs) { return subs.map(SRT.encodeItem).join('\n\n') + '\n'; }
static decodeTime(t) {
return t.split(/[:,]/).reduce(
(s, n, i) => parseInt(n, 10) + s * (i === 3 ? 1000 : 60), 0
);
}
static encodeTime(n) {
const fmt = (n, z) => (z + n).slice(-z.length);
return [1000, 60, 60, Infinity].reduce((r, f, i) => {
const t = n % f, sep = [new String(''), ','][i] || ':';
n = (n - t) / f;
return fmt(t, i ? '00' : '000') + sep + r;
}, '');
}
static decodeItem(raw) {
const s = raw.split('\n');
const n = Number(s.shift());
const [t, T] = s.shift().split(' --> ').map(SRT.decodeTime);
const d = T - t;
const m = s.join('\n');
return { n, t, d, m };
}
static encodeItem({ n, t, d, m }) {
return [ n
, SRT.encodeTime(t) + ' --> ' + SRT.encodeTime(t + d)
, m
].join('\n');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment