summaryrefslogtreecommitdiff
path: root/main.ha
blob: 953e917933f9efe5c06c94bdbb5173884c076eb4 (plain)
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
// srtplay - play .srt subtitle files in a TUI
// Copyright (c) 2023 Sam Nystrom <sam@samnystrom.dev>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use bufio;
use encoding::utf8;
use getopt;
use io;
use format::xml;
use fmt;
use fs;
use os;
use strconv;
use strings;
use strio;
use time;
use unix::poll;
use unix::tty;
use vt;

type state = struct {
	subtitles: []subtitle,

	start: time::instant,
	length: time::duration,
	elapsed: time::duration,
	pause_start: (time::instant | void),

	term: *vt::term,
};

type subtitle = struct {
	index: uint,
	start: time::duration,
	end: time::duration,
	text: vt::styled,
};

export fn main() void = {
	let help: []getopt::help = [
		"Play a .srt subtitle file",
		"<file>",
	];
	let cmd = getopt::parse(os::args, help...);
	defer getopt::finish(&cmd);
	if (len(cmd.args) != 1) {
		getopt::printusage(os::stderr, os::args[0], help)!;
		os::exit(1);
	};

	if (!tty::isatty(os::stdin_file)) {
		fmt::fatal("Error: stdin is not a tty");
	};

	let path = cmd.args[0];
	let mode = os::stat(path)!.mode;
	if (mode & fs::mode::DIR != 0) {
		fmt::fatalf("Error: '{}' is a directory\n", path);
	};
	let file = match (os::open(path)) {
	case let f: io::file =>
		yield f;
	case let err: fs::error =>
		fmt::fatalf("Error reading '{}': {}\n", path, fs::strerror(err));
	};

	let subtitles = parse_srt(file);
	io::close(file)!;
	defer free(subtitles);
	defer for (let i = 0z; i < len(subtitles); i += 1) {
		let text = subtitles[i].text;
		for (let j = 0z; j < len(text.args); j += 1) {
			free((text.args[j] as vt::styled).args[0] as str);
		};
		free(text.args);
	};

	let state = state {
		start = time::now(time::clock::REALTIME),
		term = vt::open(),
		pause_start = void,
		subtitles = subtitles,
		...
	};
	defer vt::close(state.term);
	vt::disablecur(state.term)!;

	for (let i = 0z; i < len(subtitles); i += 1) {
		if (subtitles[i].end > state.length) {
			state.length = subtitles[i].end;
		};
	};

	match (run(state)) {
	case void => void;
	case let err: vt::error =>
		vt::close(state.term);
		fmt::fatal("Error:", vt::strerror(err));
	};
};

fn run(state: state) (void | vt::error) = {
	for (true) {
		match (state.pause_start) {
		case void =>
			let now = time::now(time::clock::REALTIME);
			state.elapsed = time::diff(state.start, now);
		case let inst: time::instant =>
			state.elapsed = time::diff(state.start, inst);
		};
		if (state.elapsed > state.length) break;

		vt::clear(state.term)?;
		let time_text = fmt::asprintf(
			"{:02}:{:02}:{:02}{}\r\n",
			state.elapsed / time::HOUR,
			state.elapsed / time::MINUTE % 60,
			state.elapsed / time::SECOND % 60,
			if (state.pause_start is time::instant) " (PAUSED)" else "",
		);
		defer free(time_text);
		vt::print(state.term, time_text)?;

		let timeout = state.length;

		for (let i = 0z; i < len(state.subtitles); i += 1) {
			let sub = state.subtitles[i];
			if (sub.start > state.elapsed && sub.start < timeout) {
				timeout = sub.start;
			};
			if (sub.end > state.elapsed && sub.end < timeout) {
				timeout = sub.end;
			};
			if (sub.start <= state.elapsed && state.elapsed <= sub.end) {
				vt::print(state.term, sub.text)?;
			};
		};

		timeout -= state.elapsed;
		let next_second = time::SECOND - state.elapsed % time::SECOND;
		if (timeout > next_second) {
			timeout = next_second;
		};
		if (state.pause_start is time::instant) {
			timeout = poll::INDEF;
		};

		let pollfds = [poll::pollfd {
			fd = os::stdin_file,
			events = poll::event::POLLIN | poll::event::POLLHUP,
			...
		}];
		match (poll::poll(pollfds, timeout)) {
		case let x: uint =>
			if (x == 0) continue;
		case let err: poll::error =>
			fmt::errorln("Error polling for user input:", poll::strerror(err))!;
		};

		let ev = match (vt::pollevent(state.term)?) {
		case void =>
			continue;
		case let ev: vt::event =>
			yield ev;
		case io::EOF =>
			break;
		};

		match (ev.value) {
		case let key: rune =>
			switch (key) {
			case 'q' =>
				break;
			case 'c' =>
				if (ev.mods & vt::modflag::CTRL != 0) break;
			case 'j' =>
				fast_backward(&state, time::SECOND * 10);
			case 'l' =>
				fast_forward(&state, time::SECOND * 10);
			case 'k' =>
				pause(&state);
			case ' ' =>
				pause(&state);
			case => void;
			};
		case let key: vt::specialkey =>
			switch (key) {
			case vt::specialkey::LEFT =>
				fast_backward(&state, time::SECOND * 5);
			case vt::specialkey::RIGHT =>
				fast_forward(&state, time::SECOND * 5);
			};
		case vt::functionkey => void;
		};
	};
};

fn fast_forward(state: *state, dur: time::duration) void = {
	state.start = time::add(state.start, -dur);
};

