166 Commits
Author SHA1 Message Date
Arnavion c6053f59a1 Nested rotations. 2014-08-17 22:09:16 -07:00
Arnavion 73755e0c8a libjass.parser.parse_assScriptProperty() now properly handles a parent that's not a script section. 2014-08-17 03:59:41 -07:00
Arnavion f951475103 Replaced custom map-like interfaces with actual Map. 2014-08-17 03:59:40 -07:00
Arnavion 77474771e6 Fixed bug in SRT-to-ASS conversion not converting all HTML tags. 2014-08-17 03:51:29 -07:00
Arnavion 55f9cb42fe Store animation delays separately instead of parsing them from the sub's style properties. 2014-08-17 03:51:27 -07:00
Arnavion a8addddbd6 Begin v0.9.0 2014-08-16 21:58:29 -07:00
Arnavion ccd4a53cfb Updated mocha to v1.21.x 2014-08-16 21:52:38 -07:00
Arnavion 3928bf57f0 Added ASS.addEvent() to dynamically add dialogues to an ASS object.
Fixes #16
2014-08-16 21:33:26 -07:00
Arnavion dd6d008b74 Parse format-specifier-enabled properties inside parse_assScriptProperty itself instead of relying on caller. 2014-08-16 21:28:56 -07:00
Arnavion 45aabac358 Allow passing in a custom parse tree root to libjass.parser.parse() 2014-08-16 21:28:56 -07:00
Arnavion 55c9dc10ca Log how long it to parse the script in debug mode. 2014-08-16 18:47:17 -07:00
Arnavion 32c232308f Update ManualClock with new API. 2014-08-08 23:02:26 -07:00
Arnavion 2eaa6e451d Cleanup and typos. 2014-08-08 22:51:12 -07:00
Arnavion 03ed6091c2 Handle unknown types gracefully in type linker. 2014-08-08 22:32:32 -07:00
Arnavion 43c3e26596 Use a checkbox to toggle subs instead of a button. 2014-08-08 22:22:44 -07:00
Arnavion 9e584bb75b Better clock state machine and API. 2014-08-08 22:22:13 -07:00
Arnavion e62f150f32 Added explanatory comments to example. 2014-08-08 20:23:53 -07:00
Arnavion 24ccc5200c Set resolution option labels even if video metadata is already loaded, and other tiny fixes. 2014-08-08 20:14:56 -07:00
Arnavion c627e72b03 Use XHR's load event instead of readystatechange + readyState === DONE 2014-08-08 20:02:46 -07:00
Arnavion 6eeb634a36 Minor improvements. 2014-07-31 22:56:38 -07:00
Arnavion 2349b82f0f Fastpath for ParseNode._peek() 2014-07-31 22:56:10 -07:00
Arnavion 443714878b Simply logic for parsing whitespace or text nodes while parsing dialogue parts. 2014-07-31 22:55:11 -07:00
Arnavion 7a6f956b49 Remember the format specifier for script sections that have it. Persist the format specifier for ASS dialogues.
Required for #16
2014-07-31 22:53:45 -07:00
Arnavion 73e464e357 Parse newlines as part of parsing a script header/comment/property instead of requiring script section to swallow it. 2014-07-31 22:52:31 -07:00
Arnavion 71d58e686c Don't create objects before they're needed. 2014-07-31 22:51:38 -07:00
Arnavion adaba54be0 Revert "Work around build break because of source-map 0.1.35"
This reverts commit 54b4245482.

Fixed in source-map 0.1.37.
2014-07-13 02:16:39 -07:00
Arnavion 5be310a6ba Added RendererSettings.preciseOutlines
When false, outlines are rendered in increments of the gaussian blur (if any). Vastly boosts performance for large-outline-large-blur lines and doesn't look appreciably different.
2014-07-13 02:14:09 -07:00
Arnavion ee45e0379e Added default value of RendererSettings.preRenderTime to JSDoc. 2014-07-13 02:13:04 -07:00
Arnavion 848898c8d0 Don't rename "_classTag" property in minifier. webworker serializer refers to it by name. 2014-07-11 00:46:10 -07:00
Arnavion deda90698b UJS.SourceMap.root defaults to null. 2014-07-09 20:29:59 -07:00
Arnavion 774b218aff Use a set to hold font URLs to avoid duplicates. 2014-07-09 20:28:11 -07:00
Arnavion 6bb4873d67 Implemented SimpleSet.size 2014-07-09 20:27:26 -07:00
Arnavion 54b4245482 Work around build break because of source-map 0.1.35
Depending on https://github.com/mozilla/source-map/issues/123 it's either a bug in source-map or in TypeScript.
2014-07-09 00:21:52 -07:00
Arnavion 39d75c189d Implemented UglifyJS directive to suppress unreferenced symbol warnings. 2014-07-08 22:27:41 -07:00
Arnavion ae56620f91 Updated mocha to v1.20.x 2014-07-04 23:41:32 -07:00
Arnavion ee07ca1d7c Removed workaround for uglify-js < 2.4.14 2014-07-04 23:41:19 -07:00
Arnavion b6ca859f4b Fixed typo. 2014-07-04 23:20:07 -07:00
Arnavion c4f87d54bf Added support for \fs+ and \fs- 2014-07-04 23:19:41 -07:00
Arnavion b662698e0c Increase range of filter effects from 150% to 200% 2014-07-03 01:21:49 -07:00
Arnavion 0198fb235c Fixed some things detected by Safer Typescript compiler. 2014-07-03 00:57:06 -07:00
Arnavion fc5dce86ea Increase range of filter effects from 120% to 150% 2014-06-20 21:31:27 -07:00
Arnavion d918b1256d Explicitly set text alignment on absolutely-positioned subs because they'll go in a .an0 <div> and so won't get alignment CSS text-align. 2014-06-02 22:25:57 -07:00
Arnavion c65305fbe8 Fixed typo. 2014-06-02 21:49:00 -07:00
Arnavion 111c4199ff Fixed min-width calculation to correctly sum horizontal margins. 2014-06-02 21:23:25 -07:00
Arnavion 8bc205fc01 Added support for interfaces to documentation generator. 2014-05-31 02:17:49 -07:00
Arnavion e69221af7d Web worker improvements.
- Don't restrict usage to only one worker channel per library instance.
- WorkerChannel.request() now returns a promise instead of needing a callback passed in.
2014-05-31 01:42:22 -07:00
Arnavion 6ba048e55a Added web worker test for libjass.parser.parse() 2014-05-29 00:35:12 -07:00
Arnavion 8dda6d67e6 Web worker support for calling libjass.parser.parse() 2014-05-29 00:35:10 -07:00
Arnavion 7c6793be8c Implemented a mechanism for running tasks in a web worker. 2014-05-29 00:35:09 -07:00
Arnavion 123339519d Added browser support for async tests and mocha's setup() function. 2014-05-29 00:35:08 -07:00
Arnavion 12374765ed Added support for Map.size to SimpleMap 2014-05-29 00:35:06 -07:00
Arnavion 255447b147 Updated documentation generator to use the new TypeScript API. 2014-05-29 00:35:05 -07:00
Arnavion 32507ad644 Fixed not being able to parse tags without values. 2014-05-28 22:00:04 -07:00
Arnavion d06777d2b3 Removed private member from interface. 2014-05-27 20:46:13 -07:00
Arnavion b727f3c6e2 Added support for adding and removing files while watching.
Removed astWatcher support for watch since it's not something I care to have run in incremental compiles.
2014-05-22 23:21:53 -07:00
Arnavion 140393fcca Compiler was resolving files using the old file contents instead of the updated file contents, which would suppress reference errors until the next compile. 2014-05-22 12:35:38 -07:00
Arnavion 2d308b7130 Support top-level classes and free functions in AST walker.
While libjass will never have these, they can occur because of what's actually a compile error. Thus while the AST walker will succeed, the subsequent call to compiler.compile() will fail.
2014-05-21 00:49:10 -07:00
Arnavion 6a282416a8 Split test runner into its own file that doesn't need gulp to run.
This allows the tests child process to start nearly instantly since it doesn't have to spend a few seconds loading gulp.
2014-05-21 00:49:08 -07:00
Arnavion 40ebcfc6b7 Tell gulp.src not to read file contents since we read the files ourselves. 2014-05-21 00:21:58 -07:00
Arnavion d23e57d215 Added better watch implementation of TypeScript gulp task that only re-compiled changed files. 2014-05-21 00:21:57 -07:00
Arnavion 77ca69e1d3 Added information about using the parser in node. 2014-05-15 15:51:30 -07:00
Arnavion c2ff6dc369 Begin v0.8.0 2014-05-15 15:16:30 -07:00
Arnavion af9ea7c886 Use SPDX identifier for license. 2014-05-15 14:49:06 -07:00
Arnavion e1eb4f8e6f Updated TypeScript to v1.0.1 2014-05-13 20:12:35 -07:00
Arnavion 7303fd0f53 line-height gets inherited by children already. 2014-05-02 08:48:25 -07:00
Arnavion 96bf8d7f6c Use CSS to set alignment-specific text-align values. 2014-05-02 08:47:47 -07:00
Arnavion 74de507782 Fixed typo in JSDoc. 2014-05-02 00:48:46 -07:00
Arnavion 0155cd7392 Added clocks and a WebRenderer that's less magical than DefaultRenderer.
- Clocks are now used to trigger play, pause and timeUpdate events for renderers. There is a VideoClock that feeds off a <video> (what NullRenderer used to do) and a ManualClock that allows user script to send events (such as a player not backed by a <video>)
- NullRenderer now takes a Clock and uses its events to determine what dialogues to pre-render and draw.
- WebRenderer is a new renderer that's halfway between NullRenderer and DefaultRenderer. It takes in a <div> to render to, the libjass subs wrapper, but it is not tied to an actual <video> element. It is most of the old DefaultRenderer code except the bits that were specific to a wrapped <video>.
- DefaultRenderer now inherits from WebRenderer. It specializes WebRenderer as a renderer that wraps a <video>, just like it used to before. That is, it sets the clock to a VideoClock backed by a <video>, and makes the libjass subs wrapper wrap the <video>.
2014-05-02 00:48:28 -07:00
Arnavion 974c8f70ff Implemented support for \be
Fixes #3
2014-04-26 15:30:31 -07:00
Arnavion e4cd237779 Added missing space in SVG filter text. 2014-04-26 14:22:04 -07:00
Arnavion 4dec3b36f4 Fixed typo - rotationZ defaults to 0, not null 2014-04-26 14:22:03 -07:00
Arnavion e275cfbf2e Use pre-computed array for transform origins. 2014-04-26 14:22:02 -07:00
Arnavion 4d25127617 Changed Drawing to an accumulator of DrawingStyles.
This fixes the following:
- Declaring \pbo before \p1 used to have no effect, but now it does.
- Multiple DrawingInstructions parts used to cause an error instead of being treated as separate drawings.
2014-04-12 12:35:36 -07:00
Arnavion 8f6deb2f8e Added getter for current primary alpha to SpanStyles. 2014-04-12 12:31:11 -07:00
Arnavion 3958d9f504 Added missing return type to SpanStyles.primaryColor getter. 2014-04-12 12:30:26 -07:00
Arnavion 120a8e8cbd Separated the code that renders comments as text in debug mode into its own branch. 2014-04-12 12:00:03 -07:00
Arnavion 99dfafeafd Auto-generate @constructor, @extends, @memberOf, @private and @static from TypeScript AST. 2014-04-06 21:23:24 -07:00
Arnavion 379265414a Get baseType from AST walker instead of JSDoc. 2014-04-04 00:24:10 -07:00
Arnavion e09a34cca6 Added support for variables to documentation generator. 2014-04-04 00:24:09 -07:00
Arnavion b49bd14e55 Rewrote documentation generator to use the TypeScript syntax tree instead of UglifyJS. 2014-04-04 00:24:05 -07:00
Arnavion febd4f18ca Updated TypeScript to v1.0.0 2014-04-04 00:24:04 -07:00
Arnavion a633963b9f Added syntax highlighting. 2014-03-30 03:34:23 -07:00
Arnavion b0db48f28e Some gulp changes.
- gulp can take the names of multiple tasks to run. Use that in npm install instead of spawning two gulp processes.
- Made watch faster and more robust.
2014-03-29 15:28:39 -07:00
Arnavion c893984115 Fixed copy-paste typo. 2014-03-29 15:28:38 -07:00
Arnavion a4ef8b7ef8 Fixed typo in source-map URL for minified JS. 2014-03-28 23:17:47 -07:00
Arnavion a26a238b09 Begin v0.7.0 2014-03-24 00:43:35 -07:00
Arnavion 43c72308fb Updated mocha to v1.18.x and restricted uglify-js version to one that has the needed bugfixes. 2014-03-24 00:34:44 -07:00
Arnavion b5579ab340 Query the list of sources from output.source_map instead of guessing. 2014-03-22 18:44:34 -07:00
Arnavion dbf4b26768 Removed workaround for https://github.com/mishoo/UglifyJS2/issues/436 - Fixed in v2.4.13 2014-03-19 23:21:50 -07:00
Arnavion d6abba96d1 Use <pre><code> for usages. 2014-03-16 13:47:08 -07:00
Arnavion 165e18ae38 Replaced jake with gulp. 2014-03-11 23:14:38 -07:00
Arnavion 90f08a4116 Updated jake to v0.7.9 2014-03-07 23:45:26 -08:00
Arnavion 0dc8a08b3f Set jake version to 0.7.7 until https://github.com/mde/jake/pull/246 is fixed. 2014-03-07 22:30:20 -08:00
Arnavion 6ffd67523d Updated suppressed warnings. 2014-03-07 22:30:08 -08:00
Arnavion bd857350a0 Combine horizontal scaling into font-size for text parts so that they don't clip into their neighbours.
Fixes #15
2014-03-06 00:41:13 -08:00
Arnavion d42261ae3e Don't let .libjass-font-measure interfere with the rest of the DOM. 2014-03-06 00:39:31 -08:00
Arnavion 18b764c7ed Implemented basic SRT support.
- Supported: Multiple lines, <b>, <i>, <u>, <font color="#[0-9a-fA-F]{6}">
- Not supported: Explicit positioning.
- Internally converts SRT to ASS because I'm lazy.

