aboutsummaryrefslogtreecommitdiffstats
path: root/src/client/players/RawSubs.hx
blob: a4404b0c95b3f1344e8649dfe6aa6f25a2d79a77 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
package client.players;

import Types.VideoItem;
import haxe.crypto.Base64;
import haxe.io.Bytes;
import js.Browser.document;
import js.Browser.window;
import js.Browser;
import js.html.VideoElement;

private typedef Duration = {
	h:Int,
	m:Int,
	s:Int,
	ms:Int
}

class RawSubs {
	public static function loadSubs(subsUrl:String, video:VideoElement):Void {
		if (subsUrl == null || subsUrl.length == 0) return;
		final ext = PathTools.urlExtension(subsUrl);
		// do not load subs if there is custom plugin
		if (JsApi.hasSubtitleSupport(ext)) return;
		var url = encodeURI(subsUrl);
		if (!url.startsWith("/")) {
			final protocol = Browser.location.protocol;
			if (!url.startsWith("http")) url = '$protocol//$url';
			url = '/proxy?url=$url';
		}

		switch ext {
			case "ass":
				parseAss(video, url);
			case "srt":
				parseSrt(video, url);
			case "vtt":
				onParsed(video, "VTT subtitles", url);
				// parseVtt(video, url);
		}
	}

	static function parseSrt(video:VideoElement, url:String):Void {
		window.fetch(url).then(response -> {
			return response.text();
		}).then(text -> {
			if (isProxyError(text)) return;
			final subs:Array<{
				counter:String,
				time:String,
				text:String
			}> = [];
			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: time.replace(",", "."),
					text: textLines.join("\n").ltrim()
				});
			}
			var data = "WEBVTT\n\n";
			for (sub in subs) {
				data += '${sub.counter}\n';
				data += '${sub.time}\n';
				data += '${sub.text}\n\n';
			}
			final textBase64 = "data:text/plain;base64,";
			final url = textBase64 + Base64.encode(Bytes.ofString(data));
			onParsed(video, "SRT subtitles", url);
		});
	}

	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();
		}).then(text -> {
			if (isProxyError(text)) return;
			final subs:Array<{
				counter:Int,
				start:String,
				end:String,
				text:String,
			}> = [];
			final lines = text.replace("\r\n", "\n").split("\n");
			final matchFormat = ~/^Format:/;
			final matchDialogue = ~/^Dialogue:/;
			final blockTags = ~/\{\\[^}]*\}/g;
			final spaceTags = ~/\\(n|h)/g;
			final newLineTag = ~/\\N/g;
			final manyNewLineTags = ~/\\N(\\N)+/g;
			final drawingMode = ~/\\p[124]/;
			var eventStart = false;
			var formatFound = false;
			final ids:Map<String, Int> = [];
			var subsCounter = 1;
			for (rawLine in lines) {
				final line = rawLine.trim();
				if (!eventStart) {
					eventStart = line.startsWith("[Events]");
					continue;
				}

				if (!formatFound) {
					formatFound = matchFormat.match(line);
					if (!formatFound) continue;
					final list = matchFormat.replace(line, "").split(",");
					for (i in 0...list.length) {
						ids[list[i].trim()] = i;
					}
					ids["_length"] = list.length;
				}

				if (!matchDialogue.match(line)) continue;
				var list = matchDialogue.replace(line, "").split(",");
				while (list.length > ids["_length"]) {
					final el = list.pop();
					list[list.length - 1] += el;
				}
				list = list.map((e) -> e.trim());
				var text = list[ids["Text"]];
				if (drawingMode.match(text)) text = "";
				text = blockTags.replace(text, "");
				text = spaceTags.replace(text, " ");
				final nTag = "\\N";
				text = manyNewLineTags.replace(text, nTag);
				if (text.startsWith(nTag)) text = text.substr(nTag.length);
				if (text.endsWith(nTag)) text = text.substr(0, text.length - 2);
				text = newLineTag.replace(text, "\n");
				subs.push({
					counter: subsCounter,
					start: convertAssTime(list[ids["Start"]]),
					end: convertAssTime(list[ids["End"]]),
					text: text,
				});
				subsCounter++;
			}

			var data = "WEBVTT\n\n";
			for (sub in subs) {
				data += '${sub.counter}\n';
				data += '${sub.start} --> ${sub.end}\n';
				data += '${sub.text}\n\n';
			}
			final textBase64 = "data:text/plain;base64,";
			final url = textBase64 + Base64.encode(Bytes.ofString(data));
			onParsed(video, "ASS subtitles", url);
		});
	}

	static final assTimeStamp = ~/([0-9]+):([0-9][0-9]):([0-9][0-9]).([0-9][0-9])/;

	static function convertAssTime(time:String):String {
		if (!assTimeStamp.match(time)) {
			return toVttTime({
				h: 0,
				m: 0,
				s: 0,
				ms: 0,
			});
		}
		final h:Int = Std.parseInt(assTimeStamp.matched(1));
		final m:Int = Std.parseInt(assTimeStamp.matched(2));
		final s:Int = Std.parseInt(assTimeStamp.matched(3));
		final ms:Int = Std.parseInt(assTimeStamp.matched(4)) * 10;
		return toVttTime({
			h: h,
			m: m,
			s: s,
			ms: ms,
		});
	}

	static function parseVtt(video:VideoElement, url:String):Void {
		window.fetch(url).then(response -> response.text()).then(text -> {
			if (isProxyError(text)) return;
			final textBase64 = "data:text/plain;base64,";
			final url = textBase64 + Base64.encode(Bytes.ofString(text));
			onParsed(video, "VTT subtitles", url);
		});
	}

	static function isProxyError(text:String):Bool {
		if (text.startsWith("Proxy error:")) {
			Main.serverMessage("Failed to add subs: proxy error");
			trace('Failed to add subs: $text');
			return true;
		}
		return false;
	}

	static function onParsed(video:VideoElement, name:String, dataUrl:String) {
		final trackEl = document.createTrackElement();
		trackEl.kind = "captions";
		trackEl.label = name;
		trackEl.srclang = "en";
		trackEl.src = dataUrl;
		// trackEl.default_ = true;
		video.appendChild(trackEl);
		final track = trackEl.track;
		track.mode = SHOWING;
	}

	static inline function encodeURI(data:String):String {
		return js.Syntax.code("encodeURI({0})", data);
	}

	static inline function toVttTime(time:Duration):String {
		final h = '${time.h}'.lpad("0", 2);
		final m = '${time.m}'.lpad("0", 2);
		final s = '${time.s}'.lpad("0", 2);
		final ms = '${time.ms}'.lpad("0", 3).substr(0, 3);
		return '$h:$m:$s.$ms';
	}

	static inline function secondsToDuration(seconds:Float):Duration {
		final h = Std.int(seconds / 60 / 60);
		final m = Std.int(seconds / 60) - h * 60;
		final s = Std.int(seconds % 60);
		final ms = Std.int((seconds - Std.int(seconds)) * 1000);
		return {
			h: h,
			m: m,
			s: s,
			ms: ms
		}
	}
}
send patches to the email below
yukais@pinapelz.com
include the subject [PATCH repo_name]
pinapelz.com
homepage