fn fast_backward(state: *state, dur: time::duration) void = {
	let now = time::now(time::clock::REALTIME);
	state.start = time::add(state.start, dur);
	match (state.pause_start) {
	case void =>
		if (time::diff(state.start, now) < 0) {
			state.start = now;
		};
	case let inst: time::instant =>
		if (time::diff(state.start, inst) < 0) {
			state.start = inst;
		};
	};
	
};

fn pause(state: *state) void = {
	let now = time::now(time::clock::REALTIME);
	match (state.pause_start) {
	case void =>
		state.pause_start = now;
	case let inst: time::instant =>
		state.pause_start = void;
		state.start = time::add(state.start, time::diff(inst, now));
	};
};

type parser_state = enum {
	INDEX,
	TIMECODE,
	TEXT,
};

def XML_PROLOG: str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root>\n";

fn parse_srt(file: io::handle) []subtitle = {
	let subtitles: []subtitle = [];
	let current = subtitle {
		text = vt::styled {
			pen = vt::defaultpen,
			...
		},
		...
	};
	let content = strio::dynamic();
	defer io::close(&content)!;
	strio::concat(&content, XML_PROLOG)!;
	let state = parser_state::INDEX;

	for (let nr = 0; true; nr += 1) {
		let line = match (bufio::scanline(file)!) {
		case let line: []u8 =>
			yield match (strings::fromutf8(line)) {
			case let line: str =>
				yield line;
			case utf8::invalid =>
				fmt::fatal("Error: invalid UTF-8");
			};
		case io::EOF =>
			break;
		};
		defer free(line);

		switch (state) {
		case parser_state::INDEX =>
			match (strconv::stou(line)) {
			case let index: uint =>
				current.index = index;
			case =>
				fmt::fatalf("Error on line {}: expected uint, found '{}'\n", nr, line);
			};
			state = parser_state::TIMECODE;
		case parser_state::TIMECODE =>
			match (parse_timecode(line)) {
			case let times: (time::duration, time::duration) =>
				current.start = times.0;
				current.end = times.1;
			case =>
				fmt::fatalf("Error on line {}: invalid timecode syntax\n", nr);
			};
			state = parser_state::TEXT;
		case parser_state::TEXT =>
			if (len(line) > 0) {
				strio::concat(&content, line, "\n")!;
				continue;
			};

			strio::concat(&content, "</root>")!;
			let content_str = strio::string(&content);
			let buf = bufio::fixed(strings::toutf8(content_str), io::mode::READ);
			current.text = match (parse_text(&buf)) {
			case let text: vt::styled =>
				yield text;
			case =>
				let content = strings::trimprefix(content_str, XML_PROLOG);
				let content = strings::trimsuffix(content, "</root>");
				let text = vt::styled {
					pen = vt::defaultpen,
					args = [strings::replace(content, "\n", "\r\n")],
				};
				yield text;
			};

			append(subtitles, current);
			current = subtitle {
				text = vt::styled {
					pen = vt::defaultpen,
					...
				},
				...
			};

			strio::reset(&content);
			strio::concat(&content, XML_PROLOG)!;

			state = parser_state::INDEX;
		};
	};

	return subtitles;
};

fn parse_timecode(timecode: str) ((time::duration, time::duration) | strconv::invalid | strconv::overflow) = {
	let (start, end) = strings::cut(timecode, " --> ");
	let start = parse_time(start)?;
	let end = parse_time(end)?;
	return (start, end);
};

fn parse_time(time: str) (time::duration | strconv::invalid | strconv::overflow) = {
	let dur: time::duration = 0;

	let (time, ms) = strings::cut(time, ",");
	dur += strconv::stoi64(ms)? * time::MILLISECOND;
	let (hrs, time) = strings::cut(time, ":");
	dur += strconv::stoi64(hrs)? * time::HOUR;
	let (mins, secs) = strings::cut(time, ":");
	dur += strconv::stoi64(mins)? * time::MINUTE;
	dur += strconv::stoi64(secs)? * time::SECOND;

	return dur;
};

fn parse_text(in: io::handle) (vt::styled | io::error | xml::error) = {
	let parser = xml::parse(in)?;
	defer xml::parser_free(parser);

	let text = vt::styled {
		pen = vt::defaultpen,
		...
	};
	let pen = vt::defaultpen;
	let bold = 0;
	let italic = 0;
	let underline = 0;
	for (true) {
		let tok = match (xml::scan(parser)?) {
		case let tok: xml::token =>
			yield tok;
		case void =>
			break;
		};

		match (tok) {
		case let start: xml::elementstart =>
			switch (start) {
			case "b" =>
				if (bold == 0) {
					pen.style |= vt::style::BOLD;
				};
				bold += 1;
			case "i" =>
				if (italic == 0) {
					pen.style |= vt::style::ITALIC;
				};
				italic += 1;
			case "u" =>
				if (underline == 0) {
					pen.style |= vt::style::ULINE;
				};
				underline += 1;
			case => void;
			};
		case let end: xml::elementend =>
			switch (end) {
			case "b" =>
				if (bold == 1) {
					pen.style &= ~vt::style::BOLD;
				};
				bold -= 1;
			case "i" =>
				if (italic == 1) {
					pen.style &= ~vt::style::ITALIC;
				};
				italic -= 1;
			case "u" =>
				if (underline == 1) {
					pen.style &= ~vt::style::ULINE;
				};
				underline -= 1;
			case => void;
			};
		case xml::attribute => void;
		case let t: xml::text =>
			let styled = vt::styled {
				pen = pen,
				args = alloc([strings::replace(t, "\n", "\r\n")]),
			};
			append(text.args, styled);
		};
	};
	return text;
};