Fixes #2
2014-03-04 21:29:07 -08:00
Arnavion df5318f14c Support undefined values and objects with undefined constructors in assert.deepEqual 2014-03-04 21:24:31 -08:00
Arnavion 6783efbe91 Fixed typo in \fade handling. 2014-03-04 20:33:42 -08:00
Arnavion 72df7fce8a Replaced pre-defined fade animation with explicit animation.
`animation-fill-mode: both` in Firefox caused the fade-out animation of a \fad to be ignored if the fade-in animation was also applied. With this change the fade-in and fade-out make only one animation.
2014-03-04 20:30:21 -08:00
Arnavion 0ad4eac649 Show private by default if location.hash is for a private thing. 2014-03-01 17:50:30 -08:00
Arnavion 225b696077 Updated README 2014-03-01 17:23:19 -08:00
Arnavion 33ed1e44cd Added missing JSDoc. 2014-03-01 17:13:23 -08:00
Arnavion 44f02e50b4 Fixed ASS drawings always being black. 2014-03-01 17:00:43 -08:00
Arnavion c06dd13717 Fixed parser failure when drawing instructions have terminal spaces or are only spaces. 2014-03-01 16:44:32 -08:00
Arnavion 26edc2e0d9 Minor typo. 2014-03-01 16:24:50 -08:00
Arnavion 5992664bed Replaced 41ms setInterval-based timer with requestAnimationFrame-based timer. 2014-03-01 16:23:59 -08:00
Arnavion 7d2070900b Expose reference to renderer in debug mode. 2014-03-01 16:22:39 -08:00
Arnavion 1fcb8d6e37 Fixed font sizes.
The font size in ASS is actually meant to be the line height. ASS renderers scale the font size so that it fits in the line height. Since there is no way in the browser to calculate a font size such that it results in a given line height, libjass now uses an invisible div's offsetHeight to calculate the line height for a given font size, and works backwards from there to approximate the font size required for a target line height.
2014-03-01 16:16:33 -08:00
Arnavion 7d81f7d695 Workaround for https://github.com/mishoo/UglifyJS2/issues/436 2014-03-01 05:52:36 -08:00
Arnavion f4c2c0ee28 Don't call renderer.onVideoTimeUpdate() when this.currentTime is not available. 2014-03-01 05:52:02 -08:00
Arnavion 3b513c0e27 Separate layer wrappers. 2014-02-25 19:23:39 -08:00
Arnavion ed49bd544f Updated TypeScript to v0.9.7 2014-02-25 19:23:38 -08:00
Arnavion 3667ab415b Changed vararg functions to use arrays because the Closure Compiler annotation doesn't match what the TypeScript compiler generates for these functions.
GCC wants the vararg parameter as an actual parameter to the function even though it will be unused, while TS doesn't generate it.
2014-02-23 19:01:00 -08:00
Arnavion 7aaf3a3f24 Fixed JSDoc issues found by Closure Compiler. 2014-02-23 19:00:25 -08:00
Arnavion d3608c0f72 More JSDoc fixes. 2014-02-23 18:39:57 -08:00
Arnavion 07341f89c8 Fixed return-type JSDoc annotation. 2014-02-23 18:34:58 -08:00
Arnavion d2b0da2954 Added support for toggling subtitles by disabling and enabling the renderer.
Fixes #5
2014-02-23 01:29:27 -08:00
Arnavion f312514e40 Simplified video-event normalization. 2014-02-23 01:29:26 -08:00
Arnavion 1354964bb6 Also escape ampersands. 2014-02-22 22:52:13 -08:00
Arnavion a14389c7e1 Fixed HTML indentation and order of members. 2014-02-22 22:38:48 -08:00
Arnavion 31d03baf9f Added JSDoc for libjass.Set and libjass.Map 2014-02-22 21:54:16 -08:00
Arnavion 833c429e88 Prettier "Usage" box. 2014-02-22 21:53:58 -08:00
Arnavion 6ba8ce45c7 Don't guess private-ness without explicit @private JSDoc annotation. 2014-02-22 21:53:16 -08:00
Arnavion 269e3b917b Minor fixes. 2014-02-22 21:16:07 -08:00
Arnavion b7919d8b7c Embed the source in the source maps so that source debugging is available without needing to host the source. 2014-02-19 13:58:10 -08:00
Arnavion 3fa1be6c33 Use screw_ie8 config option.
This doesn't actually change anything, but we don't support IE6-8 anyway so there's no harm in using it.
2014-02-19 11:12:40 -08:00
Arnavion 754e28231d Fixed some outdated info. 2014-02-17 12:04:47 -08:00
Arnavion 5823d77075 Truncate Color.alpha in rgba() notation to three decimal places. 2014-02-12 09:54:45 -08:00
Arnavion f40766049a Added support for opacity to borders. 2014-02-12 09:51:28 -08:00
Arnavion 94cdace6d9 Don't create unnecessary empty span's. 2014-02-10 18:51:52 -08:00
Arnavion b5de1556db Replaced feOffset+feComponentTransfer-based outlines with feMorphology+feFlood-based outlines.
The resulting filters are smaller and faster and the outlines have the right colors.
2014-02-10 18:40:08 -08:00
Arnavion 5bf0a13277 Don't render shadow when both shadow depth X and Y are 0. 2014-02-10 17:53:34 -08:00
Arnavion d8636b0302 Fixed outdated JSDoc. 2014-02-09 13:24:37 -08:00
Arnavion 4e2cb294ed Prevent browsers being over-generous in inserting newlines.
This behavior will cause all lines to be as wide as the subtitle wrapper. While this does mean that signs positioned not exactly in the center can be so wide they clip at the edges of the video, this is the same behavior as VSFilter.
2014-02-09 13:17:54 -08:00
Arnavion 1e52a0943b Re-introduced parts.NewLine
This is needed since all span's can be inline-block now.
2014-02-09 13:16:28 -08:00
Arnavion 86cdaf2edf Fixed error when parsing cubic bezier curve drawing instructions. 2014-02-08 19:38:15 -08:00
Arnavion 508c49cc44 Trace parse failures in greater detail in debug mode. 2014-02-08 19:37:20 -08:00
Arnavion e4e3401573 Renamed DefaultRenderer.resizeVideo to DefaultRenderer.resize 2014-02-08 19:15:11 -08:00
Arnavion 8e5f242743 Added support for parsing wrapping style and border/shadow scaling script properties.
Fixes #10
2014-02-08 17:41:33 -08:00
Arnavion 0cbe15698e Set Dialogue._alignment in Dialogue._parsePartsString() for consistency. 2014-02-08 17:09:04 -08:00
Arnavion a90c8a0e0a Updated example and readme to resize video manually because of 98e95936b6 2014-02-08 17:07:46 -08:00
Arnavion 5e81bff15c Added support for parsing secondary color, default Z-rotation and border style of styles.
Fixes #9
2014-02-08 17:06:25 -08:00
Arnavion 79268096e0 Rotation and skew fixes.
- Rotation and skew now act on individual spans instead of the whole div.
- Rotation now has a perspective set.
- Rotations are now applied in the fixed order of Y-X-Z in accordance with VSFilter.
- Skew is now calculated correctly - skew angle is now set to "atan(value) deg" instead of "(45 * value) deg"
2014-02-08 15:59:21 -08:00
Arnavion 28e2588df3 Updated SimpleMap.set error message for unsupported keys. 2014-02-06 23:41:38 -08:00
Arnavion 8261bac95a Changed DefaultRenderer._currentSubs to have Dialogue keys instead of their IDs.
This fixes the use of the incorrect assumption that dialogue IDs are also their indices in ass.dialogues
2014-02-06 23:38:48 -08:00
Arnavion 79a9cd06cc Added support for Dialogue objects in SimpleMap. 2014-02-06 23:37:19 -08:00
Arnavion ec84d62c60 Removed leftovers from tsline experimentation. 2014-02-06 23:14:39 -08:00
Arnavion e5fc5ca571 Removed broken binary-search-on-end-times algorithm for deciding which dialogues to pre-render / draw. 2014-02-06 22:55:03 -08:00
Arnavion dfb9a372dd Use .toFixed(3) on margins. 2014-02-06 22:33:09 -08:00
Arnavion 98e95936b6 Don't resize the video in DefaultRenderer.resizeVideo() and don't rely on video.style.width and video.style.height to be present. 2014-02-06 21:56:49 -08:00
Arnavion dc8e7d4214 Made .libjass-filters SVG element have display: block 2014-02-06 21:56:11 -08:00
Arnavion 23f5c21bb6 Log dialogue parts even when it wasn't already pre-rendered. 2014-02-06 15:56:47 -08:00
Arnavion a0d357329a Only log timeUpdate, etc. in verbose mode. 2014-02-06 15:56:33 -08:00
Arnavion ffb6da34a3 Converted unnecessary and redundant inheritance to a mixin. 2014-02-06 15:52:11 -08:00
Arnavion 05dcd65dd5 Changed parts.VectorClip.instructions from parts.DrawingInstruction to parts.drawing.Instruction[]
vectorClipPart.instructions.instructions looked too silly, and DrawingInstruction was only meant to be a pseudo-part for ASS draw anyway.
2014-02-06 13:55:26 -08:00
Arnavion 7567a6a8b6 Fixed typo. 2014-02-06 13:29:16 -08:00
Arnavion 09efaea7ac Implemented parsing drawing instructions for VectorClip. 2014-02-06 13:28:41 -08:00
Arnavion 985de99d81 Renamed parts.DrawingInstructions.value to parts.DrawingInstructions.instructions 2014-02-06 13:27:43 -08:00
Arnavion 6492af0675 Fixed some typos and method order. 2014-02-06 13:26:09 -08:00
Arnavion b0c327ed26 Made all headings consistently level 3 2014-02-05 20:49:53 -08:00
Arnavion d5292e374e Rename function arguments that start with an underscore to not have the underscore. 2014-02-05 20:15:36 -08:00
Arnavion dac9cb0688 Fixed style errors from tslint. 2014-02-01 00:42:05 -08:00
Arnavion e40c3d50fd Replaced DefaultRenderer._{add,remove}Class with Element.classList
Fixes #11
2014-01-29 01:17:41 -08:00
Arnavion f2edbfc4cf Fixed example to use ass.properties to get script resolution. 2014-01-29 01:17:05 -08:00
Arnavion 4505edf8ba Begin v0.6.0 2014-01-26 11:42:41 -08:00
34 changed files with 6785 additions and 4860 deletions
+16 -10
View File
@@ -4,22 +4,28 @@
1. Run the following command
npm install
```shell
npm install
```
This will install the dependencies - [Jake](https://github.com/mde/jake), [TypeScript](http://www.typescriptlang.org/) and [UglifyJS2](https://github.com/mishoo/UglifyJS2). It will then run Jake to build libjass.js and use UglifyJS2 to minify it into libjass.min.js
This will install the dependencies - [Gulp](http://gulpjs.com/), [Mocha](http://visionmedia.github.io/mocha/), [TypeScript](http://www.typescriptlang.org/), [UglifyJS2](https://github.com/mishoo/UglifyJS2) and [Vinyl](https://github.com/wearefractal/vinyl). It will then run gulp to build libjass.js and minify it into libjass.min.js
1. Set the URLs of the video and the ASS file in index.xhtml
<video id="video" src=" <URL OF VIDEO HERE> " controls="">
<track src=" <URL OF SCRIPT HERE> " kind="metadata" data-format="ass" />
</video>
```html
<video id="video" src="<URL OF VIDEO HERE>" controls="">
<track src="<URL OF SCRIPT HERE>" kind="metadata" data-format="ass" />
</video>
```
1. Set the URLs of any fonts you want to make available in fonts.css
@font-face {
font-family: " <NAME OF FONT HERE> ";
src: url(" <URL OF FONT HERE> ");
}
for each font. The name of the font is what it's called in the ASS file.
```css
@font-face {
font-family: "<NAME OF FONT HERE>";
src: url("<URL OF FONT HERE>");
}
```
for each font. The name of the font is what it's called in the ASS file.
1. Start your web server and navigate to index.xhtml in a browser.
-30
View File
@@ -1,30 +0,0 @@
desc("Build libjass.js, libjass.min.js and their sourcemaps");
task("default", ["_default:writeCode", "_default:writeSourceMap", "_default:writeMinifiedCode", "_default:writeMinifiedSourceMap"], function () {
console.log("[" + this.fullName + "]");
});
desc("Clean");
task("clean", ["_clean:run"], function () {
console.log("[" + this.fullName + "]");
});
desc("Test");
task("test", ["_test:run[true]"], function () {
console.log("[" + this.fullName + "]");
});
desc("Watch");
task("watch", ["_watch:run"], function () {
console.log("[" + this.fullName + "]");
});
desc("Generate API documentation");
task("doc", [], function (outputFilename) {
console.log("[" + this.fullName + "]");
if (outputFilename === undefined) {
throw new Error("outputFilename not specified.");
}
jake.Task["_doc:writeHtml"].invoke(outputFilename);
});
+37 -10
View File
@@ -24,7 +24,7 @@ As a result, libjass is able to render subtitles with very low CPU usage. The do
### I want to use libjass for my website. What do I need to do?
1. You need to build libjass.js using the instructions in BUILD.md
1. You need to load libjass.js on the page with your video.
1. You need to load libjass.js and libjass.css on the page with your video.
1. You need to call the libjass API.
Only libjass.js and libjass.css are needed to use libjass on your website. The other files are only used during the build process and you don't need to deploy them to your website.
@@ -36,15 +36,39 @@ The API documentation is linked in the Links section below. Here's an overview:
* The method [ASS.fromString()](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS.fromString) takes in the raw ASS string and returns an [ASS](http://arnavion.github.io/libjass/api.xhtml#libjass.ASS) object representing the script properties, the line styles and dialogue lines in it. The example index.js uses XHR to get this data using the URL specified in a track tag.
* index.js initializes a default renderer that libjass ships with, the [DefaultRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer). This renderer uses information from the ASS object to build up a series of div elements around the video tag. There is a wrapper (.libjass-subs) containing div's corresponding to the 9 alignment directions, 9 for each layer in the ASS script. libjass.css contains styles for these div's to render them at the correct location.
* index.js initializes a default renderer that libjass ships with, the [DefaultRenderer](http://arnavion.github.io/libjass/api.xhtml#libjass.renderers.DefaultRenderer). This renderer uses information from the ASS object to build up a series of div elements around the video tag. There is a wrapper (.libjass-subs) containing div's corresponding to the layers in the ASS script, and each layer has div's corresponding to the 9 alignment directions. libjass.css contains styles for these div's to render them at the correct location.
* The renderer starts a timer that ticks every 41ms. In each tick, it determines the set of dialogues to be shown at the current video time, renders each of them as a div, and appendChild's the div into the appropriate layer+alignment div.
* The renderer uses [window.requestAnimationFrame](https://developer.mozilla.org/en-US/docs/Web/API/window.requestAnimationFrame) as a source of timer ticks. In each tick, it determines the set of dialogues to be shown at the current video time, renders each of them as a div, and appendChild's the div into the appropriate layer+alignment div.
* The renderer handles resizing the video and subs when the user clicks the browser's native fullscreen-video button. index.js also contains code to change the size of the video based on user input.
* The renderer handles resizing the subtitles when the user clicks the browser's native fullscreen-video button. index.js also contains code to change the size of the subtitles based on user input.
* Lastly, the renderer contains an implementation of preloading fonts before playing the video. It uses a map of font names to URLs - index.js creates this map from the @font-face rules in fonts.css.
### Can I use libjass in node?
libjass's parser works in node.
```javascript
> var libjass = require("./libjass.js")
undefined
> var parts = libjass.parser.parse("{\\an8}Are {\\i1}you{\\i0} the one who stole the clock?!", "dialogueParts")
undefined
> parts.join(" ")
'Alignment { value: 8 } Text { value: Are } Italic { value: true } Text { value: you } Italic { value: false } Text { value: the one who stole the clock?! }'
> parts.length
6
> parts[0].toString()
'Alignment { value: 8 }'
> parts[0] instanceof libjass.parts.Alignment
true
> parts[0].value
8
```
[libjass.parser.parse](http://arnavion.github.io/libjass/api.xhtml#libjass.parser.parse) parses the first parameter using the second parameter as the rule name. The rule names are derived from the methods on the [ParserRun class](http://arnavion.github.io/libjass/api.xhtml#libjass.parser.ParserRun). For example, [dialogueParts](http://arnavion.github.io/libjass/api.xhtml#libjass.parser.ParserRun.parse_dialogueParts) can be used to get an array of [libjass.parts](http://arnavion.github.io/libjass/api.xhtml#libjass.parts) objects that represent the parts of an ASS dialogue line.
### Can I contribute?
Yes! Feature requests, suggestions, bug reports and pull requests are welcome! I'm especially looking for details and edge-cases of the ASS syntax that libjass doesn't support.
@@ -52,7 +76,7 @@ Yes! Feature requests, suggestions, bug reports and pull requests are welcome! I
You can also join the IRC channel below and ask any questions.
## Links
### Links
* [GitHub](https://github.com/Arnavion/libjass/)
* IRC channel - #libjass on irc.rizon.net
@@ -60,21 +84,24 @@ You can also join the IRC channel below and ask any questions.
* [Aegisub's documentation on ASS](http://docs.aegisub.org/3.0/ASS_Tags/)
## Supported features
### Supported features
* Styles: Italic, Bold, Underline, StrikeOut, FontName, FontSize, ScaleX, ScaleY, Spacing, PrimaryColor, OutlineColor, BackColor, Outline, Shadow, Alignment, MarginL, MarginR, MarginV
* Tags: \i, \b, \u, \s, \bord, \xbord, \ybord, \shad, \xshad, \yshad, \blur, \fn, \fs, \fscx, \fscy, \fsp, \frx, \fry, \frz, \fr, \fax, \fay, \c, \1c, \3c, \4c, \alpha, \1a, \3a, \4a, \an, \a, \r, \pos, \move, \fad, \fade, \p
* Custom fonts, using CSS web fonts.
## Known bugs
### Known issues
* Unsupported tags: \be, \fe, \2c, \2a, \k, \K, \kf, \ko, \q, \org, \t, \clip, \iclip
* \an4, \an5, \an6 aren't positioned correctly.
* Font sizes aren't pixel perfect.
* Lines scaled using {\fscx} and {\fscy} have their text clip into itself in some situations, and aren't always positioned correctly.
* All lines are rendered as wrapping style 1 (end-of-line wrapping).
* Lines with multiple rotations aren't rotated the same as VSFilter or libass.
* Subtitles aren't styled in IE11 because [it doesn't support SVG filter effects on HTML](http://caniuse.com/svg-html).
## Planned improvements
### Planned improvements
* Document browser compatibility. Currently libjass is tested on IE11 (Windows 7), Firefox Nightly and Google Chrome (Dev channel).
* Write API documentation. Add more explanatory comments to the code.
@@ -82,7 +109,7 @@ You can also join the IRC channel below and ask any questions.
* Evaluate (document, benchmark) the benefits and drawbacks of DOM+CSS-based drawing over canvas.
# License
### License
```
libjass
+130
View File
@@ -0,0 +1,130 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require("fs");
var path = require("path");
var gulp = require("gulp");
var Vinyl = require("vinyl");
var helpers = require("./gulplib/helpers.js");
var Transform = helpers.Transform;
var SingletonChildProcess = helpers.SingletonChildProcess;
Object.defineProperties(global, {
Doc: { get: function () { return require("./gulplib/doc.js"); } },
TypeScript: { get: function () { return require("./gulplib/typescript.js"); } },
UglifyJS: { get: function () { return require("./gulplib/uglify.js"); } },
});
gulp.task("default", ["libjass.js", "libjass.min.js"]);
function ASTModifer(namespaces) {
var visitor = function (current) {
var newText = [];
if (current instanceof TypeScript.AST.Namespace) {
current.members.forEach(visitor);
}
else if (current instanceof TypeScript.AST.Constructor) {
newText.push("@constructor");
if (current.baseType !== null) {
newText.push("@extends {" + current.baseType.fullName + "}");
}
if (current.parent !== null) {
newText.push("@memberOf " + current.parent.fullName);
}
current.members.forEach(visitor);
}
if (current.isPrivate) {
newText.push("@private");
}
if (current.isStatic) {
newText.push("@static");
}
if (newText.length > 0) {
current.astNode["gulp-typescript-new-comment"] = newText;
}
};
Object.keys(namespaces).forEach(function (namespaceName) { visitor(namespaces[namespaceName]); });
}
gulp.task("libjass.js", function (callback) {
if (fs.existsSync("./libjass.js")) {
return callback(null);
}
return gulp.src("./libjass.ts", { read: false })
.pipe(TypeScript.gulp("/libjass.js", "/libjass.js.map", ASTModifer))
.pipe(UglifyJS.fixup())
.pipe(gulp.dest("."));
});
gulp.task("libjass.min.js", ["libjass.js"], function (callback) {
if (fs.existsSync("./libjass.min.js")) {
return callback(null);
}
var input = Object.create(null);
return gulp.src(["./libjass.js", "./libjass.js.map"]).pipe(UglifyJS.minify()).pipe(gulp.dest("."));
});
gulp.task("clean", function () {
["libjass.js", "libjass.js.map", "libjass.min.js", "libjass.min.js.map"].forEach(function (file) {
try {
fs.unlinkSync(file);
}
catch (ex) {
if (ex.code !== "ENOENT") {
throw ex;
}
}
});
});
gulp.task("watch", ["clean"], function (callback) {
var gulpTestProcess = SingletonChildProcess(path.resolve("./gulplib/test-runner.js"));
gulp.src("./libjass.ts", { read: false })
.pipe(TypeScript.watch("/libjass.js", "/libjass.js.map"))
.pipe(UglifyJS.fixup())
.pipe(gulp.dest("."))
.pipe(Transform(function (file) {
if (path.basename(file.path) === "libjass.js") {
gulpTestProcess();
}
}));
gulp.watch(["./tests/test-*.js"], { debounceDelay: 1 }, function () {
gulpTestProcess();
});
});
gulp.task("doc", ["libjass.js"], function () {
return gulp.src("./libjass.ts").pipe(Doc("/api.xhtml")).pipe(gulp.dest("../libjass-gh-pages/"));
});
+678
View File
@@ -0,0 +1,678 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require("fs");
var path = require("path");
var vm = require("vm");
var Vinyl = require("vinyl");
var Transform = require("./helpers.js").Transform;
var TypeScript = require("./typescript.js");
Array.prototype.concatMany = function (arr) {
var result = this;
arr.forEach(function (a) {
result = result.concat(a);
});
return result;
};
module.exports = function () {
var compiler = new TypeScript.Compiler();
var filenames = [];
var allFiles = [];
return Transform(function (file, encoding) {
filenames.push(file.path);
allFiles.push.apply(allFiles, compiler.addFile(file));
}, function () {
// Walk
var namespaces = TypeScript.AST.walk(compiler, allFiles);
// Make HTML
var sorter = (function () {
var visibilitySorter = function (value1, value2) {
if (value1.isPrivate === value2.isPrivate) {
return 0;
}
if (value1.isPrivate) {
return 1;
}
if (value2.isPrivate) {
return -1;
}
return 0;
};
var types = [TypeScript.AST.Variable, TypeScript.AST.Property, TypeScript.AST.Function, TypeScript.AST.Interface, TypeScript.AST.Constructor];
var typeSorter = function (value1, value2) {
var type1Index = -1;
var type2Index = -1;
types.every(function (type, index) {
if (value1 instanceof type) {
type1Index = index;
}
if (value2 instanceof type) {
type2Index = index;
}
return (type1Index === -1) || (type2Index === -1);
});
return type1Index - type2Index;
};
var nameSorter = function (value1, value2) {
return value1.name.localeCompare(value2.name);
};
var sorters = [visibilitySorter, typeSorter, nameSorter];
return function (value1, value2) {
for (var i = 0; i < sorters.length; i++) {
var result = sorters[i](value1, value2);
if (result !== 0) {
return result;
}
}
return 0;
};
})();
var namespaceNames = Object.keys(namespaces).sort(function (ns1, ns2) {
return ns1.localeCompare(ns2);
});
namespaceNames.forEach(function (namespaceName) {
namespaces[namespaceName].members.sort(sorter);
namespaces[namespaceName].members.filter(function (value) {
return value instanceof TypeScript.AST.Interface || value instanceof TypeScript.AST.Constructor;
}).forEach(function (interfaceOrConstructor) {
interfaceOrConstructor.members.sort(sorter);
});
});
var sanitize = function (string) {
return string.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
};
var indenter = function (indent) {
return function (line) {
return ((line === "") ? line : (Array(indent + 1).join("\t") + line));
};
};
var writeOverview = function (indent) {
return [].concatMany(namespaceNames.map(function (namespaceName) {
var namespace = namespaces[namespaceName];
return [
'<span class="namespace"><a href="#' + sanitize(namespaceName) + '">' + sanitize(namespaceName) + '</a></span>',
'<ul class="namespace-elements">'
].concatMany(namespace.members.map(function (value) {
return (
' <li' +
((value.isPrivate === true) ? ' class="private"' : '') +
'><a href="#' + sanitize(value.fullName) + '">' + sanitize(value.name) + '</a></li>'
);
})).concat([
'</ul>',
''
]);
})).map(indenter(indent));
};
var writeFunction = function (func, indent) {
return [
'<dl class="function' +
(func.isAbstract ? ' abstract' : '') +
(func.isPrivate ? ' private' : '') +
(func.isStatic ? ' static' : '') +
'" id="' + sanitize(func.fullName) +
'">',
' <dt class="name">' + writeFunctionName(func) + '</dt>',
' <dd class="description">',
' <p>' + sanitize(func.description) + '</p>',
' </dd>',
' <dd class="usage"><fieldset><legend />' + writeFunctionUsage(func) + '</fieldset></dd>'
].concat(writeParameters(func, 1)).concat(writeReturns(func, 1)).concat([
'</dl>'
]).map(indenter(indent));
};
var writeInterface = function (interface, indent) {
return [
'<dl class="interface' +
(interface.isPrivate ? ' private' : '') +
'" id="' +
sanitize(interface.fullName) +
'">',
' <dt class="name">' + writeInterfaceName(interface) + '</dt>',
' <dd class="description">',
' <p>' + sanitize(interface.description) + '</p>',
' </dd>'
].concat([
' <dd class="members">'
]).concatMany(interface.members.map(function (member) {
if (member instanceof TypeScript.AST.Variable) {
return writeVariable(member, 2);
}
if (member instanceof TypeScript.AST.Function) {
return writeFunction(member, 2);
}
if (member instanceof TypeScript.AST.Property) {
return writeProperty(member, 2);
}
})).concat([
' </dd>',
'</dl>'
]).map(indenter(indent));
};
var writeConstructor = function (constructor, indent) {
return [
'<dl class="constructor' +
(constructor.isAbstract ? ' abstract' : '') +
(constructor.isPrivate ? ' private' : '') +
'" id="' +
sanitize(constructor.fullName) +
'">',
' <dt class="name">' + writeConstructorName(constructor) + '</dt>',
' <dd class="description">',
' <p>' + sanitize(constructor.description) + '</p>',
' </dd>',
' <dd class="usage"><fieldset><legend />' + writeConstructorUsage(constructor) + '</fieldset></dd>'
].concat(writeParameters(constructor, 1)).concat([
' <dd class="members">'
]).concatMany(constructor.members.map(function (member) {
if (member instanceof TypeScript.AST.Variable) {
return writeVariable(member, 2);
}
if (member instanceof TypeScript.AST.Function) {
return writeFunction(member, 2);
}
if (member instanceof TypeScript.AST.Property) {
return writeProperty(member, 2);
}
})).concat([
' </dd>',
'</dl>'
]).map(indenter(indent));
};
var writeVariable = function (variable, indent) {
return [
'<dl class="variable" id="' + sanitize(variable.fullName) + '">',
' <dt class="name">' + writePropertyName(variable) + '</dt>',
' <dd class="description">',
' <p>' + sanitize(variable.description) + '</p>',
' </dd>',
' <dd class="usage"><fieldset><legend />' + writeVariableUsage(variable) + '</fieldset></dd>'
].concat([
' <dd class="return type">' + sanitize(variable.type) + '</dd>',
]).concat([
'</dl>'
]).map(indenter(indent));
};
var writeCallableName = function (callable) {
return (
'<a href="#' + sanitize(callable.fullName) + '">' +
sanitize(
callable.name +
((callable.generics.length > 0) ? ('.<' + callable.generics.join(', ') + '>') : '')
) +
'</a>'
);
};
var writeFunctionName = function (func) {
return writeCallableName(func);
};
var writeInterfaceName = function (interface) {
return (
'interface ' +
writeCallableName(interface) +
((interface.baseType !== null) ? (' extends <a href="#' + sanitize(interface.baseType.fullName) + '">' + sanitize(interface.baseType.name) + '</a>') : '')
);
};
var writeConstructorName = function (constructor) {
return (
'class ' +
writeCallableName(constructor) +
((constructor.baseType !== null) ? (' extends <a href="#' + sanitize(constructor.baseType.fullName) + '">' + sanitize(constructor.baseType.name) + '</a>') : '')
);
};
var writeVariableUsage = function (variable) {
return (
'<pre><code>' +
sanitize('var result = ' + toVariableName(variable.parent) + '.' + variable.name + ';' +
'\n' +
toVariableName(variable.parent) + '.' + variable.name + ' = value;') +
'</code></pre>'
);
};
var writeFunctionUsage = function (func) {
return (
'<pre><code>' +
sanitize(
((func.returnType !== null) ? 'var result = ' : '') +
((func.parent !== null) ? ((func.isStatic ? func.parent.name : toVariableName(func.parent)) + '.') : '') +
func.name + '(' +
func.parameters.map(function (parameter) {
return parameter.name;
}).join(', ') + ');') +
'</code></pre>'
);
};
var writeConstructorUsage = function (constructor) {
return (
'<pre><code>' +
sanitize(
'var ' + toVariableName(constructor) + ' = ' +
'new ' + constructor.name + '(' +
constructor.parameters.map(function (parameter) {
return parameter.name;
}).join(', ') + ');') +
'</code></pre>'
);
};
var writeParameters = function (callable, indent) {
return _writeParameters(callable.parameters, indent);
};
var _writeParameters = function (parameters, indent) {
if (parameters.length === 0) {
return [];
}
return [
'<dd class="parameters">',
' <dl>'
].concatMany(parameters.map(function (parameter) {
return [
' <dt class="parameter name">' + sanitize(parameter.name) + '</dt>',
' <dd class="parameter type">' + sanitize(parameter.type) + '</dd>',
' <dd class="parameter description">' + sanitize(parameter.description) + '</dd>'
].concatMany(_writeParameters(parameter.subParameters, indent + 1));
})).concat([
' </dl>',
'</dd>'
]).map(indenter(indent));
};
var writeReturns = function (func, indent) {
if (func.returnType === null) {
return [];
}
return [
'<dt>Returns</dt>',
'<dd class="return type">' + sanitize(func.returnType.type) + '</dd>',
'<dd class="return description">' + sanitize(func.returnType.description) + '</dd>'
].map(indenter(indent));
};
var writeProperty = function (property, indent) {
var result = [];
if (property.getter !== null) {
result = result.concat(writeGetter(property, indent));
}
if (property.setter !== null) {
result = result.concat(writeSetter(property, indent));
}
return result;
}
var writeGetter = function (property, indent) {
var getter = property.getter;
return [
'<dl class="getter" id="' + sanitize(property.fullName) + '">',
' <dt class="name">' + writePropertyName(property) + '</dt>',
' <dd class="description">',
' <p>' + sanitize(getter.description) + '</p>',
' </dd>',
' <dd class="usage"><fieldset><legend />' + writeGetterUsage(property) + '</fieldset></dd>'
].concat([
' <dd class="return type">' + sanitize(getter.type) + '</dd>',
]).concat([
'</dl>'
]).map(indenter(indent));
};
var writeSetter = function (property, indent) {
var setter = property.setter;
return [
'<dl class="setter" id="' + sanitize(property.fullName) + '">',
' <dt class="name">' + writePropertyName(property) + '</dt>',
' <dd class="description">',
' <p>' + sanitize(setter.description) + '</p>',
' </dd>',
' <dd class="usage"><fieldset><legend />' + writeSetterUsage(property) + '</fieldset></dd>'
].concat(writeParameters(setter, 1)).concat([
'</dl>'
]).map(indenter(indent));
};
var writePropertyName = function (property) {
return (
'<a href="#' + sanitize(property.fullName) + '">' +
sanitize(property.name) +
'</a>'
);
};
var writeGetterUsage = function (property) {
return (
'<pre><code>' +
sanitize(
'var result = ' +
toVariableName(property.parent) + '.' + property.name +
';') +
'</code></pre>'
);
};
var writeSetterUsage = function (property) {
return (
'<pre><code>' +
sanitize(
toVariableName(property.parent) + '.' + property.name +
' = ' +
property.setter.parameters[0].name +
';') +
'</code></pre>'
);
};
var toVariableName = function (constructor) {
// TODO: Handle non-letters (are both their toLowerCase() and toUpperCase())
var name = constructor.name;
var result = "";
for (var i = 0; i < name.length; i++) {
if (name[i] === name[i].toLowerCase()) {
// This is lower case. Write it as lower case.
result += name[i];
}
else {
// This is upper case.
if (i === 0) {
// This is the first character. Write it as lower case.
result += name[i].toLowerCase();
}
else if (name[i - 1] === name[i - 1].toUpperCase()) {
// The previous character was upper case.
if (i === name.length - 1) {
// This is the last character. Write it as lower case.
result += name[i].toLowerCase();
}
else if (name[i + 1] === name[i + 1].toLowerCase()) {
// The next character is lower case so this is the start of a new word. Write this one as upper case.
result += name[i];
}
else {
// The next character is upper case. Write this one as lower case.
result += name[i].toLowerCase();
}
}
else {
// Previous character was lower case so this is the start of a new word. Write this one as upper case.
result += name[i];
}
}
}
return result;
};
this.push(new Vinyl({
path: "api.xhtml",
contents: Buffer.concat([
'<?xml version="1.0" encoding="utf-8" ?>',
'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">',
' <head>',
' <title>libjass API Documentation</title>',
' <style type="text/css">',
' <![CDATA[',
' html, body, .namespaces, .content {',
' height: 100%;',
' margin: 0;',
' }',
'',
' .namespaces, .content {',
' overflow-y: scroll;',
' }',
'',
' .namespaces {',
' float: left;',
' background-color: white;',
' padding: 0 20px;',
' margin-right: 20px;',
' }',
'',
' .content > section:not(:last-child) {',
' border-bottom: 1px solid black;',
' }',
'',
' .variable, .function, .interface, .constructor, .getter, .setter {',
' margin-left: 30px;',
' padding: 10px;',
' }',
'',
' section > .variable:nth-child(2n), section > .function:nth-child(2n), section > .interface:nth-child(2n), section > .constructor:nth-child(2n) {',
' background-color: rgb(221, 250, 238);',
' }',
'',
' section > .variable:nth-child(2n + 1), section > .function:nth-child(2n + 1), section > .interface:nth-child(2n + 1), section > .constructor:nth-child(2n + 1) {',
' background-color: rgb(244, 250, 221);',
' }',
'',
' .name {',
' font-size: x-large;',
' }',
'',
' .usage {',
' font-size: large;',
' font-style: italic;',
' }',
'',
' .usage legend:before {',
' content: "Usage";',
' }',
'',
' .usage pre {',
' margin: 0;',
' }',
'',
' .interface .variable, .interface .function, .interface .getter, .interface .setter,',
' .constructor .variable, .constructor .function, .constructor .getter, .constructor .setter {',
' background-color: rgb(250, 241, 221);',
' }',
'',
' .parameter.name {',
' font-size: large;',
' }',
'',
' .type {',
' font-style: italic;',
' }',
'',
' .type:before {',
' content: "Type: ";',
' }',
'',
' .abstract > .name:before {',
' content: "abstract ";',
' }',
'',
' .private > .name:before {',
' content: "private ";',
' }',
'',
' .static > .name:before {',
' content: "static ";',
' }',
'',
' .abstract.private > .name:before {',
' content: "abstract private ";',
' }',
'',
' .private.static > .name:before {',
' content: "static private ";',
' }',
'',
' body:not(.show-private) .private {',
' display: none;',
' }',
' ]]>',
' </style>',
' <script>',
' <![CDATA[',
' addEventListener("DOMContentLoaded", function () {',
' document.querySelector("#show-private").addEventListener("change", function (event) {',
' document.body.className = (event.target.checked ? "show-private" : "");',
' }, false);',
'',
' if (document.querySelector("[href=\\"" + location.hash + "\\"]").offsetHeight === 0) {',
' document.querySelector("#show-private").click()',
' }',
' }, false);',
' ]]>',
' </script>',
' </head>',
' <body>',
' <section class="namespaces">',
' <label><input type="checkbox" id="show-private" />Show private</label>',
' <h2>Namespaces</h2>'
].concat(writeOverview(3)).concat([
' </section>',
' <div class="content">',
''
]).concatMany(namespaceNames.map(function (namespaceName) {
var variables = namespaces[namespaceName].members.filter(function (value) {
return value instanceof TypeScript.AST.Variable;
});
var functions = namespaces[namespaceName].members.filter(function (value) {
return value instanceof TypeScript.AST.Function;
});
var interfaces = namespaces[namespaceName].members.filter(function (value) {
return value instanceof TypeScript.AST.Interface;
});
var constructors = namespaces[namespaceName].members.filter(function (value) {
return value instanceof TypeScript.AST.Constructor;
});
var result = [
' <section>',
' <h1 id="' + sanitize(namespaceName) + '">' + sanitize(namespaceName) + '</h1>',
''
];
if (variables.length > 0) {
result = result.concat([
' <section>',
' <h2>Variables</h2>'
]).concatMany(variables.map(function (value) {
return writeVariable(value, 5);
})).concat([
' </section>',
''
]);
}
if (functions.length > 0) {
result = result.concat([
' <section>',
' <h2>Free functions</h2>'
]).concatMany(functions.map(function (value) {
return writeFunction(value, 5);
})).concat([
' </section>',
''
]);
}
if (interfaces.length > 0) {
result = result.concat([
' <section>',
' <h2>Interfaces</h2>'
]).concatMany(interfaces.map(function (value) {
return writeInterface(value, 5);
})).concat([
' </section>',
''
]);
}
if (constructors.length > 0) {
result = result.concat([
' <section>',
' <h2>Classes</h2>'
]).concatMany(constructors.map(function (value) {
return writeConstructor(value, 5);
})).concat([
' </section>',
''
]);
}
result = result.concat([
' </section>'
]);
return result;
})).concat([
' </div>',
' </body>',
'</html>'
]).map(function (line) {
return new Buffer(line + "\n");
}))
}));
});
};
+88
View File
@@ -0,0 +1,88 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var childProcess = require("child_process");
var stream = require("stream");
var util = require("util");
var Transform = function (transform, flush) {
if (!(this instanceof Transform)) {
return new Transform(transform, flush);
}
stream.Transform.call(this, { objectMode: true });
transform = transform || function (chunk, encoding, callback) { callback(); };
if (transform.length < 3) {
this._transform = function (chunk, encoding, callback) {
try {
transform.call(this, chunk, encoding);
callback();
}
catch (ex) {
callback(ex);
}
};
}
else {
this._transform = transform.bind(this);
}
flush = flush || function (callback) { callback(); };
if (flush.length < 1) {
this._flush = function (callback) { try { flush.call(this); callback(); } catch (ex) { callback(ex); } };
}
else {
this._flush = flush.bind(this);
}
};
util.inherits(Transform, stream.Transform);
exports.Transform = Transform;
exports.SingletonChildProcess = function (filename) {
var subProcess = null;
var rerun = false;
var spawnSubProcess = function () {
subProcess = childProcess.fork(filename);
subProcess.addListener("exit", function (code, signal) {
subProcess = null;
if (rerun) {
spawnSubProcess();
}
rerun = false;
});
};
return function () {
if (subProcess === null) {
spawnSubProcess();
}
else {
rerun = true;
}
};
};
@@ -19,20 +19,23 @@
*/
var fs = require("fs");
var path = require("path");
namespace("_clean", function () {
task("run", [], function () {
console.log("[" + this.fullName + "]");
var Mocha = require("mocha");
["libjass.js", "libjass.js.map", "libjass.min.js", "libjass.min.js.map"].forEach(function (file) {
try {
fs.unlinkSync(file);
}
catch (ex) {
if (ex.code !== "ENOENT") {
throw ex;
}
}
});
});
console.log("Running tests...");
var mocha = new Mocha({
ui: "tdd",
reporter: "spec"
});
fs.readdirSync("./tests/")
.filter(function (filename) { return filename.match(/^test-.*\.js$/) !== null; })
.forEach(function (filename) { mocha.addFile(path.resolve("./tests", filename)); });
mocha.run(function (failures) {
if (failures > 0) {
throw new Error(failures + " test(s) failed.");
}
});
File diff suppressed because it is too large Load Diff
+347
View File
@@ -0,0 +1,347 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require("fs");
var path = require("path");
var UglifyJS = require("uglify-js");
var Transform = require("./helpers.js").Transform;
module.exports = {
fixup: function () {
var codeFile = null;
var sourceMapFile = null;
return Transform(function (file) {
switch (path.extname(file.path)) {
case ".js":
codeFile = file;
break;
case ".map":
sourceMapFile = file;
break;
}
if (codeFile !== null && sourceMapFile !== null) {
UglifyJS.base54.reset();
// Parse
var root = UglifyJS.parse(codeFile.contents.toString(), {
filename: path.basename(codeFile.path),
toplevel: null
});
root = root.wrap_enclose(['(typeof module !== "undefined") ? module.exports : (this.libjass = {}):libjass', '(typeof global !== "undefined") ? global : this:global']);
root.figure_out_scope({ screw_ie8: true });
// Remove some things from the AST
var nodesToRemove;
nodesToRemove = [];
// 1. All the top-level "var libjass;"
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "libjass") {
nodesToRemove.push({ node: node, parent: this.parent().body });
}
}));
// 2. All but the first top-level "var __extends = ..."
var firstVarExtendsFound = false;
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "__extends") {
if (firstVarExtendsFound === false) {
firstVarExtendsFound = true;
// Remove the check for this.__extends
node.definitions[0].value = node.definitions[0].value.right;
}
else {
nodesToRemove.push({ node: node, parent: this.parent().body });
}
}
}));
// Repeat because removing some declarations may make others unreferenced
for (;;) {
// 3. Unreferenced variable and function declarations, and unreferenced terminal function arguments
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (node instanceof UglifyJS.AST_SymbolDeclaration && node.unreferenced()) {
if (node instanceof UglifyJS.AST_SymbolFunarg) {
if (this.parent().argnames.indexOf(node) === this.parent().argnames.length - 1) {
nodesToRemove.push({ node: node, parent: this.parent().argnames });
}
}
else if (node instanceof UglifyJS.AST_SymbolVar) {
nodesToRemove.push({ node: this.parent(), parent: this.parent(1).definitions });
if (this.parent(1).definitions.length === 1) {
nodesToRemove.push({ node: this.parent(1), parent: this.parent(2).body });
}
}
else if (node instanceof UglifyJS.AST_SymbolDefun) {
nodesToRemove.push({ node: this.parent(), parent: this.parent(1).body });
}
}
}));
if (nodesToRemove.length === 0) {
break;
}
nodesToRemove.forEach(function (tuple) {
tuple.parent.splice(tuple.parent.indexOf(tuple.node), 1);
});
nodesToRemove = [];
root.figure_out_scope({ screw_ie8: true });
}
// 4. Rename all function arguments that begin with _ to not have the _.
// This converts the TypeScript syntax of declaring private members in the constructor declaration `function Color(private _red: number, ...)` to `function Color(red, ...)`
// so that it matches the JSDoc (and looks nicer).
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (
node instanceof UglifyJS.AST_SymbolFunarg &&
node.thedef.name[0] === "_" &&
node.thedef.name !== "_super" // Don't rename _super (used in TypeScript's inheritance shim) to super. super is a reserved word.
) {
node.thedef.name = node.thedef.name.slice(1);
}
}));
// Output
var firstLicenseHeaderFound = false; // To detect and preserve the first license header
var output = {
source_map: UglifyJS.SourceMap({
file: path.basename(sourceMapFile.path),
orig: sourceMapFile.contents.toString()
}),
beautify: true,
comments: function (node, comment) {
// If this is a license header
if (comment.value.indexOf("Copyright") !== -1) {
if (!firstLicenseHeaderFound) {
firstLicenseHeaderFound = true;
}
else {
// This isn't the first license header. Strip it.
return false;
}
}
// If this is a TypeScript reference comment, strip it.
if (comment.value.substr(0, "/<reference path=".length) === "/<reference path=") {
return false;
}
/* Align multi-line comments correctly.
* TypeScript shifts them one space left, and UJS shifts them four spaces left,
* so shift each line except the first five spaces right.
*/
if (comment.type === "comment2") {
var lines = comment.value.split("\n");
lines = [lines[0]].concat(lines.slice(1).map(function (line) { return ' ' + line; }));
comment.value = lines.join('\n');
}
return true;
}
};
var stream = UglifyJS.OutputStream(output);
root.print(stream);
codeFile.contents = Buffer.concat([new Buffer(stream.toString()), new Buffer("\n//# sourceMappingURL="), new Buffer(sourceMapFile.relative)]);
this.push(codeFile);
output.source_map.get()._sources.toArray().forEach(function (filename) {
output.source_map.get().setSourceContent(filename, fs.readFileSync(filename, { encoding: "utf8"}));
});
sourceMapFile.contents = new Buffer(output.source_map.toString());
this.push(sourceMapFile);
codeFile = null;
sourceMapFile = null;
}
});
},
minify: function () {
var codeFile = null;
var sourceMapFile = null;
return Transform(function (file) {
switch (path.extname(file.path)) {
case ".js":
codeFile = file;
break;
case ".map":
sourceMapFile = file;
break;
}
if (codeFile !== null && sourceMapFile !== null) {
UglifyJS.base54.reset();
// Parse
var root = null;
root = UglifyJS.parse(codeFile.contents.toString(), {
filename: path.basename(codeFile.path),
toplevel: root
});
root.figure_out_scope({ screw_ie8: true });
// Warnings
root.scope_warnings({
func_arguments: false
});
// Compress
var compressor = UglifyJS.Compressor({
warnings: true,
screw_ie8: true
});
root = root.transform(compressor);
// Mangle
root.figure_out_scope({ screw_ie8: true });
root.compute_char_frequency();
root.mangle_names({ screw_ie8: true });
// Mangle private members
var occurrences = Object.create(null);
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (
node instanceof UglifyJS.AST_PropAccess &&
typeof node.property === "string" &&
node.property[0] === "_" &&
node.property[1] !== "_" && // Doesn't start with two leading underscores
node.property !== "_classTag" // webworker serializer uses this property by name, so it shouldn't be changed.
) {
var occurrence = occurrences[node.property];
if (occurrence === undefined) {
occurrences[node.property] = 1;
}
else {
occurrences[node.property]++;
}
}
}));
var identifiers = Object.keys(occurrences);
identifiers.sort(function (first, second) { return occurrences[second] - occurrences[first]; });
var generatedIdentifiers = occurrences;
var validIdentifierCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
var toIdentifier = function (index) {
var result = validIdentifierCharacters[(index % validIdentifierCharacters.length)];
index = (index / validIdentifierCharacters.length) | 0;
while (index > 0) {
index--;
result = validIdentifierCharacters[index % validIdentifierCharacters.length] + result;
index = (index / validIdentifierCharacters.length) | 0;
}
return "_" + result;
};
identifiers.forEach(function (identifier, index) {
generatedIdentifiers[identifier] = toIdentifier(index);
});
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (
node instanceof UglifyJS.AST_PropAccess &&
typeof node.property === "string" &&
node.property in generatedIdentifiers
) {
node.property = generatedIdentifiers[node.property];
}
}));
// Output
var firstLicenseHeaderFound = false; // To detect and preserve the first license header
var output = {
source_map: UglifyJS.SourceMap({
file: path.basename(sourceMapFile.path),
orig: sourceMapFile.contents.toString()
}),
comments: {
test: function (comment) {
if (!firstLicenseHeaderFound && comment.indexOf("Copyright") !== -1) {
firstLicenseHeaderFound = true;
return true;
}
return false;
}
},
screw_ie8: true
};
var stream = UglifyJS.OutputStream(output);
root.print(stream);
codeFile.path = codeFile.path.replace(/\.js$/, ".min.js");
sourceMapFile.path = sourceMapFile.path.replace(/\.js\.map$/, ".min.js.map");
codeFile.contents = Buffer.concat([new Buffer(stream.toString()), new Buffer("\n//# sourceMappingURL="), new Buffer(sourceMapFile.relative)]);
this.push(codeFile);
output.source_map.get()._sources.toArray().forEach(function (filename) {
output.source_map.get().setSourceContent(filename, fs.readFileSync(filename, { encoding: "utf8"}));
});
sourceMapFile.contents = new Buffer(output.source_map.toString());
this.push(sourceMapFile);
codeFile = null;
sourceMapFile = null;
}
});
}
};
var originalSymbolUnreferenced = UglifyJS.AST_Symbol.prototype.unreferenced;
UglifyJS.AST_Symbol.prototype.unreferenced = function () {
if (this.start.comments_before.length > 0 && this.start.comments_before[0].value.trim() === "ujs:unreferenced") {
return false;
}
return originalSymbolUnreferenced.call(this);
};
+110 -65
View File
@@ -36,84 +36,129 @@ addEventListener("DOMContentLoaded", function () {
var ass = null;
var testVideoAndASSLoaded = function () {
if (videoMetadataLoaded && ass) {
var renderer = new libjass.renderers.DefaultRenderer(video, ass, {
fontMap: libjass.renderers.RendererSettings.makeFontMapFromStyleElement(document.querySelector("#font-map"))
});
if (videoMetadataLoaded === false || ass === null) {
return;
}
renderer.addEventListener("ready", function () {
debug("All fonts have been preloaded. Beginning autoplay.");
video.play();
});
// Both video metadata and ASS are loaded
var changeVideoSizeSelection = function (id) {
if (typeof id === "undefined") {
[].some.call(videoSizeSelector.querySelectorAll("input[name='video-size']"), function (option) {
if (option.checked) {
id = option.id;
return true;
}
// Create a DefaultRenderer using the video element, the ASS object, and the font map
var renderer = new libjass.renderers.DefaultRenderer(video, ass, {
fontMap: libjass.renderers.RendererSettings.makeFontMapFromStyleElement(document.querySelector("#font-map"))
});
return false;
});
}
if (libjass.debugMode) {
// Export the renderer for debugging
window.renderer = renderer;
}
if (id === "video-size-video-radio") {
renderer.resizeVideo(video.videoWidth, video.videoHeight);
}
// Autoplay the video when the renderer is ready
renderer.addEventListener("ready", function () {
debug("All fonts have been preloaded. Beginning autoplay.");
else if (id === "video-size-script-radio") {
renderer.resizeVideo(ass.resolutionX, ass.resolutionY);
}
};
video.play();
});
var videoSizeSelector = document.querySelector("#video-size-selector");
videoSizeSelector.addEventListener("change", function (event) { changeVideoSizeSelection(event.target.id); }, false);
renderer.addEventListener("fullScreenChange", function (newState) {
if (newState === false) {
changeVideoSizeSelection();
}
});
changeVideoSizeSelection();
};
}
if (video.readyState < HTMLMediaElement.HAVE_METADATA) {
video.addEventListener("loadedmetadata", function () {
debug("Video metadata loaded.");
videoMetadataLoaded = true;
document.querySelector("#video-resolution-label-width").appendChild(document.createTextNode(video.videoWidth));
document.querySelector("#video-resolution-label-height").appendChild(document.createTextNode(video.videoHeight));
testVideoAndASSLoaded();
document.querySelector("#enable-disable-subs").addEventListener("change", function (event) {
renderer.setEnabled(event.target.checked);
}, false);
}
else {
debug("Video metadata loaded.");
videoMetadataLoaded = true;
testVideoAndASSLoaded();
}
var track = document.querySelector("#video > track[data-format='ass']");
var subsRequest = new XMLHttpRequest();
subsRequest.open("GET", track.src || track.getAttribute("src"), true);
subsRequest.addEventListener("readystatechange", function () {
if (subsRequest.readyState === XMLHttpRequest.DONE) {
debug("ASS script received.");
// Run when the video/script resolution needs to be changed, either because the user clicked one of the resolution options,
// or because they exited full screen and their selection needs to be restored
var changeVideoSizeSelection = function (id) {
if (typeof id === "undefined") {
// Find which option is selected
ass = libjass.ASS.fromString(subsRequest.responseText);
if (libjass.debugMode) {
window.ass = ass;
[].slice.call(videoSizeSelector.querySelectorAll("input[name='video-size']")).some(function (option) {
if (option.checked) {
id = option.id;
return true;
}
return false;
});
}
document.querySelector("#script-resolution-label-width").appendChild(document.createTextNode(ass.resolutionX));
document.querySelector("#script-resolution-label-height").appendChild(document.createTextNode(ass.resolutionY));
if (id === "video-size-video-radio") {
// Resize to video resolution
testVideoAndASSLoaded();
video.style.width = video.videoWidth + "px";
video.style.height = video.videoHeight + "px";
renderer.resize(video.videoWidth, video.videoHeight);
}
else if (id === "video-size-script-radio") {
// Resize to script resolution
video.style.width = ass.properties.resolutionX + "px";
video.style.height = ass.properties.resolutionY + "px";
renderer.resize(ass.properties.resolutionX, ass.properties.resolutionY);
}
};
var videoSizeSelector = document.querySelector("#video-size-selector");
videoSizeSelector.addEventListener("change", function (event) { changeVideoSizeSelection(event.target.id); }, false);
// When video exits full screen, restore the size according to the resolution option that's selected
renderer.addEventListener("fullScreenChange", function (newState) {
if (newState === false) {
changeVideoSizeSelection();
}
});
// Set the resolution to whatever's selected by default
changeVideoSizeSelection();
};
(function (onVideoMetadataLoaded) {
if (video.readyState < HTMLMediaElement.HAVE_METADATA) {
// Video metadata isn't available yet. Register an event handler for it.
video.addEventListener("loadedmetadata", onVideoMetadataLoaded, false);
}
else {
// Video metadata is already available.
onVideoMetadataLoaded();
}
})(function () {
debug("Video metadata loaded.");
videoMetadataLoaded = true;
// Prepare the "Video resolution" option label
document.querySelector("#video-resolution-label-width").appendChild(document.createTextNode(video.videoWidth));
document.querySelector("#video-resolution-label-height").appendChild(document.createTextNode(video.videoHeight));
// Test if everything is loaded
testVideoAndASSLoaded();
});
// Find the ASS or SRT track and load it
var track = document.querySelector("#video > track[data-format='ass'], #video > track[data-format='srt']");
var subsRequest = new XMLHttpRequest();
subsRequest.open("GET", track.src || track.getAttribute("src"), true);
subsRequest.addEventListener("load", function () {
debug("Script received.");
if (libjass.debugMode) {
console.time("Parsing ASS took");
}
// Parse the response string into an ASS object
ass = libjass.ASS.fromString(subsRequest.responseText, libjass.Format[track.getAttribute("data-format").toUpperCase()]);
if (libjass.debugMode) {
console.timeEnd("Parsing ASS took");
// Export the ASS object for debugging
window.ass = ass;
}
// Prepare the "Script resolution" option label
document.querySelector("#script-resolution-label-width").appendChild(document.createTextNode(ass.properties.resolutionX));
document.querySelector("#script-resolution-label-height").appendChild(document.createTextNode(ass.properties.resolutionY));
// Test if everything is loaded
testVideoAndASSLoaded();
}, false);
subsRequest.send(null);
}, false);
+4
View File
@@ -49,6 +49,10 @@
<input type="radio" name="video-size" id="video-size-script-radio" /><label for="video-size-script-radio">Script resolution <span id="script-resolution-label-width" />x<span id="script-resolution-label-height" /></label>
</div>
</fieldset>
<fieldset>
<legend>Subtitles</legend>
<input type="checkbox" id="enable-disable-subs" checked="checked" /><label for="enable-disable-subs">Subtitles</label>
</fieldset>
</form>
</body>
</html>
-332
View File
@@ -1,332 +0,0 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require("fs");
var path = require("path");
var UglifyJS = require("uglify-js");
namespace("_default", function () {
task("typeScript", ["_typescript:getCompilerFactory"], function () {
console.log("[" + this.fullName + "]");
var Compiler = jake.Task["_typescript:getCompilerFactory"].value;
var compiler = new Compiler();
return compiler.compile(["libjass.ts"]);
});
task("fixup", ["_default:typeScript"], function () {
console.log("[" + this.fullName + "]");
var compiled = jake.Task["_default:typeScript"].value;
UglifyJS.base54.reset();
// Parse
var root = UglifyJS.parse(compiled.code, {
filename: "libjass.js",
toplevel: null
});
root = root.wrap_enclose(['((typeof module !== "undefined") && module.exports) || (this.libjass = {}):libjass', '((typeof global !== "undefined") && global) || this:global']);
root.figure_out_scope();
// Remove some things from the AST
var nodesToRemove;
nodesToRemove = [];
// 1. All the top-level "var libjass;"
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "libjass") {
nodesToRemove.push({ node: node, parent: this.parent().body });
}
}));
// 2. All but the first top-level "var __extends = ..."
var firstVarExtendsFound = false;
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (node instanceof UglifyJS.AST_Var && node.definitions[0].name.name === "__extends") {
if (firstVarExtendsFound === false) {
firstVarExtendsFound = true;
// Remove the check for this.__extends
node.definitions[0].value = node.definitions[0].value.right;
// console.log(require("util").inspect(node.definitions[0]));
// throw 5;
}
else {
nodesToRemove.push({ node: node, parent: this.parent().body });
}
}
}));
// Repeat because removing some declarations may make others unreferenced
for (;;) {
// 3. Unreferenced variable and function declarations, and unreferenced terminal function arguments
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (node instanceof UglifyJS.AST_SymbolDeclaration && node.unreferenced()) {
if (node instanceof UglifyJS.AST_SymbolFunarg) {
if (this.parent().argnames.indexOf(node) === this.parent().argnames.length - 1) {
nodesToRemove.push({ node: node, parent: this.parent().argnames });
}
}
else if (node instanceof UglifyJS.AST_SymbolVar) {
nodesToRemove.push({ node: this.parent(), parent: this.parent(1).definitions });
if (this.parent(1).definitions.length === 1) {
nodesToRemove.push({ node: this.parent(1), parent: this.parent(2).body });
}
}
else if (node instanceof UglifyJS.AST_SymbolDefun) {
nodesToRemove.push({ node: this.parent(), parent: this.parent(1).body });
}
}
}));
if (nodesToRemove.length === 0) {
break;
}
nodesToRemove.forEach(function (node) {
node.parent.splice(node.parent.indexOf(node.node), 1);
});
nodesToRemove = [];
root.figure_out_scope();
}
// Output
var firstLicenseHeaderFound = false; // To detect and preserve the first license header
var output = {
source_map: UglifyJS.SourceMap({
file: "libjass.js.map",
orig: compiled.sourceMap,
root: ""
}),
beautify: true,
comments: function (node, comment) {
// If this is a license header
if (comment.value.indexOf("Copyright") !== -1) {
if (!firstLicenseHeaderFound) {
firstLicenseHeaderFound = true;
}
else {
// This isn't the first license header. Strip it.
return false;
}
}
// If this is a TypeScript reference comment, strip it.
if (comment.value.substr(0, "/<reference path=".length) === "/<reference path=") {
return false;
}
/* Align multi-line comments correctly.
* TypeScript shifts them one space left, and UJS shifts them four spaces left,
* so shift each line except the first five spaces right.
*/
if (comment.type === "comment2") {
var lines = comment.value.split("\n");
lines = [lines[0]].concat(lines.slice(1).map(function (line) { return ' ' + line; }));
comment.value = lines.join('\n');
}
return true;
}
};
var stream = UglifyJS.OutputStream(output);
root.print(stream);
return {
code: stream.toString() + "\n//# sourceMappingURL=libjass.js.map",
sourceMap: output.source_map.toString()
};
});
task("writeCode", ["_default:fixup"], function () {
console.log("[" + this.fullName + "]");
var fixedUp = jake.Task["_default:fixup"].value;
fs.writeFileSync("libjass.js", fixedUp.code);
});
task("writeSourceMap", ["_default:fixup"], function () {
console.log("[" + this.fullName + "]");
var fixedUp = jake.Task["_default:fixup"].value;
fs.writeFileSync("libjass.js.map", fixedUp.sourceMap);
});
task("minify", ["_default:fixup"], function () {
console.log("[" + this.fullName + "]");
var fixedUp = jake.Task["_default:fixup"].value;
UglifyJS.base54.reset();
// Parse
var root = null;
root = UglifyJS.parse(fixedUp.code, {
filename: "libjass.js",
toplevel: root
});
root.figure_out_scope();
// Suppress some warnings
var originalWarn = UglifyJS.AST_Node.warn;
UglifyJS.AST_Node.warn = function (text, properties) {
if (
(text === "Couldn't figure out mapping for {file}:{line},{col} \u2192 {cline},{ccol} [{name}]" && properties.file === "libjass.js" && properties.line === 1 && properties.col === 0 && properties.cline === 1 && properties.ccol === 1)
) {
return;
}
originalWarn.call(UglifyJS.AST_Node, text, properties);
};
// Warnings
root.scope_warnings({
func_arguments: false
});
// Compress
var compressor = UglifyJS.Compressor({
warnings: true
});
root = root.transform(compressor);
// Mangle
root.figure_out_scope();
root.compute_char_frequency();
root.mangle_names();
// Mangle private members
var occurrences = Object.create(null);
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (
node instanceof UglifyJS.AST_PropAccess &&
typeof node.property === "string" &&
node.property[0] === "_" && node.property[1] !== "_"
) {
var occurrence = occurrences[node.property];
if (occurrence === undefined) {
occurrences[node.property] = 1;
}
else {
occurrences[node.property]++;
}
}
}));
var identifiers = Object.keys(occurrences);
identifiers.sort(function (first, second) { return occurrences[second] - occurrences[first]; });
var generatedIdentifiers = occurrences;
var validIdentifierCharacters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
var toIdentifier = function (index) {
var result = validIdentifierCharacters[(index % validIdentifierCharacters.length)];
index = (index / validIdentifierCharacters.length) | 0;
while (index > 0) {
index--;
result = validIdentifierCharacters[index % validIdentifierCharacters.length] + result;
index = (index / validIdentifierCharacters.length) | 0;
}
return "_" + result;
};
identifiers.forEach(function (identifier, index) {
generatedIdentifiers[identifier] = toIdentifier(index);
});
root.walk(new UglifyJS.TreeWalker(function (node, descend) {
if (
node instanceof UglifyJS.AST_PropAccess &&
typeof node.property === "string" &&
node.property in generatedIdentifiers
) {
node.property = generatedIdentifiers[node.property];
}
}));
// Output
var firstLicenseHeaderFound = false; // To detect and preserve the first license header
var output = {
source_map: UglifyJS.SourceMap({
file: "libjass.min.js.map",
orig: fixedUp.sourceMap,
root: ""
}),
comments: {
test: function (comment) {
if (!firstLicenseHeaderFound && comment.indexOf("Copyright") !== -1) {
firstLicenseHeaderFound = true;
return true;
}
return false;
}
}
};
var stream = UglifyJS.OutputStream(output);
root.print(stream);
return {
code: stream.toString() + "\n//# sourceMappingURL=libjass.min.js.map",
sourceMap: output.source_map.toString()
};
});
task("writeMinifiedCode", ["_default:minify"], function () {
console.log("[" + this.fullName + "]");
var minified = jake.Task["_default:minify"].value;
fs.writeFileSync("libjass.min.js", minified.code);
});
task("writeMinifiedSourceMap", ["_default:minify"], function () {
console.log("[" + this.fullName + "]");
var minified = jake.Task["_default:minify"].value;
fs.writeFileSync("libjass.min.js.map", minified.sourceMap);
});
});
-1149
View File
File diff suppressed because it is too large Load Diff
-78
View File
@@ -1,78 +0,0 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var path = require("path");
var Mocha = require("mocha");
namespace("_test", function () {
task("run", ["clean", "_default:writeCode"], function (failTaskOnFailure) {
console.log("[" + this.fullName + "]");
failTaskOnFailure = (failTaskOnFailure === true) || (failTaskOnFailure === "true");
var mocha = new Mocha({
ui: "tdd",
reporter: "spec",
loadInNewContext: !failTaskOnFailure
});
(new jake.FileList("./tests/test-*.js")).toArray().forEach(function (filename) {
mocha.addFile(filename);
});
mocha.run(function (failures) {
if (failTaskOnFailure && failures > 0) {
fail(failures + " test(s) failed.");
}
complete();
});
}, { async: true });
});
Mocha.prototype.loadFiles = function (fn){
var self = this;
var suite = this.suite;
var pending = this.files.length;
this.files.forEach(function(file){
file = path.resolve(file);
suite.emit('pre-require', global, file, self);
var fileExports;
if (!self.options.loadInNewContext) {
fileExports = require(file);
}
else {
var filePathAsJsString = file.replace(/\\/g, "\\\\");
var newContextScript = 'var module = new Module("' + filePathAsJsString + '"); module.load("' + filePathAsJsString + '"); module.exports';
fileExports = require('vm').runInNewContext(newContextScript, {
Module: module.constructor,
process: process
});
}
suite.emit('require', fileExports, file, self);
suite.emit('post-require', global, file, self);
--pending || (fn && fn());
});
};
-185
View File
@@ -1,185 +0,0 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var fs = require("fs");
var path = require("path");
var UglifyJS = require("uglify-js");
var typeScriptModulePath = path.resolve("./node_modules/typescript/bin");
var typeScriptJsPath = path.join(typeScriptModulePath, "typescript.js");
var makeCompilerFunction = function (TypeScript) {
var Compiler = function () {
this.mutableSettings = new TypeScript.CompilationSettings();
this.mutableSettings.codeGenTarget = TypeScript.LanguageVersion.EcmaScript5;
this.mutableSettings.mapSourceFiles = true;
this.mutableSettings.noImplicitAny = true;
};
Compiler.prototype.compile = function (inputFilenames) {
console.log("Compiling " + JSON.stringify(inputFilenames) + "...");
this.mutableSettings.outFileOption = "output.js";
try {
var run = new CompilerRun();
var resolutionResults = TypeScript.ReferenceResolver.resolve(inputFilenames, {
resolveRelativePath: function (file, directory) {
return path.resolve(directory, file);
},
fileExists: fs.existsSync.bind(fs),
getScriptSnapshot: run.getScriptSnapshot.bind(run),
getParentDirectory: path.dirname.bind(path)
}, true);
var resolvedFiles = resolutionResults.resolvedFiles;
resolvedFiles.unshift({
path: path.resolve(typeScriptModulePath, "lib.d.ts"),
referencedFiles: [],
importedFiles: []
});
run.addDiagnostics(resolutionResults.diagnostics);
var compiler = new TypeScript.TypeScriptCompiler(new TypeScript.NullLogger(), TypeScript.ImmutableCompilationSettings.fromCompilationSettings(this.mutableSettings));
resolvedFiles.forEach(function (resolvedFile) {
var scriptSnapshot = run.getScriptSnapshot(resolvedFile.path);
compiler.addFile(resolvedFile.path, scriptSnapshot, 0, 0, false, resolvedFile.referencedFiles);
});
var iterator = compiler.compile(path.resolve.bind(path));
var compilerOutput = Object.create(null);
while (iterator.moveNext()) {
var result = iterator.current();
run.addDiagnostics(result.diagnostics);
result.outputFiles.forEach(function (outputFile) {
switch (outputFile.fileType) {
case TypeScript.OutputFileType.JavaScript:
compilerOutput.code = outputFile.text;
break;
case TypeScript.OutputFileType.SourceMap:
compilerOutput.sourceMap = outputFile.text;
break;
}
});
}
if (run.diagnostics.some(function (diagnostic) { return diagnostic.info().category === 1; })) {
throw new Error("There were one or more errors.");
}
console.log("Compile succeeded.");
return compilerOutput;
}
catch (ex) {
if (ex instanceof Error) {
throw ex;
}
else {
throw new Error("Internal compiler error: " + ex.stack + "\n");
}
}
};
var CompilerRun = function () {
this.diagnostics = [];
this._scriptSnapshots = Object.create(null);
};
CompilerRun.prototype.addDiagnostics = function (newDiagnostics) {
newDiagnostics.forEach(function (diagnostic) {
var message = diagnostic.message();
if (diagnostic.fileName()) {
message = diagnostic.fileName() + "(" + (diagnostic.line() + 1) + "," + (diagnostic.character() + 1) + "): " + message;
}
console.error(message);
});
this.diagnostics.push.apply(this.diagnostics, newDiagnostics);
};
CompilerRun.prototype.getScriptSnapshot = function (filename) {
var scriptSnapshot = this._scriptSnapshots[filename];
if (!scriptSnapshot) {
var fileContents;
try {
fileContents = fs.readFileSync(filename, { encoding: "utf8" });
}
catch (ex) {
run.addDiagnostics([new TypeScript.Diagnostic(null, null, 0, 0, TypeScript.DiagnosticCode.Cannot_read_file_0_1, [filename, ex.message])]);
fileContents = "";
}
var scriptSnapshot = TypeScript.ScriptSnapshot.fromString(fileContents);
this._scriptSnapshots[filename] = scriptSnapshot;
}
return scriptSnapshot;
};
return Compiler;
};
namespace("_typescript", function () {
task("require", [], function () {
console.log("[" + this.fullName + "]");
var vm = require("vm");
var data = fs.readFileSync(typeScriptJsPath, { encoding: "utf8" });
data += "module.exports = TypeScript;";
var TypeScript = {};
vm.runInNewContext(data, {
module: Object.defineProperty(Object.create(null), "exports", {
get: function () { return TypeScript; },
set: function (value) { TypeScript = value; }
}),
require: require,
process: process,
__filename: typeScriptJsPath,
__dirname: typeScriptModulePath
});
return TypeScript;
});
task("getCompilerFactory", ["_typescript:require"], function () {
console.log("[" + this.fullName + "]");
var TypeScript = jake.Task["_typescript:require"].value;
return makeCompilerFunction(TypeScript);
});
});
-84
View File
@@ -1,84 +0,0 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var childProcess = require("child_process");
var fs = require("fs");
var path = require("path");
namespace("_watch", function () {
task("runTask", ["_test:run[false]", "_default:writeSourceMap"], function () { });
task("run", [], function () {
console.log("[" + this.fullName + "]");
var spawnSubProcess = function () {
var pathToJake = path.resolve("./node_modules/.bin/jake");
var subProcess = childProcess.exec(pathToJake + " _watch:runUntilError --trace");
subProcess.stdout.pipe(process.stdout);
subProcess.stderr.pipe(process.stderr);
subProcess.addListener("exit", function (code, signal) {
spawnSubProcess();
});
};
spawnSubProcess();
}, { async: true });
task("runUntilError", ["_typescript:getCompilerFactory"], function () {
console.log("[" + this.fullName + "]");
var tasksToReEnable = [];
var stack = ["_watch:runTask"];
while (stack.length > 0) {
var next = stack.shift();
if (next.indexOf("[") !== -1) {
next = next.substr(0, next.indexOf("["));
}
if (next !== "_typescript:getCompilerFactory" && tasksToReEnable.indexOf(jake.Task[next]) === -1) {
tasksToReEnable.push(jake.Task[next]);
stack.push.apply(stack, jake.Task[next].prereqs);
}
}
var timeoutId = null;
fs.watch(".", function (event, filename) {
if (filename === null) {
return;
}
var extension = path.extname(filename);
if (extension !== ".ts") {
return;
}
console.log(event, filename, JSON.stringify([].slice.call(arguments, 0)));
clearTimeout(timeoutId);
timeoutId = setTimeout(function () {
tasksToReEnable.forEach(function (task) { task.reenable(); });
jake.Task["_watch:runTask"].invoke();
}, 1000);
});
});
});
+36 -45
View File
@@ -20,6 +20,7 @@
.libjass-wrapper {
position: relative;
overflow: hidden;
}
.libjass-wrapper.libjass-full-screen {
@@ -33,13 +34,6 @@
.libjass-subs, .libjass-subs * {
pointer-events: none;
-webkit-animation-fill-mode: both !important;
animation-fill-mode: both !important;
}
.libjass-subs > * {
position: absolute;
width: 100%;
}
.libjass-subs.paused * {
@@ -47,64 +41,61 @@
animation-play-state: paused !important;
}
.an1, .an2, .an3 {
.libjass-subs .an {
position: absolute;
}
.libjass-subs .an1, .libjass-subs .an2, .libjass-subs .an3 {
bottom: 0;
}
.an4, .an5, .an6 {
.libjass-subs .an4, .libjass-subs .an5, .libjass-subs .an6 {
display: table;
width: 100%;
height: 100%;
}
.an4 > *, .an5 > *, .an6 > * {
.libjass-subs .an4 > *, .libjass-subs .an5 > *, .libjass-subs .an6 > * {
display: table-cell;
top: 50%;
vertical-align: middle;
}
.an7, .an8, .an9 {
.libjass-subs .an7, .libjass-subs .an8, .libjass-subs .an9 {
top: 0;
}
.libjass-subs span {
white-space: pre-wrap;
.libjass-subs .an1, .libjass-subs .an4, .libjass-subs .an7 {
text-align: left;
}
.libjass-subs div {
.libjass-subs .an2, .libjass-subs .an5, .libjass-subs .an8 {
text-align: center;
}
.libjass-subs .an3, .libjass-subs .an6, .libjass-subs .an9 {
text-align: right;
}
.libjass-subs {
line-height: 0;
}
@-webkit-keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
/* Filter wrapper span */
.libjass-subs div[data-dialogue-id] {
-webkit-perspective-origin: center;
-webkit-perspective: 200px;
perspective-origin: center;
perspective: 200px;
}
@keyframes fade-in {
from {
opacity: 0;
}
to {
opacity: 1;
}
.libjass-font-measure {
position: absolute;
visibility: hidden;
border: 0;
margin: 0;
padding: 0;
}
@-webkit-keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
@keyframes fade-out {
from {
opacity: 1;
}
to {
opacity: 0;
}
.libjass-filters {
display: block;
}
+5 -1
View File
@@ -19,7 +19,11 @@
*/
///<reference path="utility.ts" />
///<reference path="web-worker.ts" />
///<reference path="parts.ts" />
///<reference path="parser.ts" />
///<reference path="renderer.ts" />
///<reference path="renderers-clocks.ts" />
///<reference path="renderers-null.ts" />
///<reference path="renderers-web.ts" />
///<reference path="renderers-default.ts" />
///<reference path="types.ts" />
+9 -8
View File
@@ -1,6 +1,6 @@
{
"name": "libjass",
"version": "0.5.0",
"version": "0.9.0",
"description": "A library to render ASS subtitles on HTML5 video in the browser.",
"keywords": ["browser", "html5", "subtitles"],
"homepage": "https://github.com/Arnavion/libjass",
@@ -8,7 +8,7 @@
"url": "https://github.com/Arnavion/libjass/issues"
},
"licenses": [{
"type": "Apache 2.0",
"type": "Apache-2.0",
"url": "http://www.apache.org/licenses/LICENSE-2.0.html"
}],
"maintainers": [{
@@ -20,13 +20,14 @@
"url": "https://github.com/Arnavion/libjass"
},
"scripts": {
"postinstall": "jake clean && jake --trace",
"test": "jake test"
"postinstall": "gulp clean default",
"test": "node ./gulplib/test-runner.js"
},
"dependencies": {
"jake": "latest",
"mocha": "1.17.x",
"typescript": "0.9.5",
"uglify-js": "2.x"
"gulp": "latest",
"mocha": "1.21.x",
"typescript": "1.0.1",
"uglify-js": "2.x >=2.4.14",
"vinyl": "latest"
}
}
+569 -305
View File
File diff suppressed because it is too large Load Diff
+1379 -1659
View File
File diff suppressed because it is too large Load Diff
+445
View File
@@ -0,0 +1,445 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
///<reference path="libjass.ts" />
module libjass.renderers {
/**
* A mixin class that represents an event source.
*
* @template T
*/
export class EventSource<T> {
_eventListeners: Map<T, Function[]>;
/**
* Add a listener for the given event.
*
* @param {!T} type The type of event to attach the listener for
* @param {!Function} listener The listener
*/
addEventListener(type: T, listener: Function): void {
var listeners = this._eventListeners.get(type);
if (listeners === undefined) {
this._eventListeners.set(type, listeners = []);
}
listeners.push(listener);
}
/**
* @param {!T} type The type of event to dispatch
* @param {!Array.<*>} args Arguments for the listeners of the event
*/
_dispatchEvent(type: T, args: Object[]): void {
var listeners = this._eventListeners.get(type);
if (listeners !== undefined) {
listeners.forEach((listener: Function) => {
listener.apply(this, args);
});
}
}
}
export enum ClockEvent {
Play,
Tick,
Pause,
Stop,
}
export interface Clock extends EventSource<ClockEvent> {
/**
* @type {number}
*/
currentTime: number;
/**
* @type {boolean}
*/
enabled: boolean;
/**
* Enable the clock.
*
* @return {boolean} True if the clock is now enabled, false if it was already enabled.
*/
enable(): boolean;
/**
* Disable the clock.
*
* @return {boolean} True if the clock is now disabled, false if it was already disabled.
*/
disable(): boolean;
/**
* Toggle the clock.
*/
toggle(): void;
/**
* Enable or disable the clock.
*
* @param {boolean} enabled If true, the clock is enabled, otherwise it's disabled.
* @return {boolean} True if the clock is now in the given state, false if it was already in that state.
*/
setEnabled(enabled: boolean): boolean;
// EventSource members
addEventListener: (type: ClockEvent, listener: Function) => void;
}
/**
* An implementation of libjass.renderers.Clock that allows user script to manually trigger play, pause and timeUpdate events.
*/
export class ManualClock implements Clock {
private _currentTime: number = -1;
private _enabled: boolean = true;
/**
* Trigger a ClockEvent.Play
*/
play(): void {
this._dispatchEvent(ClockEvent.Play, []);
}
/**
* Trigger a ClockEvent.Tick
*
* @param {number} currentTime
*/
tick(currentTime: number): void {
this._currentTime = currentTime;
this._dispatchEvent(ClockEvent.Tick, []);
}
/**
* Trigger a ClockEvent.Pause
*/
pause(): void {
this._dispatchEvent(ClockEvent.Pause, []);
}
/**
* Trigger a ClockEvent.Stop
*/
stop(): void {
this._dispatchEvent(ClockEvent.Stop, []);
}
// Clock members
/**
* @type {number}
*/
get currentTime(): number {
return this._currentTime;
}
/**
* @type {boolean}
*/
get enabled(): boolean {
return this._enabled;
}
/**
* Enable the clock.
*
* @return {boolean} True if the clock is now enabled, false if it was already enabled.
*/
enable(): boolean {
if (this._enabled) {
return false;
}
this._enabled = true;
return true;
}
/**
* Disable the clock.
*
* @return {boolean} True if the clock is now disabled, false if it was already disabled.
*/
disable(): boolean {
if (!this._enabled) {
return false;
}
this._enabled = false;
return true;
}
/**
* Toggle the clock.
*/
toggle(): void {
if (this._enabled) {
this.disable();
}
else {
this.enable();
}
}
/**
* Enable or disable the clock.
*
* @param {boolean} enabled If true, the clock is enabled, otherwise it's disabled.
* @return {boolean} True if the clock is now in the given state, false if it was already in that state.
*/
setEnabled(enabled: boolean): boolean {
if (enabled) {
return this.enable();
}
else {
return this.disable();
}
}
// EventSource members
_eventListeners: Map<ClockEvent, Function[]> = new Map<ClockEvent, Function[]>();
addEventListener: (type: ClockEvent, listener: Function) => void;
_dispatchEvent: (type: ClockEvent, args: Object[]) => void;
}
mixin(ManualClock, [EventSource]);
enum VideoState {
Playing = 0,
Paused = 1,
}
/**
* An implementation of libjass.renderers.Clock that generates play, pause and timeUpdate events according to the state of a <video> element.
*
* @param {!HTMLVideoElement} video
*/
export class VideoClock implements Clock {
private _currentTime: number = -1;
private _enabled: boolean = true;
private _videoState: VideoState;
private _nextAnimationFrameRequestId: number = null;
constructor(private _video: HTMLVideoElement) {
this._video.addEventListener("playing", () => this._onVideoPlaying(), false);
this._video.addEventListener("pause", () => this._onVideoPause(), false);
this._video.addEventListener("seeking", () => this._onVideoSeeking(), false);
}
// Clock members
/**
* @type {number}
*/
get currentTime(): number {
return this._currentTime;
}
/**
* @type {boolean}
*/
get enabled(): boolean {
return this._enabled;
}
/**
* Enable the clock.
*
* @return {boolean} True if the clock is now enabled, false if it was already enabled.
*/
enable(): boolean {
if (this._enabled) {
return false;
}
if (this._videoState !== VideoState.Paused) {
if (libjass.debugMode) {
console.warn("VideoClock.enable: Abnormal state detected. VideoClock._videoState should have been VideoState.Paused");
}
}
this._enabled = true;
this._startTicking();
return true;
}
/**
* Disable the clock.
*
* @return {boolean} True if the clock is now disabled, false if it was already disabled.
*/
disable(): boolean {
if (!this._enabled) {
return false;
}
if (this._videoState === VideoState.Playing) {
this._videoState = VideoState.Paused;
this._dispatchEvent(ClockEvent.Pause, []);
}
this._enabled = false;
this._dispatchEvent(ClockEvent.Stop, []);
this._stopTicking();
return true;
}
/**
* Toggle the clock.
*/
toggle(): void {
if (this._enabled) {
this.disable();
}
else {
this.enable();
}
}
/**
* Enable or disable the clock.
*
* @param {boolean} enabled If true, the clock is enabled, otherwise it's disabled.
* @return {boolean} True if the clock is now in the given state, false if it was already in that state.
*/
setEnabled(enabled: boolean): boolean {
if (enabled) {
return this.enable();
}
else {
return this.disable();
}
}
private _onVideoPlaying(): void {
if (!this._enabled) {
return;
}
if (this._videoState === VideoState.Playing) {
return;
}
this._startTicking();
}
private _onVideoPause(): void {
if (!this._enabled) {
return;
}
if (this._videoState === VideoState.Paused) {
return;
}
this._videoState = VideoState.Paused;
this._dispatchEvent(ClockEvent.Pause, []);
if (this._nextAnimationFrameRequestId === null) {
if (libjass.debugMode) {
console.warn("VideoClock._onVideoPause: Abnormal state detected. VideoClock._nextAnimationFrameRequestId should not have been null");
}
return;
}
this._stopTicking();
}
private _onVideoSeeking(): void {
if (!this._enabled) {
return;
}
if (this._videoState === VideoState.Playing) {
this._videoState = VideoState.Paused;
this._dispatchEvent(ClockEvent.Pause, []);
}
if (this._currentTime === this._video.currentTime) {
return;
}
this._currentTime = this._video.currentTime;
this._dispatchEvent(ClockEvent.Tick, []);
}
private _onTimerTick(): void {
if (!this._enabled) {
return;
}
if (this._videoState === VideoState.Playing) {
if (this._currentTime !== this._video.currentTime) {
this._currentTime = this._video.currentTime;
this._dispatchEvent(ClockEvent.Tick, []);
}
else {
this._videoState = VideoState.Paused;
this._dispatchEvent(ClockEvent.Pause, []);
}
}
else {
if (this._currentTime !== this._video.currentTime) {
this._currentTime = this._video.currentTime;
this._videoState = VideoState.Playing;
this._dispatchEvent(ClockEvent.Play, []);
this._dispatchEvent(ClockEvent.Tick, []);
}
}
this._nextAnimationFrameRequestId = requestAnimationFrame(() => this._onTimerTick());
}
private _startTicking(): void {
if (this._nextAnimationFrameRequestId === null) {
this._nextAnimationFrameRequestId = requestAnimationFrame(() => this._onTimerTick());
}
}
private _stopTicking(): void {
if (this._nextAnimationFrameRequestId !== null) {
cancelAnimationFrame(this._nextAnimationFrameRequestId);
this._nextAnimationFrameRequestId = null;
}
}
// EventSource members
_eventListeners: Map<ClockEvent, Function[]> = new Map<ClockEvent, Function[]>();
addEventListener: (type: ClockEvent, listener: Function) => void;
_dispatchEvent: (type: ClockEvent, args: Object[]) => void;
}
mixin(VideoClock, [EventSource]);
}
+88
View File
@@ -0,0 +1,88 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
///<reference path="libjass.ts" />
interface Document {
fullscreenElement: Element;
mozFullScreenElement: Element;
webkitFullscreenElement: Element;
}
module libjass.renderers {
/**
* A default renderer implementation.
*
* @param {!HTMLVideoElement} video
* @param {!libjass.ASS} ass
* @param {!libjass.renderers.RendererSettings} settings
*/
export class DefaultRenderer extends WebRenderer {
private _videoIsFullScreen: boolean = false;
constructor(private _video: HTMLVideoElement, ass: ASS, settings: RendererSettings) {
super(ass, new VideoClock(_video), settings, document.createElement("div"));
this._video.parentElement.replaceChild(this.libjassSubsWrapper, this._video);
this.libjassSubsWrapper.insertBefore(this._video, this.libjassSubsWrapper.firstElementChild);
}
/**
* @deprecated
*/
resizeVideo(width: number, height: number): void {
console.warn("`DefaultRenderer.resizeVideo(width, height)` has been deprecated. Use `DefaultRenderer.resize(width, height)` instead.");
this.resize(width, height);
}
_ready(): void {
document.addEventListener("mozfullscreenchange", event => this._onFullScreenChange(document.mozFullScreenElement), false);
document.addEventListener("webkitfullscreenchange", event => this._onFullScreenChange(document.webkitFullscreenElement), false);
document.addEventListener("fullscreenchange", event => this._onFullScreenChange(document.fullscreenElement), false);
this.resize(this._video.offsetWidth, this._video.offsetHeight);
super._ready();
}
private _onFullScreenChange(fullScreenElement: Element) {
if (fullScreenElement === undefined) {
fullScreenElement = document.msFullscreenElement;
}
if (fullScreenElement === this._video) {
this.libjassSubsWrapper.classList.add("libjass-full-screen");
this.resize(screen.width, screen.height);
this._videoIsFullScreen = true;
this._dispatchEvent("fullScreenChange", [this._videoIsFullScreen]);
}
else if (fullScreenElement === null && this._videoIsFullScreen) {
this.libjassSubsWrapper.classList.remove("libjass-full-screen");
this._videoIsFullScreen = false;
this._dispatchEvent("fullScreenChange", [this._videoIsFullScreen]);
}
}
}
}
+280
View File
@@ -0,0 +1,280 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
///<reference path="libjass.ts" />
module libjass.renderers {
/**
* A renderer implementation that doesn't output anything.
*
* @param {!libjass.ASS} ass
* @param {!libjass.renderers.Clock} clock
* @param {!libjass.renderers.RendererSettings} settings
*/
export class NullRenderer {
private static _lastRendererId = -1;
private _id: number;
private _settings: RendererSettings;
constructor(private _ass: ASS, private _clock: Clock, settings: RendererSettings) {
this._id = ++NullRenderer._lastRendererId;
this._settings = RendererSettings.from(settings);
this._clock.addEventListener(ClockEvent.Play, () => this._onClockPlay());
this._clock.addEventListener(ClockEvent.Tick, () => this._onClockTick());
this._clock.addEventListener(ClockEvent.Pause, () => this._onClockPause());
this._clock.addEventListener(ClockEvent.Stop, () => this._onClockStop());
}
/**
* The unique ID of this renderer. Auto-generated.
*
* @type {number}
*/
get id(): number {
return this._id;
}
/**
* @type {!libjass.ASS}
*/
get ass(): ASS {
return this._ass;
}
/**
* @type {!libjass.renderers.Clock}
*/
get clock(): Clock {
return this._clock;
}
/**
* @type {!libjass.renderers.RendererSettings}
*/
get settings(): RendererSettings {
return this._settings;
}
/**
* Pre-render a dialogue. This is a no-op for this type.
*
* @param {!libjass.Dialogue} dialogue
*/
preRender(dialogue: Dialogue): void { }
/**
* Draw a dialogue. This is a no-op for this type.
*
* @param {!libjass.Dialogue} dialogue
*/
draw(dialogue: Dialogue): void { }
/**
* Enable the renderer.
*
* @return {boolean} True if the renderer is now enabled, false if it was already enabled.
*/
enable(): boolean {
return this._clock.enable();
}
/**
* Disable the renderer.
*
* @return {boolean} True if the renderer is now disabled, false if it was already disabled.
*/
disable(): boolean {
return this._clock.disable();
}
/**
* Toggle the renderer.
*/
toggle(): void {
this._clock.toggle();
}
/**
* Enable or disable the renderer.
*
* @param {boolean} enabled If true, the renderer is enabled, otherwise it's disabled.
* @return {boolean} True if the renderer is now in the given state, false if it was already in that state.
*/
setEnabled(enabled: boolean): boolean {
return this._clock.setEnabled(enabled);
}
/**
* @type {boolean}
*/
get enabled(): boolean {
return this._clock.enabled;
}
/**
* Runs when the clock is enabled, or starts playing, or is resumed from pause.
*/
_onClockPlay(): void {
if (libjass.verboseMode) {
console.log("NullRenderer._onClockPlay");
}
}
/**
* Runs when the clock's current time changed. This might be a result of either regular playback or seeking.
*/
_onClockTick(): void {
var currentTime = this._clock.currentTime;
if (libjass.verboseMode) {
console.log("NullRenderer._onClockTick: currentTime = " + currentTime);
}
for (var i = 0; i < this._ass.dialogues.length; i++) {
var dialogue = this._ass.dialogues[i];
if (dialogue.end > currentTime) {
if (dialogue.start <= currentTime) {
// This dialogue is visible right now. Draw it.
this.draw(dialogue);
}
else if (dialogue.start <= (currentTime + this._settings.preRenderTime)) {
// This dialogue will be visible soon. Pre-render it.
this.preRender(dialogue);
}
}
}
}
/**
* Runs when the clock is paused.
*/
_onClockPause(): void {
if (libjass.verboseMode) {
console.log("NullRenderer._onClockPause");
}
}
/**
* Runs when the clock is disabled.
*/
_onClockStop(): void {
if (libjass.verboseMode) {
console.log("NullRenderer._onClockStop");
}
}
}
/**
* Settings for the renderer.
*/
export class RendererSettings {
/**
* A map of font name to one or more URLs of that font. If provided, the fonts in this map are pre-loaded by the WebRenderer when it's created.
*
* If you have a <style> or <link> element on the page containing @font-face rules, you can use the RendererSettings.makeFontMapFromStyleElement() convenience method to create a font map.
*
* @type {!Map.<string, !Array.<string>>}
*/
fontMap: Map<string, string[]>;
/**
* Subtitles will be pre-rendered for this amount of time (seconds).
*
* Defaults to 5.
*
* @type {number}
*/
preRenderTime: number;
/**
* Subtitle outlines will be rendered in full detail. When false, the value of blur is used to draw less outlines for better performance and (hopefully) similar output.
*
* Defaults to false.
*
* @type {boolean}
*/
preciseOutlines: boolean;
/**
* A convenience method to create a font map from a <style> or <link> element that contains @font-face rules.
*
* @param {!LinkStyle} linkStyle
* @return {!Map.<string, !Array.<string>>}
*/
static makeFontMapFromStyleElement(linkStyle: LinkStyle): Map<string, string[]> {
var map = new Map<string, string[]>();
var styleSheet = <CSSStyleSheet>linkStyle.sheet;
var rules: CSSFontFaceRule[] = Array.prototype.filter.call(styleSheet.cssRules, (rule: CSSRule) => rule.type === CSSRule.FONT_FACE_RULE);
rules.forEach((rule: CSSFontFaceRule) => {
var src = rule.style.getPropertyValue("src");
var urls: string[] = [];
if (!src) {
src = rule.cssText.split("\n")
.map((line: string) => line.match(/src: ([^;]+);/))
.filter((matches: string[]) => matches !== null)
.map((matches: string[]) => matches[1])[0];
}
urls = src.split(/,\s*/).map((url: string) => url.match(/^url\((.+)\)$/)[1]);
if (urls.length > 0) {
var name = RendererSettings._stripQuotes(rule.style.getPropertyValue("font-family"));
var existingList = map.get(name);
if (existingList === undefined) {
existingList = [];
map.set(name, existingList);
}
existingList.unshift.apply(existingList, urls.map(RendererSettings._stripQuotes));
}
});
return map;
}
/**
* Converts an arbitrary object into a RendererSettings object.
*
* @param {!*} object
* @return {!libjass.renderers.RendererSettings}
*/
static from(object: any): RendererSettings {
return RendererSettings._from(object.fontMap, object.preRenderTime, object.preciseOutlines);
}
private static _from(fontMap: Map<string, string[]> = null, preRenderTime: number = 5, preciseOutlines: boolean = false): RendererSettings {
var result = new RendererSettings();
result.fontMap = fontMap;
result.preRenderTime = preRenderTime;
result.preciseOutlines = preciseOutlines;
return result;
}
private static _stripQuotes(str: string): string {
return str.match(/^["']?(.*?)["']?$/)[1];
}
}
}
File diff suppressed because it is too large Load Diff
+77 -18
View File
@@ -48,6 +48,8 @@ var require = function (name) {
var Suite = function (name, parent) {
this.name = name;
this.setup = function () { };
this.children = [];
this.parent = parent;
@@ -98,12 +100,25 @@ var require = function (name) {
}, enumerable: true },
});
Suite.prototype.run = function (logger) {
Suite.prototype.run = function (logger, done) {
var _this = this;
logger.beginSuite(this);
this.children.forEach(function (child) { child.run(logger); });
this.setup();
logger.endSuite(this);
var remainingChildren = this.children.slice();
var runChild = function () {
if (remainingChildren.length > 0) {
var nextChild = remainingChildren.shift();
nextChild.run(logger, runChild);
}
else {
logger.endSuite(_this);
done();
}
};
runChild();
};
var Test = function (description, body, parent) {
@@ -118,21 +133,49 @@ var require = function (name) {
this.exception = null;
};
Test.prototype.run = function (logger) {
Test.prototype.run = function (logger, done) {
if (this.body) {
this.passed = false;
try {
this.body();
if (this.body.length === 0) {
try {
this.body();
this.passed = true;
this.passed = true;
}
catch (testException) {
this.exception = testException;
}
logger.writeTest(this);
done();
}
catch (testException) {
this.exception = testException;
else {
try {
var _this = this;
this.body(function (testException) {
if (testException !== undefined && testException !== null) {
_this.exception = testException;
}
else {
_this.passed = true;
}
logger.writeTest(_this);
done();
});
}
catch (testException) {
this.exception = testException;
logger.writeTest(this);
done();
}
}
}
logger.writeTest(this);
};
var currentSuite = null;
@@ -147,6 +190,10 @@ var require = function (name) {
return newSuite;
};
setup = function (body) {
currentSuite.setup = body;
}
test = function (description, body) {
return new Test(description, body, currentSuite);
};
@@ -154,12 +201,16 @@ var require = function (name) {
var assert = new function () {
this.deepEqual = function (actual, expected) {
if (expected === undefined && actual === undefined) {
return;
}
if (expected === undefined) {
throw new Error("Expected should not be undefined");
throw new Error("Expected undefined but got [" + actual + "]");
}
if (actual === undefined) {
throw new Error("Actual should not be undefined");
throw new Error("Expected [" + expected + "] but got undefined")
}
if (expected === null && actual === null) {
@@ -174,7 +225,7 @@ var assert = new function () {
throw new Error("Expected [" + expected + "] but got null")
}
if (expected.constructor !== actual.constructor) {
if (expected.constructor !== actual.constructor && actual.constructor !== undefined) {
throw new Error("Expected value of type [" + expected.constructor.name + "] but got value of type [" + actual.constructor.name + "].");
}
@@ -280,7 +331,7 @@ var Logger = function (outputDiv) {
this.writeTest = function (test) {
if (test.passed === true) {
var message = "Test " + test.number + " - \"" + test.description + "\" - " + test.customProperties.rule + " [ " + test.customProperties.input + " ] ";
var message = "Test " + test.number + " - \"" + test.description + "\" - " + test.customProperties.rule + " [ " + test.customProperties.input + " ]";
console.log(message);
append(testDiv, message).className += " passed";
}
@@ -341,7 +392,15 @@ var Logger = function (outputDiv) {
addEventListener("DOMContentLoaded", function () {
var logger = new Logger(document.querySelector("#output"));
rootSuites.forEach(function (suite) { suite.run(logger); });
logger.writeTotal(rootSuites);
var remainingSuites = rootSuites.slice();
var runSuite = function () {
if (remainingSuites.length > 0) {
var nextSuite = remainingSuites.shift();
nextSuite.run(logger, runSuite);
}
else {
logger.writeTotal(rootSuites);
}
};
runSuite();
}, false);
+1
View File
@@ -39,6 +39,7 @@
<script src="test-primitives.js" />
<script src="test-tags.js" />
<script src="test-miscellaneous.js" />
<script src="test-webworker.js" />
</head>
<body>
<div id="output" />
+2
View File
@@ -21,6 +21,8 @@
var libjass = require("../libjass.js");
var assert = require("assert");
libjass.debugMode = true;
var parserTest = function (description, input, rule, expected) {
var result = test(description, function () {
var actual = null;
+82
View File
@@ -100,4 +100,86 @@ suite("Miscellaneous", function () {
new libjass.parts.PrimaryColor(new libjass.parts.Color(68, 68, 68, 1)),
new libjass.parts.Text("u")
]);
parserTest("klk-01", "{\\an5\\bord0\\blur1\\p1\\c&H97B9D6&\\pos(143.39,358.77)\\frz334.3\\fscx39\\fscy47\\iclip(m 129 338 l 121 381 110 372 110 331)}m 0 0 l 100 0 100 100 0 100", "dialogueParts", [
new libjass.parts.Alignment(5),
new libjass.parts.Border(0),
new libjass.parts.GaussianBlur(1),
new libjass.parts.DrawingMode(1),
new libjass.parts.PrimaryColor(new libjass.parts.Color(214, 185, 151, 1)),
new libjass.parts.Position(143.39, 358.77),
new libjass.parts.RotateZ(334.3),
new libjass.parts.FontScaleX(0.39),
new libjass.parts.FontScaleY(0.47),
new libjass.parts.VectorClip(1, [
new libjass.parts.drawing.MoveInstruction(129, 338),
new libjass.parts.drawing.LineInstruction(121, 381),
new libjass.parts.drawing.LineInstruction(110, 372),
new libjass.parts.drawing.LineInstruction(110, 331)
], false),
new libjass.parts.DrawingInstructions([
new libjass.parts.drawing.MoveInstruction(0, 0),
new libjass.parts.drawing.LineInstruction(100, 0),
new libjass.parts.drawing.LineInstruction(100, 100),
new libjass.parts.drawing.LineInstruction(0, 100)
])
]);
parserTest("chihaya-16", "{\\an7\\pos(0,0)\\bord0\\blur0.5\\p1\\c&HFAFAFA&}m 88 644 l 87 681 l 255 681 l 256 643 m 311 643 l 310 681 l 482 681 l 483 641 m 562 641 l 561 679 l 730 676 l 731 640 m 800 638 l 798 677 l 968 676 l 970 639 m 1031 638 l 1028 675 l 1200 674 l 1200 640 {p0}", "dialogueParts", [
new libjass.parts.Alignment(7),
new libjass.parts.Position(0, 0),
new libjass.parts.Border(0),
new libjass.parts.GaussianBlur(0.5),
new libjass.parts.DrawingMode(1),
new libjass.parts.PrimaryColor(new libjass.parts.Color(250, 250, 250)),
new libjass.parts.DrawingInstructions([
new libjass.parts.drawing.MoveInstruction(88, 644),
new libjass.parts.drawing.LineInstruction(87, 681),
new libjass.parts.drawing.LineInstruction(255, 681),
new libjass.parts.drawing.LineInstruction(256, 643),
new libjass.parts.drawing.MoveInstruction(311, 643),
new libjass.parts.drawing.LineInstruction(310, 681),
new libjass.parts.drawing.LineInstruction(482, 681),
new libjass.parts.drawing.LineInstruction(483, 641),
new libjass.parts.drawing.MoveInstruction(562, 641),
new libjass.parts.drawing.LineInstruction(561, 679),
new libjass.parts.drawing.LineInstruction(730, 676),
new libjass.parts.drawing.LineInstruction(731, 640),
new libjass.parts.drawing.MoveInstruction(800, 638),
new libjass.parts.drawing.LineInstruction(798, 677),
new libjass.parts.drawing.LineInstruction(968, 676),
new libjass.parts.drawing.LineInstruction(970, 639),
new libjass.parts.drawing.MoveInstruction(1031, 638),
new libjass.parts.drawing.LineInstruction(1028, 675),
new libjass.parts.drawing.LineInstruction(1200, 674),
new libjass.parts.drawing.LineInstruction(1200, 640)
]),
new libjass.parts.Comment("p0")
]);
parserTest("SRT", "1\n00:00:10,500 --> 00:00:13,000\nElephant's Dream\n\n2\n00:00:15,000 --> 00:00:18,000 X1:52 X2:303 Y1:438 Y2:453\n<font color=\"cyan\">At the left we can see...</font>", "srtScript", [{
number: 1,
start: "00:00:10.500", end: "00:00:13.000",
bounds: { x1: null, y1: null, x2: null, y2: null },
text: "Elephant's Dream"
}, {
number: 2,
start: "00:00:15.000", end: "00:00:18.000",
bounds: "X1:52 X2:303 Y1:438 Y2:453",
text: "<font color=\"cyan\">At the left we can see...</font>"
}
]);
parserTest("SRT multiple lines", "1\n00:01:15,940 --> 00:01:17,280\nHave you secured the key?\nWhy can't people forgive each other\n\n2\n00:01:17,280 --> 00:01:17,670\nWhy can't people forgive each other", "srtScript", [{
number: 1,
start: "00:01:15.940", end: "00:01:17.280",
bounds: { x1: null, y1: null, x2: null, y2: null },
text: "Have you secured the key?\nWhy can't people forgive each other"
}, {
number: 2,
start: "00:01:17.280", end: "00:01:17.670",
bounds: { x1: null, y1: null, x2: null, y2: null },
text: "Why can't people forgive each other"
}
]);
});
+96 -1
View File
@@ -56,7 +56,15 @@ suite("Tags", function () {
parserTest("Enclosed tag", "{\\b150}", "enclosedTags", [new libjass.parts.Bold(true), new libjass.parts.Comment("50")]);
});
suite("Primary color tag - \\c or \\1c", function () {
suite("Italics tag - \\i", function () {
parserTest("True", "i1", "tag_i", new libjass.parts.Italic(true));
parserTest("False", "i0", "tag_i", new libjass.parts.Italic(false));
parserTest("null", "i", "tag_i", new libjass.parts.Italic(null));
});
suite("Primary color tags - \\c and \\1c", function () {
parserTest("Just the tag", "1c&H3F171F&", "tag_1c", new libjass.parts.PrimaryColor(new libjass.parts.Color(31, 23, 63, 1)));
parserTest("Just the tag", "c&H3F171F&", "tag_c", new libjass.parts.PrimaryColor(new libjass.parts.Color(31, 23, 63, 1)));
@@ -72,7 +80,94 @@ suite("Tags", function () {
parserTest("Just the tag", "alpha00", "tag_alpha", new libjass.parts.Alpha(1));
});
suite("Font size tag - \\fs", function () {
parserTest("5", "fs5", "tag_fs", new libjass.parts.FontSize(5));
parserTest("null", "fs", "tag_fs", new libjass.parts.FontSize(null));
parserTest("Plus 5", "fs+5", "tag_fsplus", new libjass.parts.FontSizePlus(5));
parserTest("Plus null", "fs+", "tag_fsplus", null);
parserTest("Minus 5", "fs-5", "tag_fsminus", new libjass.parts.FontSizeMinus(5));
parserTest("Minus null", "fs-", "tag_fsminus", null);
});
suite("Transform tag - \\t", function () {
parserTest("No tags", "{\\t(100,200)}", "enclosedTags", [new libjass.parts.Comment("\\t(100,200)")]);
});
suite("Clip tags - \\clip and \\iclip", function () {
parserTest("Rectangular clip", "{\\clip(100,200,300,400)}", "enclosedTags", [new libjass.parts.RectangularClip(100, 200, 300, 400, true)]);
parserTest("Vector clip", "{\\clip(m 129 338 l 121 381 110 372 110 331)}", "enclosedTags", [new libjass.parts.VectorClip(1, [
new libjass.parts.drawing.MoveInstruction(129, 338),
new libjass.parts.drawing.LineInstruction(121, 381),
new libjass.parts.drawing.LineInstruction(110, 372),
new libjass.parts.drawing.LineInstruction(110, 331)
], true)]);
parserTest("Vector clip with scale", "{\\clip(1, m 129 338 l 121 381 110 372 110 331)}", "enclosedTags", [new libjass.parts.VectorClip(1, [
new libjass.parts.drawing.MoveInstruction(129, 338),
new libjass.parts.drawing.LineInstruction(121, 381),
new libjass.parts.drawing.LineInstruction(110, 372),
new libjass.parts.drawing.LineInstruction(110, 331)
], true)]);
parserTest("Inverted rectangular clip", "{\\iclip(100,200,300,400)}", "enclosedTags", [new libjass.parts.RectangularClip(100, 200, 300, 400, false)]);
parserTest("Inverted vector clip", "{\\iclip(m 129 338 l 121 381 110 372 110 331)}", "enclosedTags", [new libjass.parts.VectorClip(1, [
new libjass.parts.drawing.MoveInstruction(129, 338),
new libjass.parts.drawing.LineInstruction(121, 381),
new libjass.parts.drawing.LineInstruction(110, 372),
new libjass.parts.drawing.LineInstruction(110, 331)
], false)]);
parserTest("Inverted vector clip with scale", "{\\iclip(1, m 129 338 l 121 381 110 372 110 331)}", "enclosedTags", [new libjass.parts.VectorClip(1, [
new libjass.parts.drawing.MoveInstruction(129, 338),
new libjass.parts.drawing.LineInstruction(121, 381),
new libjass.parts.drawing.LineInstruction(110, 372),
new libjass.parts.drawing.LineInstruction(110, 331)
], false)]);
});
suite("Drawing instructions", function () {
parserTest("Normal", "m 984 425 l 985 445 l 985 542 l 973 544 b 983 524 987 496 984 459", "drawingInstructions", [
new libjass.parts.drawing.MoveInstruction(984, 425),
new libjass.parts.drawing.LineInstruction(985, 445),
new libjass.parts.drawing.LineInstruction(985, 542),
new libjass.parts.drawing.LineInstruction(973, 544),
new libjass.parts.drawing.CubicBezierCurveInstruction(983, 524, 987, 496, 984, 459)
]);
parserTest("Re-use previous instruction", "m 984 425 l 985 445 985 542 973 544 b 983 524 987 496 984 459", "drawingInstructions", [
new libjass.parts.drawing.MoveInstruction(984, 425),
new libjass.parts.drawing.LineInstruction(985, 445),
new libjass.parts.drawing.LineInstruction(985, 542),
new libjass.parts.drawing.LineInstruction(973, 544),
new libjass.parts.drawing.CubicBezierCurveInstruction(983, 524, 987, 496, 984, 459)
]);
parserTest("Leading space", " m 984 425", "drawingInstructions", [
new libjass.parts.drawing.MoveInstruction(984, 425)
]);
parserTest("Terminal space", "m 984 425 ", "drawingInstructions", [
new libjass.parts.drawing.MoveInstruction(984, 425)
]);
parserTest("Space on both ends", " m 984 425 ", "drawingInstructions", [
new libjass.parts.drawing.MoveInstruction(984, 425)
]);
parserTest("Empty", "", "drawingInstructions", [
]);
parserTest("One space", " ", "drawingInstructions", [
]);
parserTest("Two spaces", " ", "drawingInstructions", [
]);
});
});
+65
View File
@@ -0,0 +1,65 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var libjass = require("../libjass.js");
var assert = require("assert");
suite("Web worker", function () {
var workerChannel = null;
setup(function () {
workerChannel = libjass.webworker.createWorker();
});
suite("Parse", function () {
if (libjass.webworker.supported) {
test("Parse", function (done) {
this.customProperties = {
rule: "dialogueParts",
input: "{\\an8}Are {\\i1}you{\\i0} the one who stole the clock?!"
};
workerChannel.request(libjass.webworker.WorkerCommands.Parse, {
input: this.customProperties.input,
rule: this.customProperties.rule
}).then(function (promise) {
try {
assert.deepEqual(promise.result, [
new libjass.parts.Alignment(8),
new libjass.parts.Text("Are "),
new libjass.parts.Italic(true),
new libjass.parts.Text("you"),
new libjass.parts.Italic(false),
new libjass.parts.Text(" the one who stole the clock?!")
]);
done();
}
catch (ex) {
done(ex);
}
});
});
}
else {
test("Parse: Web workers not supported in this environment.");
}
});
});
+233 -82
View File
@@ -21,21 +21,14 @@
///<reference path="libjass.ts" />
module libjass {
export interface StyleMap {
[name: string]: Style;
}
/**
* This class represents an ASS script. It contains the script properties, an array of Styles, and an array of Dialogues.
*
* @constructor
*
* @memberof libjass
*/
export class ASS {
private _properties: ScriptProperties = new ScriptProperties();
private _styles: StyleMap = Object.create(null);
private _styles: Map<string, Style> = new Map<string, Style>();
private _dialogues: Dialogue[] = [];
private _dialoguesFormatSpecifier: string[];
/**
* The properties of this script.
@@ -49,9 +42,9 @@ module libjass {
/**
* The styles in this script.
*
* @type {!Object.<string, !libjass.Style>}
* @type {!Map.<string, !libjass.Style>}
*/
get styles(): StyleMap {
get styles(): Map<string, Style> {
return this._styles;
}
@@ -71,38 +64,74 @@ module libjass {
}
}
/**
* Add an event to this ASS script.
*
* @param {string} line The line from the script that contains the new event.
*/
addEvent(line: string): void {
var typedTemplateArray = <TypedTemplateArray>[];
typedTemplateArray.formatSpecifier = this._dialoguesFormatSpecifier;
var typedTemplate = <TypedTemplate>parser.parse(line, "assScriptProperty", new parser.ParseNode(null, { contents: typedTemplateArray }));
this._addEvent(typedTemplate);
}
private _addEvent(line: TypedTemplate) {
if (line.type === "Dialogue") {
var dialogueTemplate = line.template;
if (libjass.verboseMode) {
console.log("Read dialogue: " + JSON.stringify(dialogueTemplate), dialogueTemplate);
}
// Create the dialogue and add it to the dialogues array
this.dialogues.push(new Dialogue(dialogueTemplate, this));
}
}
/**
* Creates an ASS object from the raw text of an ASS script.
*
* @param {string} rawASS The raw text of the ASS script.
* @param {string} raw The raw text of the script.
* @param {number=0} type The type of the script. One of the libjass.Format constants.
* @return {!libjass.ASS}
*
* @static
*/
static fromString(rawASS: string): ASS {
rawASS = rawASS.replace(/\r$/gm, "");
static fromString(raw: string, type: Format = Format.ASS): ASS {
raw = raw.replace(/\r$/gm, "");
var script = parser.parse(rawASS, "script");
switch (type) {
case Format.ASS:
return ASS._fromASSString(raw);
case Format.SRT:
return ASS._fromSRTString(raw);
default:
throw new Error("Illegal value of type: " + type);
}
}
private static _fromASSString(rawASS: string): ASS {
var script = <Map<string, any>>parser.parse(rawASS, "assScript");
var result = new ASS();
// Get the script info template
var infoTemplate: Template = script["Script Info"];
var infoTemplate: Map<string, string> = script.get("Script Info");
if (libjass.verboseMode) {
console.log("Read script info: " + JSON.stringify(infoTemplate), infoTemplate);
}
// Parse the horizontal script resolution
result.properties.resolutionX = parseInt(infoTemplate["PlayResX"]);
// Parse the vertical script resolution
result.properties.resolutionY = parseInt(infoTemplate["PlayResY"]);
// Parse the script properties
result.properties.resolutionX = parseInt(infoTemplate.get("PlayResX"));
result.properties.resolutionY = parseInt(infoTemplate.get("PlayResY"));
result.properties.wrappingStyle = parseInt(infoTemplate.get("WrapStyle"));
result.properties.scaleBorderAndShadow = (infoTemplate.get("ScaledBorderAndShadow") === "yes");
// Get styles from the styles section
script["V4+ Styles"].forEach((line: any) => {
(<TypedTemplateArray>script.get("V4+ Styles")).forEach(line => {
if (line.type === "Style") {
var styleTemplate: Template = line.template;
var styleTemplate = line.template;
if (libjass.verboseMode) {
console.log("Read style: " + JSON.stringify(styleTemplate), styleTemplate);
@@ -110,38 +139,85 @@ module libjass {
// Create the style and add it to the styles map
var newStyle = new Style(styleTemplate);
result.styles[newStyle.name] = newStyle;
result.styles.set(newStyle.name, newStyle);
}
});
// Get dialogues from the events section
script["Events"].forEach((line: any) => {
if (line.type === "Dialogue") {
var dialogueTemplate: Template = line.template;
var events = <TypedTemplateArray>script.get("Events");
result._dialoguesFormatSpecifier = events.formatSpecifier;
events.forEach(line => result._addEvent(line));
if (libjass.verboseMode) {
console.log("Read dialogue: " + JSON.stringify(dialogueTemplate), dialogueTemplate);
}
return result;
}
// Create the dialogue and add it to the dialogues array
result.dialogues.push(new Dialogue(dialogueTemplate, result));
}
private static _fromSRTString(rawSRT: string): ASS {
var script: any[] = parser.parse(rawSRT, "srtScript");
var result = new ASS();
// Parse the script properties
result.properties.resolutionX = 1280;
result.properties.resolutionY = 720;
result.properties.wrappingStyle = 1;
result.properties.scaleBorderAndShadow = true;
var newStyle = new Style(new Map<string, string>()
.set("Name", "Default")
.set("Italic", "0").set("Bold", "0").set("Underline", "0").set("StrikeOut", "0")
.set("Fontname", "").set("Fontsize", "50")
.set("ScaleX", "100").set("ScaleY", "100")
.set("Spacing", "0")
.set("Angle", "0")
.set("PrimaryColour", "&H0000FFFF").set("SecondaryColour", "&H00000000").set("OutlineColour", "&H00000000").set("BackColour", "&H00000000")
.set("Outline", "1").set("BorderStyle", "1")
.set("Shadow", "1")
.set("Alignment", "2")
.set("MarginL", "80").set("MarginR", "80").set("MarginV", "35")
);
result.styles.set(newStyle.name, newStyle);
script.sort((line1, line2) => line1["number"] - line2["number"]).forEach(line => {
result.dialogues.push(new Dialogue(new Map<string, string>()
.set("Style", "Default")
.set("Start", line.start).set("End", line.end)
.set("Layer", "0")
.set("Text",
(<string>line.text)
.replace(/<b>/g, "{\\b1}").replace(/<\/b>/g, "{\\b0}")
.replace(/<i>/g, "{\\i1}").replace(/<\/i>/g, "{\\i0}")
.replace(/<u>/g, "{\\u1}").replace(/<\/u>/g, "{\\u0}")
.replace(
/<font color="#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})">/g,
(/* ujs:unreferenced */ substring: string, red: string, green: string, blue: string) => "{\c&H" + blue + green + red + "&}"
).replace(/<\/font>/g, "{\\c}")
), result));
});
return result;
}
}
export enum Format {
ASS,
SRT
}
export enum WrappingStyle {
SmartWrappingWithWiderTopLine = 0,
SmartWrappingWithWiderBottomLine = 3,
EndOfLineWrapping = 1,
NoLineWrapping = 2,
}
/**
* This class represents the properties of an ASS script.
*
* @constructor
*
* @memberof libjass
*/
export class ScriptProperties {
private _resolutionX: number;
private _resolutionY: number;
private _wrappingStyle: WrappingStyle;
private _scaleBorderAndShadow: boolean;
/**
* The horizontal script resolution.
@@ -178,13 +254,53 @@ module libjass {
set resolutionY(value: number) {
this._resolutionY = value;
}
/**
* The wrap style.
*
* @type {number}
*/
get wrappingStyle(): WrappingStyle {
return this._wrappingStyle;
}
/**
* The wrap style.
*
* @type {number}
*/
set wrappingStyle(value: WrappingStyle) {
this._wrappingStyle = value;
}
/**
* Whether to scale outline widths and shadow depths from script resolution to video resolution or not. If true, widths and depths are scaled.
*
* @type {boolean}
*/
get scaleBorderAndShadow(): boolean {
return this._scaleBorderAndShadow;
}
/**
* Whether to scale outline widths and shadow depths from script resolution to video resolution or not. If true, widths and depths are scaled.
*
* @type {boolean}
*/
set scaleBorderAndShadow(value: boolean) {
this._scaleBorderAndShadow = value;
}
}
export enum BorderStyle {
Outline = 1,
OpaqueBox = 3,
}
/**
* This class represents a single global style declaration in an ASS script. The styles can be obtained via the ASS.styles property.
*
* @constructor
* @param {!Object} template The template object that contains the style's properties. It is a map of the string values read from the ASS file.
* @param {!Map.<string, string>} template The template object that contains the style's properties. It is a map of the string values read from the ASS file.
* @param {string} template["Name"] The name of the style
* @param {string} template["Italic"] -1 if the style is italicized
* @param {string} template["Bold"] -1 if the style is bold
@@ -204,8 +320,6 @@ module libjass {
* @param {string} template["MarginL"] The left margin
* @param {string} template["MarginR"] The right margin
* @param {string} template["MarginV"] The vertical margin
*
* @memberof libjass
*/
export class Style {
private _name: string;
@@ -223,11 +337,15 @@ module libjass {
private _letterSpacing: number;
private _rotationZ: number;
private _primaryColor: parts.Color;
private _secondaryColor: parts.Color;
private _outlineColor: parts.Color;
private _shadowColor: parts.Color;
private _outlineThickness: number;
private _borderStyle: BorderStyle;
private _shadowDepth: number;
@@ -237,35 +355,39 @@ module libjass {
private _marginRight: number;
private _marginVertical: number;
constructor(template: Template) {
this._name = template["Name"];
constructor(template: Map<string, string>) {
this._name = template.get("Name");
this._italic = template["Italic"] === "-1";
this._bold = template["Bold"] === "-1";
this._underline = template["Underline"] === "-1";
this._strikeThrough = template["StrikeOut"] === "-1";
this._italic = template.get("Italic") === "-1";
this._bold = template.get("Bold") === "-1";
this._underline = template.get("Underline") === "-1";
this._strikeThrough = template.get("StrikeOut") === "-1";
this._fontName = template["Fontname"];
this._fontSize = parseFloat(template["Fontsize"]);
this._fontName = template.get("Fontname");
this._fontSize = parseFloat(template.get("Fontsize"));
this._fontScaleX = parseFloat(template["ScaleX"]) / 100;
this._fontScaleY = parseFloat(template["ScaleY"]) / 100;
this._fontScaleX = parseFloat(template.get("ScaleX")) / 100;
this._fontScaleY = parseFloat(template.get("ScaleY")) / 100;
this._letterSpacing = parseFloat(template["Spacing"]);
this._letterSpacing = parseFloat(template.get("Spacing"));
this._primaryColor = <parts.Color>parser.parse(template["PrimaryColour"], "colorWithAlpha");
this._outlineColor = <parts.Color>parser.parse(template["OutlineColour"], "colorWithAlpha");
this._shadowColor = <parts.Color>parser.parse(template["BackColour"], "colorWithAlpha");
this._rotationZ = parseFloat(template.get("Angle"));
this._outlineThickness = parseFloat(template["Outline"]);
this._primaryColor = <parts.Color>parser.parse(template.get("PrimaryColour"), "colorWithAlpha");
this._secondaryColor = <parts.Color>parser.parse(template.get("SecondaryColour"), "colorWithAlpha");
this._outlineColor = <parts.Color>parser.parse(template.get("OutlineColour"), "colorWithAlpha");
this._shadowColor = <parts.Color>parser.parse(template.get("BackColour"), "colorWithAlpha");
this._shadowDepth = parseFloat(template["Shadow"]);
this._outlineThickness = parseFloat(template.get("Outline"));
this._borderStyle = parseInt(template.get("BorderStyle"));
this._alignment = parseInt(template["Alignment"]);
this._shadowDepth = parseFloat(template.get("Shadow"));
this._marginLeft = parseFloat(template["MarginL"]);
this._marginRight = parseFloat(template["MarginR"]);
this._marginVertical = parseFloat(template["MarginV"]);
this._alignment = parseInt(template.get("Alignment"));
this._marginLeft = parseFloat(template.get("MarginL"));
this._marginRight = parseFloat(template.get("MarginR"));
this._marginVertical = parseFloat(template.get("MarginV"));
}
/**
@@ -358,6 +480,15 @@ module libjass {
return this._letterSpacing;
}
/**
* The default Z-rotation of this style.
*
* @type {number}
*/
get rotationZ(): number {
return this._rotationZ;
}
/**
* The color of this style's font.
*
@@ -367,6 +498,15 @@ module libjass {
return this._primaryColor;
}
/**
* The alternate color of this style's font, used in karaoke.
*
* @type {!libjass.parts.Color}
*/
get secondaryColor(): parts.Color {
return this._secondaryColor;
}
/**
* The color of this style's outline.
*
@@ -394,6 +534,15 @@ module libjass {
return this._outlineThickness;
}
/**
* The border style of this style.
*
* @type {number}
*/
get borderStyle(): BorderStyle {
return this._borderStyle;
}
/**
* The depth of this style's shadow.
*
@@ -443,16 +592,13 @@ module libjass {
/**
* This class represents a dialogue in an ASS script.
*
* @constructor
* @param {!Object} template The template object that contains the dialogue's properties. It is a map of the string values read from the ASS file.
* @param {!Map.<string, string>} template The template object that contains the dialogue's properties. It is a map of the string values read from the ASS file.
* @param {string} template["Style"] The name of the default style of this dialogue
* @param {string} template["Start"] The start time
* @param {string} template["End"] The end time
* @param {string} template["Layer"] The layer number
* @param {string} template["Text"] The text of this dialogue
* @param {ASS} ass The ASS object to which this dialogue belongs
*
* @memberof libjass
*/
export class Dialogue {
private static _lastDialogueId = -1;
@@ -472,19 +618,17 @@ module libjass {
private _sub: HTMLDivElement = null;
constructor(template: Template, ass: ASS) {
constructor(template: Map<string, string>, ass: ASS) {
this._id = ++Dialogue._lastDialogueId;
this._style = ass.styles[template["Style"]];
this._style = ass.styles.get(template.get("Style"));
this._start = Dialogue._toTime(template["Start"]);
this._end = Dialogue._toTime(template["End"]);
this._start = Dialogue._toTime(template.get("Start"));
this._end = Dialogue._toTime(template.get("End"));
this._layer = Math.max(parseInt(template["Layer"]), 0);
this._layer = Math.max(parseInt(template.get("Layer")), 0);
this._alignment = this._style.alignment;
this._rawPartsString = template["Text"];
this._rawPartsString = template.get("Text");
}
/**
@@ -566,6 +710,8 @@ module libjass {
private _parsePartsString(): void {
this._parts = <parts.Part[]>parser.parse(this._rawPartsString, "dialogueParts");
this._alignment = this._style.alignment;
this._parts.forEach((part, index) => {
if (part instanceof parts.Alignment) {
this._alignment = (<parts.Alignment>part).value;
@@ -614,11 +760,8 @@ module libjass {
/**
* Converts this string into the number of seconds it represents. This string must be in the form of hh:mm:ss.MMM
*
* @param {string} string
* @param {string} str
* @return {number}
*
* @private
* @static
*/
private static _toTime(str: string): number {
return str.split(":").reduce<number>((previousValue, currentValue) => previousValue * 60 + parseFloat(currentValue), 0);
@@ -626,10 +769,18 @@ module libjass {
}
/**
* A template object. It is a map of string keys and string values.
* A template object with a particular type.
*/
export interface Template {
[key: string]: string;
export interface TypedTemplate {
type: string;
template: Map<string, string>;
}
/**
* An array of TypedTemplate objects with the format specifier that was used to parse them.
*/
export interface TypedTemplateArray extends Array<TypedTemplate> {
formatSpecifier: string[];
}
/**
+57 -33
View File
@@ -22,20 +22,24 @@
"use strict";
interface Global {
Set: { new <T>(): Set<T>; prototype: Set<any> }
Map: { new <K, V>(): Map<K, V>; prototype: Map<any, any> }
}
declare var global: Global; // Defined as a parameter of the anonymous function wrapper
module libjass {
/**
* Set implementation for browsers that don't support it. Only supports Number and String elements.
*
* Elements are stored as properties of an object, with names derived from their type.
*
* @constructor
* @template T
*
* @private
* @memberof libjass
*/
class SimpleSet<T> implements Set<T> {
private _elements: { [key: string]: T };
private _size: number;
constructor() {
this.clear();
@@ -52,6 +56,10 @@ module libjass {
throw new Error("This Set implementation only supports Number and String values.");
}
if (!(property in this._elements)) {
this._size++;
}
this._elements[property] = value;
return this;
@@ -61,6 +69,7 @@ module libjass {
*/
clear(): void {
this._elements = Object.create(null);
this._size = 0;
}
/**
@@ -91,8 +100,11 @@ module libjass {
throw new Error("This Set implementation doesn't support delete().");
}
/**
* @type {number}
*/
get size(): number {
throw new Error("This Set implementation doesn't support size.");
return this._size;
}
private _toProperty(value: T): string {
@@ -108,32 +120,27 @@ module libjass {
}
}
export var Set: {
new <T>(): Set<T>;
} = null;
// Use this browser's implementation of Set if it has one
if (global.Set !== undefined && typeof global.Set.prototype.forEach === "function") {
Set = global.Set;
}
else {
Set = SimpleSet;
/**
* Set to browser's implementation of Set if it has one, else set to libjass.SimpleSet
*
* @type {function(new:Set)}
*/
export var Set = global.Set;
if (Set === undefined || typeof Set.prototype.forEach !== "function") {
Set = <any>SimpleSet;
}
/**
* Map implementation for browsers that don't support it. Only supports Number and String keys.
* Map implementation for browsers that don't support it. Only supports keys which are of Number or String type, or which have a property called "id".
*
* Keys and values are stored as properties of an object, with property names derived from the key type.
*
* @constructor
* @template K, V
*
* @private
* @memberof libjass
*/
class SimpleMap<K, V> implements Map<K, V> {
private _keys: { [key: string]: K };
private _values: { [key: string]: V };
private _size: number;
constructor() {
this.clear();
@@ -176,7 +183,11 @@ module libjass {
var property = this._keyToProperty(key);
if (property === null) {
throw new Error("This Map implementation only supports Number and String keys.");
throw new Error("This Map implementation only supports Number and String keys, or keys with an id property.");
}
if (!(property in this._keys)) {
this._size++;
}
this._keys[property] = key;
@@ -201,6 +212,7 @@ module libjass {
if (result) {
delete this._keys[property];
delete this._values[property];
this._size--;
}
return result;
@@ -211,6 +223,7 @@ module libjass {
clear(): void {
this._keys = Object.create(null);
this._values = Object.create(null);
this._size = 0;
}
/**
@@ -224,8 +237,11 @@ module libjass {
}
}
/**
* @type {number}
*/
get size(): number {
throw new Error("This Map implementation doesn't support size.");
return this._size;
}
private _keyToProperty(key: K): string {
@@ -237,21 +253,29 @@ module libjass {
return "'" + key;
}
if ((<any>key).id !== undefined) {
return "!" + (<any>key).id;
}
return null;
}
}
export var Map: {
new <K, V>(): Map<K, V>;
} = null;
declare var global: any; // Defined as a parameter of the anonymous function wrapper
// Use this browser's implementation of Map if it has one
if (global.Map !== undefined && typeof global.Map.prototype.forEach === "function") {
Map = global.Map;
}
else {
/**
* Set to browser's implementation of Map if it has one, else set to libjass.SimpleMap
*
* @type {function(new:Map)}
*/
export var Map = global.Map;
if (Map === undefined || typeof Map.prototype.forEach !== "function") {
Map = <any>SimpleMap;
}
export function mixin(derived: any, mixins: any[]) {
mixins.forEach((mixin: any) => {
Object.getOwnPropertyNames(mixin.prototype).forEach(name => {
derived.prototype[name] = mixin.prototype[name];
});
});
}
}
+298
View File
@@ -0,0 +1,298 @@
/**
* libjass
*
* https://github.com/Arnavion/libjass
*
* Copyright 2013 Arnav Singh
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
///<reference path="libjass.ts" />
interface Document {
currentScript: HTMLScriptElement;
}
interface WorkerGlobalScope {
postMessage(message: any): void;
addEventListener(type: string, listener: (message: any) => void, useCapture: boolean): void;
}
declare var WorkerGlobalScope: {
prototype: WorkerGlobalScope;
new (): WorkerGlobalScope;
};
module libjass.webworker {
Object.defineProperty(webworker, "supported", {
value: typeof Worker !== "undefined",
configurable: true,
enumerable: true
});
/**
* Represents a communication channel between the host and the web worker. An instance of this class is created by calling libjass.webworker.setup()
*/
export interface WorkerChannel {
/**
* Sends a request to the other side to execute the given command with the given parameters.
*
* @param {number} command
* @param {*} parameters
* @return {!libjass.webworker.WorkerPromise} A promise that will get resolved when the other side computes the result
*/
request(command: WorkerCommands, parameters: any): WorkerPromise;
}
/**
* Create a new web worker.
*
* @return {!libjass.webworker.WorkerChannel} A communication channel to the new web worker.
*/
export function createWorker(): WorkerChannel {
return new WorkerChannelImpl(new Worker(_scriptNode.src));
}
/**
* A promise returned by libjass.webworker.WorkerChannel.request()
*/
export interface WorkerPromise {
resolved: boolean;
result: any;
/**
* Registers a callback to run when this promise is resolved. If the promise is already resolved, the callback is called immediately.
*
* @param {function(*) } callback A function of the form (promise: *): void
*/
then(callback: WorkerPromiseCallback): void;
cancel(): void;
}
/**
* The signature of a callback called by WorkerPromise when it is resolved.
*/
export interface WorkerPromiseCallback {
(promise: WorkerPromise): void;
}
/**
* The commands that can be sent to or from a web worker.
*/
export enum WorkerCommands {
Response = 0
}
/**
* The signature of a handler registered to handle a particular WorkerCommand.
*/
export interface WorkerCommandHandler {
(parameters: any, response: WorkerResultCallback): void;
}
/**
* The signature of a callback called by a WorkerCommandHandler to report its result back to the caller.
*/
export interface WorkerResultCallback {
(error: any, result: any): void;
}
/**
* Registers a handler for the given worker command.
*
* @param {number} command The command that this handler will handle. Valid values are the values of libjass.webworker.WorkerCommands
* @param {function(*, function(*, *))} handler The handler. A function of the form (parameters: *, response: function(error: *, result: *): void): void
*/
export function _registerWorkerCommand(command: WorkerCommands, handler: WorkerCommandHandler) {
workerCommands.set(command, handler);
}
export function _registerClassPrototype(prototype: any): void {
prototype._classTag = classPrototypes.size;
classPrototypes.set(prototype._classTag, prototype);
}
var _scriptNode: HTMLScriptElement = null;
if (typeof document !== "undefined" && document.currentScript !== undefined) {
_scriptNode = document.currentScript;
}
var workerCommands = new Map<WorkerCommands, WorkerCommandHandler>();
var classPrototypes = new Map<number, any>();
interface WorkerCommunication {
addEventListener(type: "message", listener: (ev: MessageEvent) => any, useCapture?: boolean): void;
addEventListener(type: string, listener: EventListener, useCapture?: boolean): void;
postMessage(message: any): void;
}
interface WorkerRequestMessage {
requestId: number;
command: WorkerCommands;
parameters: any;
}
interface WorkerResponseMessage {
requestId: number;
error: any;
result: any;
}
/**
* Internal implementation of libjass.webworker.WorkerChannel
*
* @param {!*} comm The other side of the channel. When created by the host, this is the web worker. When created by the web worker, this is its global object.
*/
class WorkerChannelImpl implements WorkerChannel {
private _pendingRequests = new Map<number, WorkerPromiseImpl>();
constructor(private _comm: WorkerCommunication) {
this._comm.addEventListener("message", ev => this._onMessage(<string>ev.data), false);
}
request(command: WorkerCommands, parameters: any): WorkerPromise {
var promise = new WorkerPromiseImpl(this);
var requestId = promise.id;
this._pendingRequests.set(requestId, promise);
var requestMessage: WorkerRequestMessage = { requestId: requestId, command: command, parameters: parameters };
this._comm.postMessage(WorkerChannelImpl._toJSON(requestMessage));
return promise;
}
cancelRequest(requestId: number): void {
this._pendingRequests.delete(requestId);
}
private _respond(message: WorkerResponseMessage): void {
this._comm.postMessage(WorkerChannelImpl._toJSON({ command: WorkerCommands.Response, requestId: message.requestId, error: message.error, result: message.result }));
}
private _onMessage(rawMessage: string): void {
var message = <{ command: WorkerCommands }>WorkerChannelImpl._fromJSON(rawMessage);
if (message.command === WorkerCommands.Response) {
var responseMessage = <WorkerResponseMessage><any>message;
var promise = this._pendingRequests.get(responseMessage.requestId);
if (promise !== undefined) {
this._pendingRequests.delete(responseMessage.requestId);
promise.resolve(responseMessage.error, responseMessage.result);
}
return;
}
var requestMessage = <WorkerRequestMessage>message;
var commandCallback = workerCommands.get(requestMessage.command);
if (commandCallback === undefined) {
this._respond({ requestId: requestMessage.requestId, error: new Error("Unrecognized command: " + requestMessage.command), result: null });
return;
}
commandCallback(requestMessage.parameters, (error: any, result: any) => this._respond({ requestId: requestMessage.requestId, error: error, result: result }));
}
private static _toJSON(obj: any): string {
return JSON.stringify(obj, (/* ujs:unreferenced */ key: string, value: any) => {
if (value && value._classTag !== undefined) {
value._classTag = value._classTag;
}
return value;
});
}
private static _fromJSON(str: string): any {
return JSON.parse(str, (/* ujs:unreferenced */ key: string, value: any) => {
if (value && value._classTag !== undefined) {
var hydratedValue = Object.create(classPrototypes.get(value._classTag));
Object.keys(value).forEach(key => {
if (key !== "_classTag") {
hydratedValue[key] = value[key];
}
});
value = hydratedValue;
}
return value;
});
}
}
var inWorker = (typeof WorkerGlobalScope !== "undefined" && global instanceof WorkerGlobalScope);
if (inWorker) {
new WorkerChannelImpl(<WorkerGlobalScope><any>global);
}
class WorkerPromiseImpl implements WorkerPromise {
private static _lastPromiseId: number = -1;
private _id: number = ++WorkerPromiseImpl._lastPromiseId;
private _resolved: boolean = false;
private _result: any = null;
private _error: any = null;
private _callback: WorkerPromiseCallback = null;
constructor(private _channel: WorkerChannelImpl) { }
get resolved(): boolean {
return this._resolved;
}
get result(): any {
if (!this._resolved) {
throw new Error("Unresolved promise.");
}
if (this._error !== null) {
throw this._error;
}
return this._result;
}
then(callback: WorkerPromiseCallback): void {
this._callback = callback;
if (this._resolved) {
setTimeout(() => this._callback(this), 0);
}
}
cancel(): void {
if (this._resolved) {
return;
}
this._channel.cancelRequest(this._id);
}
get id(): number {
return this._id;
}
resolve(error: any, result: any): void {
this._resolved = true;
this._error = error;
this._result = result;
if (this._callback !== null) {
this._callback(this);
}
}
}
}