/
srt_text_parser.js
119 lines (97 loc) · 2.34 KB
/
srt_text_parser.js
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
/*! @license
* Shaka Player
* Copyright 2016 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
goog.provide('shaka.text.SrtTextParser');
goog.require('goog.asserts');
goog.require('shaka.text.TextEngine');
goog.require('shaka.text.VttTextParser');
goog.require('shaka.util.BufferUtils');
goog.require('shaka.util.StringUtils');
/**
* @implements {shaka.extern.TextParser}
* @export
*/
shaka.text.SrtTextParser = class {
/** */
constructor() {
/**
* @type {!shaka.extern.TextParser}
* @private
*/
this.parser_ = new shaka.text.VttTextParser();
}
/**
* @override
* @export
*/
parseInit(data) {
goog.asserts.assert(false, 'SRT does not have init segments');
}
/**
* @override
* @export
*/
setSequenceMode(sequenceMode) {
// Unused.
}
/**
* @override
* @export
*/
parseMedia(data, time) {
const SrtTextParser = shaka.text.SrtTextParser;
const BufferUtils = shaka.util.BufferUtils;
const StringUtils = shaka.util.StringUtils;
// Get the input as a string.
const str = StringUtils.fromUTF8(data);
const vvtText = SrtTextParser.srt2webvtt(str);
const newData = BufferUtils.toUint8(StringUtils.toUTF8(vvtText));
return this.parser_.parseMedia(newData, time);
}
/**
* Convert a SRT format to WebVTT
*
* @param {string} data
* @return {string}
* @export
*/
static srt2webvtt(data) {
const SrtTextParser = shaka.text.SrtTextParser;
let result = 'WEBVTT\n\n';
// Supports no cues
if (data == '') {
return result;
}
// remove dos newlines
let srt = data.replace(/\r+/g, '');
// trim white space start and end
srt = srt.trim();
// get cues
const cuelist = srt.split('\n\n');
for (const cue of cuelist) {
result += SrtTextParser.convertSrtCue_(cue);
}
return result;
}
/**
* Convert a SRT cue into WebVTT cue
*
* @param {string} caption
* @return {string}
* @private
*/
static convertSrtCue_(caption) {
const lines = caption.split(/\n/);
// detect and skip numeric identifier
if (lines[0].match(/\d+/)) {
lines.shift();
}
// convert time codes
lines[0] = lines[0].replace(/,/g, '.');
return lines.join('\n') + '\n\n';
}
};
shaka.text.TextEngine.registerParser(
'text/srt', () => new shaka.text.SrtTextParser());