This repository has been archived by the owner on Jan 31, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
jquery.webvtt.js
executable file
·115 lines (90 loc) · 2.74 KB
/
jquery.webvtt.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
/**
* jQuery WebVTT Plugin 0.0.1
* http://github.com/brainbits/jquery-webvtt
* Requires jQuery 1.4.2
*
* Copyright 2011 Brainbits GmbH.
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*/
(function ($) {
"use strict";
/**
* Some regular expressions for parsing
*/
var TIMESTAMP = /^(?:(\d{2,}):)?(\d{2}):(\d{2})[,.](\d{3})$/,
CUE = /^(?:(.*)(?:\r\n|\n))?([\d:,.]+) --> ([\d:,.]+)(?:\r\n|\n)(.*)$/,
WEBVTT = /^\uFEFF?WEBVTT(?: .*)?/;
/**
* Converts a WebVTT timestamp into a floating number
*/
function timestampToNumber(time) {
if (!TIMESTAMP.test(time)) {
throw "'" + time + "' doesn't match to the WebVTT timestamp pattern.";
}
var matches = TIMESTAMP.exec(time),
number = matches[4] / 1000;
number += parseInt(matches[3], 10);
if (matches[2]) {
number += matches[2] * 60;
}
if (matches[1]) {
number += matches[1] * 60 * 60;
}
return number;
}
/**
* Parse the WebVTT source into a javascript array
*/
function parse(text) {
var lines = $.trim(text).split(/(?:(?:\r\n|\n){2,})/),
cues = [],
matches = [],
i = 0;
do {
// If there is the optional WebVTT Header, omit first two lines
if (i === 0 && WEBVTT.test(lines[i])) {
i += 1;
}
if (!CUE.test(lines[i])) {
throw "An error while parsing a WebVTT cue string on cue " + (i + 1) + ".";
}
matches = CUE.exec(lines[i]);
cues.push({
marker: matches[1],
from: timestampToNumber(matches[2]),
to: timestampToNumber(matches[3]),
payload: $('<p/>').text(matches[4])
});
i += 1;
} while (i < lines.length);
return cues;
}
/**
* The global jquery function
*/
$.webVtt = function (source, time) {
var element = $(source),
matches = $([]);
if (!element.data('webvtt')) {
element.data('webvtt', parse(element.html()));
}
if ($.type(time) !== "number") {
time = timestampToNumber(time);
}
$.each(element.data('webvtt'), function (index, cue) {
if (cue.from <= time && cue.to > time) {
matches = matches.add(cue.payload);
}
});
return matches;
};
/**
* Extends the jquery functions for concatenation
*/
$.fn.extend({
webVtt: function (time) {
return $.webVtt(this[0], time);
}
});
}(jQuery));