-
Notifications
You must be signed in to change notification settings - Fork 0
/
srt2vtt.php
105 lines (89 loc) · 3.31 KB
/
srt2vtt.php
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
<?php
/**
* User: pculka
* Date: 27.4.2014
* Time: 19:14
*/
// default configuration
$srt2vttConf = array(
"appendCopyrightInfo" => false,
"autoConvertEncoding" => true, // not yet implemented
"sourceEncodingList" => array('ISO-8859-1', 'Windows-1252', 'ASCII', 'UTF-8' ), // not yet implemented
"debug" => true,
);
if (file_exists("srt2vtt.conf.php"))
require_once("srt2vtt.conf.php");
try {
// access the get, check for valid filename
$file = realpath(html_entity_decode($_GET['i']));
$fn = filter_var($file, FILTER_VALIDATE_REGEXP, array( "options" => array( "regexp" => '%^[^"<>|:*?]+\.srt$%m') ) );
if ($fn === false) {
throw new Exception(_("Specified subtitle source is invalid"));
}
if (file_exists($fn)) {
// read the file
$subtitleLines = file($fn);
if (empty($subtitleLines)) throw new Exception(_("Subtitle file empty"));
// prepare the result
$result = "WEBVTT\n\n\n";
define('SRT_STATE_SUBNUMBER', 0);
define('SRT_STATE_TIME', 1);
define('SRT_STATE_TEXT', 2);
define('SRT_STATE_BLANK', 3);
$subs = array();
$state = SRT_STATE_SUBNUMBER;
$subNum = 0;
$subText = '';
$subTime = '';
foreach($subtitleLines as $line) {
switch($state) {
case SRT_STATE_SUBNUMBER:
$subNum = trim($line);
$state = SRT_STATE_TIME;
break;
case SRT_STATE_TIME:
$subTime = trim($line);
$state = SRT_STATE_TEXT;
break;
case SRT_STATE_TEXT:
if (trim($line) == '') {
$sub = new stdClass;
$sub->number = $subNum;
list($sub->startTime, $sub->stopTime) = explode(' --> ', $subTime);
$sub->text = $subText;
$subText = '';
$state = SRT_STATE_SUBNUMBER;
$subs[] = $sub;
} else {
$subText .= trim($line)."\n";
}
break;
}
}
foreach ($subs as $sub) {
$result .= $sub->number."\n";
$result .= str_replace(',', '.', $sub->startTime)." --> ".str_replace(',', '.', $sub->stopTime)."\n";
$result .= $sub->text."\n\n";
}
header('Content-type: text/plain; charset=utf-8');
echo $result;
} else {
throw new Exception(_("File not found"));
}
} catch (Exception $e) {
header('Content-type: text/plain; charset=utf-8');
$result = "WEBVTT\n\n\n";
$result .= "1\n";
$result .= "00:00:00.000 --> 00:10:00.000\n";
$result .= $e->getMessage()."\n\n\n";
$subNum = 2;
echo $result;
} finally {
// append information if configured
// #todo: get highest sub number, increment, add specified amount of wait time and display the disclaimer (if specified);
if ($srt2vttConf['appendCopyrightInfo']) {
echo (int)$subNum."\n";
echo "00:00:00.001 --> 00:10:00.000\n";
echo "compiled by srt2vtt by pculka";
}
}