4 [comment]: # ([![Build Status](https://travis-ci.org/mozilla/vtt.js.svg?branch=master)](https://travis-ci.org/mozilla/vtt.js) [![npm-version](http://img.shields.io/npm/v/vtt.js.svg)](https://www.npmjs.org/package/vtt.js) [![Dependency Status](https://david-dm.org/mozilla/vtt.js.svg?theme=shields.io)](https://david-dm.org/mozilla/vtt.js) [![devDependency Status](https://david-dm.org/mozilla/vtt.js/dev-status.svg?theme=shields.io)](https://david-dm.org/mozilla/vtt.js#info=devDependencies))
6 Implementation of the [WebVTT](https://developer.mozilla.org/en-US/docs/HTML/WebVTT) spec in JavaScript. Can be used
7 in NodeJS, on the browser, and many other places. Mozilla uses this implementation for parsing and processing WebVTT
8 files in Firefox/Gecko.
10 This is a fork of vttjs with some changes that are used by Video.js.
14 - [Spec Compliance](#spec-compliance)
16 - [WebVTT.Parser](#webvttparser)
17 - [parse(data)](#parsedata)
19 - [onregion(region)](#onregionregion)
20 - [oncue(cue)](#oncuecue)
21 - [onflush()](#onflush)
22 - [onparsingerror(error)](#onparsingerrorerror)
23 - [ontimestampmap(timestampmap)](#ontimestampmaptimestampmap)
24 - [WebVTT.convertCueToDOMTree(window, cuetext)](#webvttconvertcuetodomtreewindow-cuetext)
25 - [WebVTT.processCues(window, cues, overlay)](#webvttprocesscueswindow-cues-overlay)
26 - [ParsingError](#parsingerror)
28 - [Extended API](#extended-api)
30 - [VTTCue.fromJSON(json)](#vttcuefromjsonjson)
31 - [VTTCue.create(options)](#vttcuecreateoptions)
32 - [VTTRegion](#vttregion)
33 - [Extended API](#extended-api-1)
34 - [VTTRegion.fromJSON(json)](#vttregionfromjsonjson)
35 - [VTTRegion.create(options)](#vttregioncreateoptions)
37 - [Building Yourself](#building-yourself)
42 - [node-vtt](#node-vtt)
43 - [Developing vtt.js](#developing-vttjs)
45 - [Writing Tests](#writing-tests)
46 - [Grunt Run Task](#grunt-run-task)
51 - [Parsing](http://dev.w3.org/html5/webvtt/#webvtt-file-format-parsing) (Completed)
52 - [File](http://dev.w3.org/html5/webvtt/#webvtt-file-parsing) (Completed)
53 - [Region](http://dev.w3.org/html5/webvtt/#webvtt-region-settings-parsing) (Completed)
54 - [Cue Timings and Settings](http://dev.w3.org/html5/webvtt/#webvtt-cue-timings-and-settings-parsing) (Completed)
55 - [WebVTT Cue Text](http://dev.w3.org/html5/webvtt/#dfn-webvtt-cue-text-parsing-rules) (Completed)
56 - [Cue DOM Construction](http://dev.w3.org/html5/webvtt/#webvtt-cue-text-dom-construction-rules) (Completed)
57 - [Rendering](http://dev.w3.org/html5/webvtt/#rendering) (In Progress)
58 - [Processing Model](http://dev.w3.org/html5/webvtt/#processing-model) (In Progress) ***No VTTRegion or vertical text support***
59 - [Apply WebVTT Cue Settings](http://dev.w3.org/html5/webvtt/#dfn-apply-webvtt-cue-settings) (In Progress)
60 - Steps 1 - 11 (Completed)
61 - Step 12 (In progress)
62 - [Applying CSS Properties](http://dev.w3.org/html5/webvtt/#applying-css-properties-to-webvtt-node-objects) (Completed)
63 - [CSS Extensions](http://dev.w3.org/html5/webvtt/#css-extensions) **(Won't Implement)**
64 - [WebVTT API Shim](http://dev.w3.org/html5/webvtt/#webvtt-api-for-browsers) (Completed)
65 - [VTTCue](http://dev.w3.org/html5/webvtt/#vttcue-interface) (Completed) ***Shims the TextTrackCue interface as well***
66 - [VTTRegion](http://dev.w3.org/html5/webvtt/#vttregion-interface) (Completed)
70 Our processing model portion of the specification makes use of a custom property, `hasBeenReset`. It allows us to detect
71 when a VTTCue is dirty, i.e. one of its properties that affects display has changed and so we need to recompute its display
72 state. This allows us to reuse a cue's display state if it has already been computed and nothing has changed to effect its
80 The parser has a simple API:
83 var parser = new WebVTT.Parser(window, stringDecoder);
84 parser.onregion = function(region) {};
85 parser.oncue = function(cue) {};
86 parser.onflush = function() {};
87 parser.onparsingerror = function(e) {};
88 parser.parse(moreData);
89 parser.parse(moreData);
93 The Parser constructor is passed a window object with which it will create new
94 VTTCues and VTTRegions as well as an optional StringDecoder object which
95 it will use to decode the data that the `parse()` function receives. For ease of
96 use, a StringDecoder is provided via `WebVTT.StringDecoder()`. If a custom
97 StringDecoder object is passed in it must support the API specified by the
98 [#whatwg string encoding](http://encoding.spec.whatwg.org/#api) spec.
102 Hands data in some format to the parser for parsing. The passed data format
103 is expected to be decodable by the StringDecoder object that it has. The parser
104 decodes the data and reassembles partial data (streaming), even across line breaks.
107 var parser = new WebVTT.Parser(window, WebVTT.StringDecoder());
108 parser.parse("WEBVTT\n\n");
109 parser.parse("00:32.500 --> 00:33.500 align:start size:50%\n");
110 parser.parse("<v.loud Mary>That's awesome!");
116 Indicates that no more data is expected and will force the parser to parse any
117 unparsed data that it may have. Will also trigger [onflush](#onflush).
119 ####onregion(region)####
121 Callback that is invoked for every region that is correctly parsed. Returns a [VTTRegion](#http://dev.w3.org/html5/webvtt/#dfn-vttregion)
125 parser.onregion = function(region) {
132 Callback that is invoked for every cue that is fully parsed. In case of streaming parsing oncue is
133 delayed until the cue has been completely received. Returns a [VTTCue](#http://dev.w3.org/html5/webvtt/#vttcue-interface) object.
136 parser.oncue = function(cue) {
143 Is invoked in response to `flush()` and after the content was parsed completely.
146 parser.onflush = function() {
147 console.log("Flushed");
151 ####onparsingerror(error)####
153 Is invoked when a parsing error has occured. This means that some part of the
154 WebVTT file markup is badly formed. See [ParsingError](#parsingerror) for more
158 parser.onparsingerror = function(e) {
163 ####ontimestampmap(timestampmap)####
165 Is invoked when an `X-TIMESTAMP-MAP` metadata header ([defined here](https://tools.ietf.org/html/draft-pantos-http-live-streaming-20#section-3.5)) is parsed. This header maps WebVTT cue timestamps to MPEG-2 (PES) timestamps in other Renditions of the Variant Stream.
168 parser.ontimestampmap = function(timestamp) {
169 console.log('LOCAL:', timestamp.LOCAL);
170 console.log('MPEGTS:', timestamp.MPEGTS);
174 ####WebVTT.convertCueToDOMTree(window, cuetext)####
176 Parses the cue text handed to it into a tree of DOM nodes that mirrors the internal WebVTT node structure of
177 the cue text. It uses the window object handed to it to construct new HTMLElements and returns a tree of DOM
178 nodes attached to a top level div.
181 var div = WebVTT.convertCueToDOMTree(window, cuetext);
184 ####WebVTT.processCues(window, cues, overlay)####
186 Converts the cuetext of the cues passed to it to DOM trees—by calling convertCueToDOMTree—and
187 then runs the processing model steps of the WebVTT specification on the divs. The processing model applies the necessary
188 CSS styles to the cue divs to prepare them for display on the web page. During this process the cue divs get added
189 to a block level element (overlay). The overlay should be a part of the live DOM as the algorithm will use the
190 computed styles (only of the divs to do overlap avoidance.
193 var divs = WebVTT.processCues(window, cues, overlay);
198 A custom JS error object that is reported through the
199 [onparsingerror](#onparsingerror) callback. It has a `name`, `code`, and
200 `message` property, along with all the regular properties that come with a
201 JavaScript error object.
205 "name": "ParsingError",
207 "message": "SomeMessage"
211 There are two error codes that can be reported back currently:
216 **Note:** Exceptions other then `ParsingError` will be thrown and not reported.
220 A DOM shim for the VTTCue. See the [spec](http://dev.w3.org/html5/webvtt/#vttcue-interface)
221 for more information. Our VTTCue shim also includes properties of its abstract base class
222 [TextTrackCue](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#texttrackcue).
225 var cue = new window.VTTCue(0, 1, "I'm a cue.");
228 **Note:** Since this polfyill doesn't implement the track specification directly the `onenter`
229 and `onexit` events will do nothing and do not exist on this shim.
233 There is also an extended version of this shim that gives a few convenience methods
234 for converting back and forth between JSON and VTTCues. If you'd like to use these
235 methods then us `vttcue-extended.js` instead of `vttcue.js`. This isn't normally
236 built into the `vtt.js` distributable so you will have to build a custom distribution
237 instead of using bower.
241 Converts a cue to JSON.
244 var json = cue.toJSON();
247 ####VTTCue.fromJSON(json)####
249 Create and initialize a VTTCue from JSON.
252 var cue = VTTCue.fromJSON(json);
255 ####VTTCue.create(options)####
257 Initializes a VTTCue from an options object where the properties in the option
258 objects are the same as the properties on the VTTCue.
261 var cue = VTTCue.create(options);
266 A DOM shim for the VTTRegion. See the [spec](http://dev.w3.org/html5/webvtt/#vttregion-interface)
267 for more information.
270 var region = new window.VTTRegion(0, 1, "I'm a region.");
276 There is also an extended version of this shim that gives a few convenience methods
277 for converting back and forth between JSON and VTTRegions. If you'd like to use these
278 methods then us `vttregion-extended.js` instead of `vttregion.js`. This isn't normally
279 built into the `vtt.js` distributable so you will have to build a custom distribution
280 instead of using bower.
282 ####VTTRegion.fromJSON(json)####
284 Creates and initializes a VTTRegion from JSON.
287 var region = VTTRegion.fromJSON(json);
290 ####VTTRegion.create(options)####
292 Creates a VTTRegion from an options object where the properties on the options
293 object are the same as the properties on the VTTRegion.
296 var region = VTTRegion.create(options);
302 In order to use the `vtt.js` in a browser, you need to get the built distribution of vtt.js. The distribution
303 contains polyfills for [TextDecoder](http://encoding.spec.whatwg.org/), [VTTCue](http://dev.w3.org/html5/webvtt/#vttcue-interface),
304 and [VTTRegion](http://dev.w3.org/html5/webvtt/#vttregion-interface) since not all browsers currently
307 ###Building Yourself###
309 Building a browser-ready version of the library is done using `grunt` (if you haven't installed
310 `grunt` globally, you can run it from `./node_modules/.bin/grunt` after running `npm install`):
314 $ Running "uglify:dist" (uglify) task
315 $ File "dist/vtt.min.js" created.
317 $ Running "concat:dist" (concat) task
318 $ File "dist/vtt.js" created.
320 $ Done, without errors.
323 Your newly built `vtt.js` now lives in `dist/vtt.min.js`, or alternatively, `dist/vtt.js` for an
328 You can also get the a prebuilt distribution from [Bower](http://bower.io/). Either run the shell
332 $ bower install vtt.js
335 Or include `vtt.js` as a dependency in your `bower.json` file. `vtt.js` should now
336 live in `bower_components/vtt.js/vtt.min.js`. There is also an unminified
337 version included with bower at `bower_components/vtt.js/vtt.js`.
341 To use `vtt.js` you can just include the script on an HTML page like so:
346 <meta charset="utf-8">
347 <title>vtt.js in the browser</title>
348 <script src="bower_components/vtt.js/vtt.min.js"></script>
352 var vtt = "WEBVTT\n\nID\n00:00.000 --> 00:02.000\nText",
353 parser = new WebVTT.Parser(window, WebVTT.StringDecoder()),
356 parser.oncue = function(cue) {
359 parser.onregion = function(region) {
360 regions.push(region);
365 var div = WebVTT.convertCueToDOMTree(window, cues[0].text);
366 var divs = WebVTT.processCues(window, cues, document.getElementById("overlay"));
368 <div id="overlay" style="position: relative; width: 300px; height: 150px"></div>
376 You have a couple of options if you'd like to run the library from Node.
380 `vtt.js` is on npm. Just do:
386 Require it and use it:
389 var vtt = require("vtt.js"),
392 VTTRegion = vtt.VTTRegion;
394 var parser = new WebVTT.Parser(window);
398 var elements = WebVTT.processCues(window, cues, overlay);
399 var element = WebVTT.convertCueToDOMTree(window, cuetext);
401 var cue = new VTTCue(0, 1, "I'm a cue.");
402 var region = new VTTRegion();
405 See the [API](#api) for more information on how to use it.
407 **Note:** If you use this method you will have to provide your own window object
408 or a shim of one with the necessary functionality for either the parsing or processing
409 portion of the spec. The only shims that are provided to you are `VTTCue` and `VTTRegion`
410 which you can attach to your global that is passed into the various functions.
414 Use [node-vtt](https://github.com/mozilla/node-vtt). Node-vtt runs `vtt.js` on a PhantomJS page
415 from Node so it has access to a full DOM and CSS layout engine which means you can run any part
416 of the library you want. See the [node-vtt](https://github.com/mozilla/node-vtt) repo for more
422 A few things to note:
424 * When bumping the version remember to use the `grunt release` task as this will
425 bump `package.json` + `bower.json` and build the `dist` files for `vtt.js` in one
427 * The [Grunt Run Task](#grunt-run-task) tool is handy for running the library without having
428 to run the whole test suite or set of tests.
432 Tests are written and run using [Mocha](http://visionmedia.github.io/mocha/) on node.js.
434 To run all the tests, do the following:
440 If you want to run individual tests, you can install the [Mocha](http://visionmedia.github.io/mocha/) command-line
441 tool globally, and then run tests per-directory:
444 $ npm install -g mocha
445 $ cd tests/some/sub/dir
446 $ mocha --reporter spec --timeout 200000
449 See the [usage docs](http://visionmedia.github.io/mocha/#usage) for further usage info.
453 Tests are done by comparing live parsed output to a last-known-good JSON file. The JSON files
454 can be easily generated using `vtt.js`, so you don't need to write these by hand
455 (see details below about [Grunt Run Task](#grunt-run-task)).
459 There's a prebuilt API in place for testing different parts of `vtt.js`. Simply
460 require the [TestRunner](https://github.com/mozilla/vtt.js/blob/master/tests/test-runner.js)
461 module in the `lib` directory and start writing tests using `mocha`. See an example of a test file
462 [here](https://github.com/mozilla/vtt.js/blob/master/tests/cue-settings/align/test.js)
463 with its first test's WebVTT file [here](https://github.com/mozilla/vtt.js/blob/master/tests/cue-settings/align/bad-align.vtt)
464 and its corresponding [parsing JSON file](https://github.com/mozilla/vtt.js/blob/master/tests/cue-settings/align/bad-align.json)
465 and [processing JSON file](https://github.com/mozilla/vtt.js/blob/master/tests/cue-settings/align/bad-align-proc.json).
466 You can also check out the [tests](https://github.com/mozilla/vtt.js/tree/master/tests)
467 directory for more examples on how to write tests.
469 ####jsonEqual(vttFile, jsonRefFile, message, onDone)####
471 First parses the WebVTT file as UTF8 and compares it to the reference JSON file
472 and then parses the WebVTT file as a string and compares it to the reference JSON
475 ####jsonEqualStreaming(vttFile, jsonRefFile, message, onDone)####
477 Simulates parsing the file while streaming by splitting the WebVTT file into
478 chunks. Will simulate parsing like this `n` times for a single WebVTT file where
479 `n` is the length in unicode characters of the file, so use this only on small
480 files or else you will get a timeout failure on your test.
482 ####jsonEqualParsing(vttFile, jsonRefFile, message, onDone)####
484 Runs `jsonEqual` and `jsonEqualStreaming` in one go.
486 ####jsonEqualProcModel(vttFile, jsonRefFile, message, onDone)####
488 Runs the processing model over the `VTTCues` and `VTTRegions` that are returned
489 from parsing the WebVTT file.
491 ####jsonEqualAll(vttFile, jsonRefFile, message, onDone)####
493 Runs `jsonEqualParsing` and `jsonEqualProcModel`. Note that `jsonRefFile` should
494 contain JSON that is generated from parsing. The processing model test will compare
495 its results to a JSON file located at `[vttFile]-proc.json`. Therefore, if you
496 have a WebVTT file named `basic.vtt` the JSON reference file for the processing
497 model tests will be `basic-proc.json`.
499 ####jsonEqualAllNoStream(vttFile, jsonRefFile, message, onDone)####
501 Runs `jsonEqual` and `jsonEqualProcModel` use this if you want to do parsing
502 and processing tests, but do not want to simulate streaming because you
503 have too big of a WebVTT file.
507 You can automatically generate a JSON file for a given `.vtt` file using the
510 To get parsed JSON output from some WebVTT file do:
513 $ grunt run:my-vtt-file.vtt
514 $ grunt run:my-vtt-file.vtt > my-json-file.json
517 To get processed output from the WebVTT file do:
520 $ grunt run:my-vtt-file.vtt:p
521 $ grunt run:my-vtt-file.vtt:p > my-json-file.json
524 By passing the `c` flag you can automatically copy the output into a JSON file
525 with the same name as the WebVTT file:
528 $ grunt run:my-vtt-file.vtt:c
529 $ grunt run:my-vtt-file.vtt:pc
532 The parsed JSON output now lives in `my-vtt-file.json` and the processing JSON
533 output lives in `my-vtt-file-proc.json`.
535 You can also run it over a directory copying the output of parsing or
536 processing each WebVTT file to a corresponding JSON file like so:
539 $ grunt run:my-vtt-file-directory
540 $ grunt run:my-vtt-file-directory:p
543 This is useful when you've modified how `vtt.js` works and each JSON file needs
546 The `run` task utilizes a script called `cue2json`, but
547 does a few other things for you before each run like building a development
548 build for `cue2json` to use. It's also a bit easier to type in the CL options
549 for the task. If you want to know more about `cue2json` you can run it directly
554 $ Generate JSON test files from a reference VTT file.
555 $ Usage: node ./bin/cue2json.js [options]
558 $ -v, --vtt Path to VTT file.
559 $ -d, --dir Path to test directory. Will recursively find all JSON files with matching VTT files and rewrite them.
560 $ -c, --copy Copies the VTT file to a JSON file with the same name.
561 $ -p, --process Generate a JSON file of the output returned from the processing model.
566 * `cue2json` utilizes the last development build done. This is why the Grunt `run` task is
567 good as you don't have to remember to build it yourself. If you don't build it yourself then you could
568 potentially get incorrect results from it.
569 * Since `cue2json` uses the actual parser to generate these JSON files there is the possibility that
570 the generated JSON will contain bugs. Therefore, always check the generated JSON files to check that the
571 parser actually parsed according to spec.