• Stars
    star
    461
  • Rank 91,395 (Top 2 %)
  • Language
    JavaScript
  • License
    Apache License 2.0
  • Created almost 11 years ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A JavaScript implementation of the WebVTT specification

vtt.js

Build Status npm-version Dependency Status devDependency Status

Implementation of the WebVTT spec in JavaScript. Can be used in NodeJS, on the browser, and many other places. Mozilla uses this implementation for parsing and processing WebVTT files in Firefox/Gecko.

Table of Contents

Spec Compliance

Notes

Our processing model portion of the specification makes use of a custom property, hasBeenReset. It allows us to detect when a VTTCue is dirty, i.e. one of its properties that affects display has changed and so we need to recompute its display state. This allows us to reuse a cue's display state if it has already been computed and nothing has changed to effect its position.

API

WebVTT.Parser

The parser has a simple API:

var parser = new WebVTT.Parser(window, stringDecoder);
parser.onregion = function(region) {};
parser.oncue = function(cue) {};
parser.onflush = function() {};
parser.onparsingerror = function(e) {};
parser.parse(moreData);
parser.parse(moreData);
parser.flush();

The Parser constructor is passed a window object with which it will create new VTTCues and VTTRegions as well as an optional StringDecoder object which it will use to decode the data that the parse() function receives. For ease of use, a StringDecoder is provided via WebVTT.StringDecoder(). If a custom StringDecoder object is passed in it must support the API specified by the #whatwg string encoding spec.

parse(data)

Hands data in some format to the parser for parsing. The passed data format is expected to be decodable by the StringDecoder object that it has. The parser decodes the data and reassembles partial data (streaming), even across line breaks.

var parser = new WebVTT.Parser(window, WebVTT.StringDecoder());
parser.parse("WEBVTT\n\n");
parser.parse("00:32.500 --> 00:33.500 align:start size:50%\n");
parser.parse("<v.loud Mary>That's awesome!");
parser.flush();

flush()

Indicates that no more data is expected and will force the parser to parse any unparsed data that it may have. Will also trigger onflush.

onregion(region)

Callback that is invoked for every region that is correctly parsed. Returns a VTTRegion object.

parser.onregion = function(region) {
  console.log(region);
};

oncue(cue)

Callback that is invoked for every cue that is fully parsed. In case of streaming parsing oncue is delayed until the cue has been completely received. Returns a VTTCue object.

parser.oncue = function(cue) {
  console.log(cue);
};

onflush()

Is invoked in response to flush() and after the content was parsed completely.

parser.onflush = function() {
  console.log("Flushed");
};

onparsingerror(error)

Is invoked when a parsing error has occured. This means that some part of the WebVTT file markup is badly formed. See ParsingError for more information.

parser.onparsingerror = function(e) {
  console.log(e);
};

WebVTT.convertCueToDOMTree(window, cuetext)

Parses the cue text handed to it into a tree of DOM nodes that mirrors the internal WebVTT node structure of the cue text. It uses the window object handed to it to construct new HTMLElements and returns a tree of DOM nodes attached to a top level div.

var div = WebVTT.convertCueToDOMTree(window, cuetext);

WebVTT.processCues(window, cues, overlay)

