diff options
| author | RblSb <msrblsb@gmail.com> | 2024-04-21 21:23:49 +0300 |
|---|---|---|
| committer | RblSb <msrblsb@gmail.com> | 2024-04-21 21:23:49 +0300 |
| commit | 8679f8edcb6d2f3142db30848c640aed6fe883b8 (patch) | |
| tree | d61dc27c32de84fdc2e8f9ce56134e7b24551cd8 /src | |
| parent | 00f12e898954cb4683cdf7aa9ff0ef04a33ada23 (diff) | |
Improve srt parsing
Diffstat (limited to 'src')
| -rw-r--r-- | src/client/players/RawSubs.hx | 40 |
1 files changed, 35 insertions, 5 deletions
diff --git a/src/client/players/RawSubs.hx b/src/client/players/RawSubs.hx index d7e32e2..8448dfd 100644 --- a/src/client/players/RawSubs.hx +++ b/src/client/players/RawSubs.hx @@ -51,17 +51,24 @@ class RawSubs { time:String, text:String }> = []; - final blocks = text.replace("\r\n", "\n").split("\n\n"); - for (block in blocks) { - final lines = block.split("\n"); + final lines = text.replace("\r\n", "\n").split("\n"); + final blocks = getSrtBlocks(lines); + final badTimeReg = ~/(,[0-9]+)/g; + for (lines in blocks) { if (lines.length < 3) continue; final textLines = [ for (i in 2...lines.length) lines[i] ]; + // fix incomplete ms in timestamps like `00:00:02,50 --> 00:00:06,220` + final time = badTimeReg.map(lines[1], reg -> { + final ms = reg.matched(1); + if (ms.length < 4) return ms.rpad("0", 4); + return ms; + }); subs.push({ counter: lines[0], - time: lines[1].replace(",", "."), - text: textLines.join("\n") + time: time.replace(",", "."), + text: textLines.join("\n").ltrim() }); } var data = "WEBVTT\n\n"; @@ -76,6 +83,29 @@ class RawSubs { }); } + static function getSrtBlocks(lines:Array<String>):Array<Array<String>> { + final blocks = []; + final isNumLineReg = ~/^([0-9]+)$/; + // [id, time, firstTextLine, ... lastTextLine] + var block = []; + for (i => line in lines) { + if (blocks.length == 0 && line.length == 0) continue; + final prevLine = lines[i - 1] ?? ""; + final nextLine = lines[i + 1] ?? ""; + // block id line + if (prevLine.length == 0 && isNumLineReg.match(line) && nextLine.contains("-->")) { + // push previously collected block and start new one + if (block.length > 0) { + blocks.push(block); + block = []; + } + } + block.push(line); + } + if (block.length > 0) blocks.push(block); + return blocks; + } + static function parseAss(video:VideoElement, url:String):Void { window.fetch(url).then(response -> { return response.text(); |