Converts the cuetext of the cues passed to it to DOM trees—by calling convertCueToDOMTree—and then runs the processing model steps of the WebVTT specification on the divs. The processing model applies the necessary CSS styles to the cue divs to prepare them for display on the web page. During this process the cue divs get added to a block level element (overlay). The overlay should be a part of the live DOM as the algorithm will use the computed styles (only of the divs to do overlap avoidance.

var divs = WebVTT.processCues(window, cues, overlay);

ParsingError

A custom JS error object that is reported through the onparsingerror callback. It has a name, code, and message property, along with all the regular properties that come with a JavaScript error object.

{
  "name": "ParsingError",
  "code": "SomeCode",
  "message": "SomeMessage"
}

There are two error codes that can be reported back currently:

  • 0 BadSignature
  • 1 BadTimeStamp

Note: Exceptions other then ParsingError will be thrown and not reported.

VTTCue

A DOM shim for the VTTCue. See the spec for more information. Our VTTCue shim also includes properties of its abstract base class TextTrackCue.

var cue = new window.VTTCue(0, 1, "I'm a cue.");

Note: Since this polfyill doesn't implement the track specification directly the onenter and onexit events will do nothing and do not exist on this shim.

Extended API

There is also an extended version of this shim that gives a few convenience methods for converting back and forth between JSON and VTTCues. If you'd like to use these methods then us vttcue-extended.js instead of vttcue.js. This isn't normally built into the vtt.js distributable so you will have to build a custom distribution instead of using bower.

toJSON()

Converts a cue to JSON.

var json = cue.toJSON();

VTTCue.fromJSON(json)

Create and initialize a VTTCue from JSON.

var cue = VTTCue.fromJSON(json);

VTTCue.create(options)

Initializes a VTTCue from an options object where the properties in the option objects are the same as the properties on the VTTCue.

var cue = VTTCue.create(options);

VTTRegion

A DOM shim for the VTTRegion. See the spec for more information.

var region = new window.VTTRegion(0, 1, "I'm a region.");
cue.region = region;

Extended API

There is also an extended version of this shim that gives a few convenience methods for converting back and forth between JSON and VTTRegions. If you'd like to use these methods then us vttregion-extended.js instead of vttregion.js. This isn't normally built into the vtt.js distributable so you will have to build a custom distribution instead of using bower.

VTTRegion.fromJSON(json)

Creates and initializes a VTTRegion from JSON.

var region = VTTRegion.fromJSON(json);

VTTRegion.create(options)

Creates a VTTRegion from an options object where the properties on the options object are the same as the properties on the VTTRegion.

var region = VTTRegion.create(options);

Browser

In order to use the vtt.js in a browser, you need to get the built distribution of vtt.js. The distribution contains polyfills for TextDecoder, VTTCue, and VTTRegion since not all browsers currently support them.

Building Yourself

Building a browser-ready version of the library is done using grunt (if you haven't installed grunt globally, you can run it from ./node_modules/.bin/grunt after running npm install):

$ grunt build
$ Running "uglify:dist" (uglify) task
$ File "dist/vtt.min.js" created.

$ Running "concat:dist" (concat) task
$ File "dist/vtt.js" created.

$ Done, without errors.

Your newly built vtt.js now lives in dist/vtt.min.js, or alternatively, dist/vtt.js for an unminified version.

Bower

You can also get the a prebuilt distribution from Bower. Either run the shell command:

$ bower install vtt.js

Or include vtt.js as a dependency in your bower.json file. vtt.js should now live in bower_components/vtt.js/vtt.min.js. There is also an unminified version included with bower at bower_components/vtt.js/vtt.js.

Usage

To use vtt.js you can just include the script on an HTML page like so:

<html>
<head>
  <meta charset="utf-8">
  <title>vtt.js in the browser</title>
  <script src="bower_components/vtt.js/vtt.min.js"></script>
</head>
<body>
  <script>
    var vtt = "WEBVTT\n\nID\n00:00.000 --> 00:02.000\nText",
        parser = new WebVTT.Parser(window, WebVTT.StringDecoder()),
        cues = [],
        regions = [];
    parser.oncue = function(cue) {
      cues.push(cue);
    };
    parser.onregion = function(region) {
      regions.push(region);
    }
    parser.parse(vtt);
    parser.flush();

    var div = WebVTT.convertCueToDOMTree(window, cues[0].text);
    var divs = WebVTT.processCues(window, cues, document.getElementById("overlay"));
  </script>
  <div id="overlay" style="position: relative; width: 300px; height: 150px"></div>
</body>
</html>

Node

You have a couple of options if you'd like to run the library from Node.

vtt.js

vtt.js is on npm. Just do:

npm install vtt.js

Require it and use it:

var vtt = require("vtt.js"),
    WebVTT = vtt.WebVTT,
    VTTCue = vtt.VTTCue,
    VTTRegion = vtt.VTTRegion;

var parser = new WebVTT.Parser(window);
parser.parse();
// etc

var elements = WebVTT.processCues(window, cues, overlay);
var element = WebVTT.convertCueToDOMTree(window, cuetext);

var cue = new VTTCue(0, 1, "I'm a cue.");
var region = new VTTRegion();

See the API for more information on how to use it.

Note: If you use this method you will have to provide your own window object or a shim of one with the necessary functionality for either the parsing or processing portion of the spec. The only shims that are provided to you are VTTCue and VTTRegion which you can attach to your global that is passed into the various functions.

node-vtt

Use node-vtt. Node-vtt runs vtt.js on a PhantomJS page from Node so it has access to a full DOM and CSS layout engine which means you can run any part of the library you want. See the node-vtt repo for more information.

Developing vtt.js

A few things to note:

  • When bumping the version remember to use the grunt release task as this will bump package.json + bower.json and build the dist files for vtt.js in one go.
  • The Grunt Run Task tool is handy for running the library without having to run the whole test suite or set of tests.

Tests

Tests are written and run using Mocha on node.js.

To run all the tests, do the following:

$ npm test

If you want to run individual tests, you can install the Mocha command-line tool globally, and then run tests per-directory:

$ npm install -g mocha
$ cd tests/some/sub/dir
$ mocha --reporter spec --timeout 200000

See the usage docs for further usage info.

Writing Tests

Tests are done by comparing live parsed output to a last-known-good JSON file. The JSON files can be easily generated using vtt.js, so you don't need to write these by hand (see details below about Grunt Run Task).

TestRunner

There's a prebuilt API in place for testing different parts of vtt.js. Simply require the TestRunner module in the lib directory and start writing tests using mocha. See an example of a test file here with its first test's WebVTT file here and its corresponding parsing JSON file and processing JSON file. You can also check out the tests directory for more examples on how to write tests.

jsonEqual(vttFile, jsonRefFile, message, onDone)

First parses the WebVTT file as UTF8 and compares it to the reference JSON file and then parses the WebVTT file as a string and compares it to the reference JSON file.

jsonEqualStreaming(vttFile, jsonRefFile, message, onDone)

Simulates parsing the file while streaming by splitting the WebVTT file into chunks. Will simulate parsing like this n times for a single WebVTT file where n is the length in unicode characters of the file, so use this only on small files or else you will get a timeout failure on your test.

jsonEqualParsing(vttFile, jsonRefFile, message, onDone)

Runs jsonEqual and jsonEqualStreaming in one go.

jsonEqualProcModel(vttFile, jsonRefFile, message, onDone)

Runs the processing model over the VTTCues and VTTRegions that are returned from parsing the WebVTT file.

jsonEqualAll(vttFile, jsonRefFile, message, onDone)

Runs jsonEqualParsing and jsonEqualProcModel. Note that jsonRefFile should contain JSON that is generated from parsing. The processing model test will compare its results to a JSON file located at [vttFile]-proc.json. Therefore, if you have a WebVTT file named basic.vtt the JSON reference file for the processing model tests will be basic-proc.json.

jsonEqualAllNoStream(vttFile, jsonRefFile, message, onDone)

Runs jsonEqual and jsonEqualProcModel use this if you want to do parsing and processing tests, but do not want to simulate streaming because you have too big of a WebVTT file.

Grunt Run Task

You can automatically generate a JSON file for a given .vtt file using the run Grunt task.

To get parsed JSON output from some WebVTT file do:

$ grunt run:my-vtt-file.vtt
$ grunt run:my-vtt-file.vtt > my-json-file.json

To get processed output from the WebVTT file do:

$ grunt run:my-vtt-file.vtt:p
$ grunt run:my-vtt-file.vtt:p > my-json-file.json

By passing the c flag you can automatically copy the output into a JSON file with the same name as the WebVTT file:

$ grunt run:my-vtt-file.vtt:c
$ grunt run:my-vtt-file.vtt:pc

The parsed JSON output now lives in my-vtt-file.json and the processing JSON output lives in my-vtt-file-proc.json.

You can also run it over a directory copying the output of parsing or processing each WebVTT file to a corresponding JSON file like so:

$ grunt run:my-vtt-file-directory
$ grunt run:my-vtt-file-directory:p

This is useful when you've modified how vtt.js works and each JSON file needs a slight change.

The run task utilizes a script called cue2json, but does a few other things for you before each run like building a development build for cue2json to use. It's also a bit easier to type in the CL options for the task. If you want to know more about cue2json you can run it directly like so:

$ ./bin/cue2json.js 
$ Generate JSON test files from a reference VTT file.
$ Usage: node ./bin/cue2json.js [options]
$ 
$ Options:
$   -v, --vtt      Path to VTT file.                                                                                     
$   -d, --dir      Path to test directory. Will recursively find all JSON files with matching VTT files and rewrite them.
$   -c, --copy     Copies the VTT file to a JSON file with the same name.                                                
$   -p, --process  Generate a JSON file of the output returned from the processing model. 

Notes:

  • cue2json utilizes the last development build done. This is why the Grunt run task is good as you don't have to remember to build it yourself. If you don't build it yourself then you could potentially get incorrect results from it.
  • Since cue2json uses the actual parser to generate these JSON files there is the possibility that the generated JSON will contain bugs. Therefore, always check the generated JSON files to check that the parser actually parsed according to spec.

More Repositories

1

pdf.js

PDF Reader in JavaScript
JavaScript
43,965
star
2

DeepSpeech

DeepSpeech is an open source embedded (offline, on-device) speech-to-text engine which can run in real time on devices ranging from a Raspberry Pi 4 to high power GPU servers.
C++
24,221
star
3

send

Simple, private file sharing from the makers of Firefox
FreeMarker
13,225
star
4

sops

Simple and flexible tool for managing secrets
Go
12,778
star
5

BrowserQuest

A HTML5/JavaScript multiplayer game experiment
JavaScript
9,167
star
6

nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
JavaScript
8,415
star
7

geckodriver

WebDriver for Firefox
6,911
star
8

TTS

🤖 💬 Deep learning for Text to Speech (Discussion forum: https://discourse.mozilla.org/c/tts)
Jupyter Notebook
6,749
star
9

readability

A standalone version of the readability lib
JavaScript
6,470
star
10

sccache

Sccache is a ccache-like tool. It is used as a compiler wrapper and avoids compilation when possible. Sccache has the capability to utilize caching in remote storage environments, including various cloud storage options, or alternatively, in local storage.
Rust
5,334
star
11

mozjpeg

Improved JPEG encoder.
C
5,216
star
12

Fira

Mozilla's new typeface, used in Firefox OS
CSS
4,920
star
13

rhino

Rhino is an open-source implementation of JavaScript written entirely in Java
JavaScript
3,956
star
14

shumway

Shumway is a Flash VM and runtime written in JavaScript
TypeScript
3,692
star
15

source-map

Consume and generate source maps.
JavaScript
3,471
star
16

gecko-dev

Read-only Git mirror of the Mercurial gecko repositories at https://hg.mozilla.org. How to contribute: https://firefox-source-docs.mozilla.org/contributing/contribution_quickref.html
2,897
star
17

multi-account-containers

Firefox Multi-Account Containers lets you keep parts of your online life separated into color-coded tabs that preserve your privacy. Cookies are separated by container, allowing you to use the web with multiple identities or accounts simultaneously.
JavaScript
2,594
star
18

bleach

Bleach is an allowed-list-based HTML sanitizing library that escapes or strips markup and attributes
Python
2,590
star
19

web-ext

A command line tool to help build, run, and test web extensions
JavaScript
2,557
star
20

node-convict

Featureful configuration management library for Node.js
JavaScript
2,304
star
21

MozDef

DEPRECATED - MozDef: Mozilla Enterprise Defense Platform
Python
2,173
star
22

cbindgen

A project for generating C bindings from Rust code
Rust
2,157
star
23

popcorn-js

The HTML5 Media Framework. (Unmaintained. See https://github.com/menismu/popcorn-js for activity)
JavaScript
2,148
star
24

webextension-polyfill

A lightweight polyfill library for Promise-based WebExtension APIs in Chrome
JavaScript
2,088
star
25

fathom

A framework for extracting meaning from web pages
JavaScript
1,972
star
26

cipherscan

A very simple way to find out which SSL ciphersuites are supported by a target.
Python
1,912
star
27

hawk

HTTP Holder-Of-Key Authentication Scheme
JavaScript
1,903
star
28

persona

Persona is a secure, distributed, and easy to use identification system.
JavaScript
1,828
star
29

http-observatory

Mozilla HTTP Observatory
Python
1,784
star
30

uniffi-rs

a multi-language bindings generator for rust
Rust
1,783
star
31

neqo

Neqo, an implementation of QUIC in Rust
Rust
1,759
star
32

mentat

UNMAINTAINED A persistent, relational store inspired by Datomic and DataScript.
Rust
1,652
star
33

task.js

Beautiful concurrency for JavaScript
JavaScript
1,635
star
34

hubs

Duck-themed multi-user virtual spaces in WebVR. Built with A-Frame.
JavaScript
1,561
star
35

thimble.mozilla.org

UPDATE: This project is no longer maintained. Please check out Glitch.com instead.
JavaScript
1,423
star
36

fx-private-relay

Keep your email safe from hackers and trackers. Make an email alias with 1 click, and keep your address to yourself.
Python
1,415
star
37

pontoon

Mozilla's Localization Platform
Python
1,396
star
38

kitsune

Platform for Mozilla Support
Python
1,247
star
39

mig

Distributed & real time digital forensics at the speed of the cloud
Go
1,195
star
40

OpenWPM

A web privacy measurement framework
Python
1,150
star
41

bedrock

Making mozilla.org awesome, one pebble at a time
HTML
1,149
star
42

server-side-tls

Server side TLS Tools
HTML
1,114
star
43

grcov

Rust tool to collect and aggregate code coverage data for multiple source files
Rust
1,106
star
44

policy-templates

Policy Templates for Firefox
1,105
star
45

rust-android-gradle

Kotlin
989
star
46

pdfjs-dist

Generic build of PDF.js library.
JavaScript
952
star
47

contain-facebook

Facebook Container isolates your Facebook activity from the rest of your web activity in order to prevent Facebook from tracking you outside of the Facebook website via third party cookies.
JavaScript
945
star
48

narcissus

INACTIVE - http://mzl.la/ghe-archive - The Narcissus meta-circular JavaScript interpreter
JavaScript
901
star
49

openbadges-backpack

Mozilla Open Badges Backpack
JavaScript
861
star
50

addons-server

🕶 addons.mozilla.org Django app and API 🎉
Python
833
star
51

awsbox

INACTIVE - http://mzl.la/ghe-archive - A featherweight PaaS on top of Amazon EC2 for deploying node apps
JavaScript
811
star
52

dxr

DEPRECATED - Powerful search for large codebases
Python
804
star
53

ssh_scan

DEPRECATED - A prototype SSH configuration and policy scanner (Blog: https://mozilla.github.io/ssh_scan/)
Ruby
796
star
54

chromeless

DEPRECATED - Build desktop applications with web technologies.
JavaScript
761
star
55

node-client-sessions

secure sessions stored in cookies
JavaScript
745
star
56

playdoh

PROJECT DEPRECATED (WAS: "Mozilla's Web application base template. Half Django, half awesomeness, half not good at math.")
Python
714
star
57

DeepSpeech-examples

Examples of how to use or integrate DeepSpeech
Python
682
star
58

blurts-server

Firefox Monitor arms you with tools to keep your personal information safe. Find out what hackers already know about you and learn how to stay a step ahead of them.
Fluent
679
star
59

tofino

Project Tofino is a browser interaction experiment.
HTML
655
star
60

addon-sdk

DEPRECATED - The Add-on SDK repository.
641
star
61

MozStumbler

Android Stumbler for Mozilla
Java
614
star
62

application-services

Firefox Application Services
Rust
598
star
63

standards-positions

Python
595
star
64

lightbeam

Orignal unmaintained version of the Lightbeam extension. See lightbeam-we for the new one which works in modern versions of Firefox.
JavaScript
587
star
65

moz-sql-parser

DEPRECATED - Let's make a SQL parser so we can provide a familiar interface to non-sql datastores!
Python
574
star
66

firefox-translations

Firefox Translations is a webextension that enables client side translations for web browsers.
JavaScript
571
star
67

spidernode

Node.js on top of SpiderMonkey
JavaScript
560
star
68

inclusion

Our repository for Diversity, Equity and Inclusion work at Mozilla
557
star
69

positron

a experimental, Electron-compatible runtime on top of Gecko
551
star
70

fxa

Monorepo for Firefox Accounts
JavaScript
547
star
71

cargo-vet

supply-chain security for Rust
Rust
547
star
72

ichnaea

Mozilla Ichnaea
Python
539
star
73

addons-frontend

Front-end to complement mozilla/addons-server
JavaScript
525
star
74

tls-observatory

An observatory for TLS configurations, X509 certificates, and more.
Go
518
star
75

neo

INACTIVE - http://mzl.la/ghe-archive - DEPRECATED: See https://neutrino.js.org for alternative
JavaScript
503
star
76

notes

DEPRECATED - A notepad for Firefox
HTML
493
star
77

nixpkgs-mozilla

Mozilla overlay for Nixpkgs.
Nix
490
star
78

bugbug

Platform for Machine Learning projects on Software Engineering
Python
487
star
79

django-csp

Content Security Policy for Django.
Python
486
star
80

skywriter

Mozilla Skywriter
JavaScript
481
star
81

Spoke

Easily create custom 3D environments
JavaScript
480
star
82

zamboni

Backend for the Firefox Marketplace
Python
475
star
83

libdweb

Extension containing an experimental libdweb APIs
JavaScript
441
star
84

FirefoxColor

Theming demo for Firefox Quantum and beyond
JavaScript
437
star
85

pointer.js

INACTIVE - http://mzl.la/ghe-archive - INACTIVE - http://mzl.la/ghe-archive - Normalizes mouse/touch events into 'pointer' events.
JavaScript
435
star
86

mozilla-django-oidc

A django OpenID Connect library
Python
418
star
87

cubeb

Cross platform audio library
C++
411
star
88

agithub

Agnostic Github client API -- An EDSL for connecting to REST servers
Python
410
star
89

fxa-auth-server

DEPRECATED - Migrated to https://github.com/mozilla/fxa
JavaScript
401
star
90

zilla-slab

Mozilla's Zilla Slab Type Family
Shell
391
star
91

r2d2b2g

Firefox OS Simulator is a test environment for Firefox OS. Use it to test your apps in a Firefox OS-like environment that looks and feels like a mobile phone.
JavaScript
391
star
92

masche

Deprecated - MIG Memory Forensic library
Go
387
star
93

qbrt

CLI to a Gecko desktop app runtime
JavaScript
386
star
94

mp4parse-rust

Parser for ISO Base Media Format aka video/mp4 written in Rust.
Rust
380
star
95

valence

INACTIVE - http://mzl.la/ghe-archive - Firefox Developer Tools protocol adapters (Unmaintained)
JavaScript
377
star
96

OpenDesign

Mozilla Open Design aims to bring open source principles to Creative Design. Find us on Matrix: chat.mozilla.org/#/room/#opendesign:mozilla.org
367
star
97

reflex

Functional reactive UI library
JavaScript
364
star
98

mortar

INACTIVE - http://mzl.la/ghe-archive - A collection of web app templates
364
star
99

minion

Minion
354
star
100

makedrive

[RETIRED] Webmaker Filesystem
JavaScript
352
star