Tag: js

  • Re-learning JavaScript OOP well

    It’s been a while since I’ve done some more serious JavaScript development, and even then it was typically very procedural. With adding version-dependent features for Popcorn’s SSA/ASS subtitle parser, I figured this would be a good opportunity to learn. I remember from the past that JavaScript uses Prototypical Inheritance, something I have no experience with in other languages. Luckily, I didn’t have to go far to find some helpful resources.

    In fact, MDN has an article with everything I needed to know, with a lecture by Douglas Crockford filling in the gaps.

    Inheritance and working off the prototype are what I’ve struggled with most, so I’m including some code snippets below. Most are inspired or outright copied and adapted from the MDN article. It’s also on pastebin.

    // Define a constructor for an 'SSAParser' object
    function SSAParser(text) {
      this.text = text;
      this.lines = [];
    }
    
    // Define a function for our parser object. So that memory is only allocated for it once across many objects, we put it on the prototype.
    // Inside the prototype, 'this' refers to the instance object
    SSAParser.prototype = {
      parse: function() {
        return "SSA parser: " + this.text;
      },
    
      getName: function() {
        return "SSA parser";
      }
    };
    
    // Instantiate with 'new' so that the properties are put on a new object (called 'this' in the constructor)
    var parser = new SSAParser("1");
    var parsed = parser.parse();
    
    // Not using 'new' will cause it to be like a normal function call.
    // The result will have 'this' point to the function itself, causing unpleasantness
    var parser = SSAParser("1");
    
    try {
      var parsed = parser.parse();  // SSAParser doesn't return a value, so 'var parser' is undefined, causing an error
    } catch (e) { alert("Please use 'new'"); }
    
    // Being clever, we can avoid using 'new' by always calling the function directly, and explicitly specifying 'this' to be our parser object. This results in far more typing.
    var parser = {};
    SSAParser.call( parser, text );
    var parsed = SSAParser.prototype.parse.call(parser);
    
    // Everything on the prototype is publicly accessible
    // Using closures, we can adapt the above method to have hidden helper functions that aren't publicly accessible
    SSAParser.prototype.useHelper = (function (){
      // This function is defined once, but is not directly on the prototype.
      // It is not publicly visible, but as it's defined in the same closure as a function on the prototype, it is accessible
      // 'this' points to the 'getHelperText' function by default, unless we override it
      function getHelperText() {
        return "From hidden helper: " + this.text;
      }
    
      // This function ends up on the prototype, we can access 'this' properly from within it
      return function() {
        var text = "From helper: " + this.text;
    
        // We can call getHelperText and reference our instance members within.
        // It becomes a private member function
        text += getHelperText.call(this);
        return this.text;
      }
    })();
    
    // Inheritance, ASSParser extends SSAParser
    function ASSParser(text) {
      // Explicitly call parent constructor
      SSAParser.call( this, text );
    }
    
    // We set the prototype to be our base class and update the constructor
    ASSParser.prototype = new SSAParser();
    ASSParser.prototype.constructor = SSAParser;
    
    // Override parent definition of getName
    // Unless we store the old definition of 'getName' we can no longer call the parent version
    ASSParser.prototype.getName = function() {
        return "ASS parser";
    }
    
    // Define new function, which references parent
    ASSParser.prototype.getPi = function() {
        return Math.PI;
    }
    
    var parser = new ASSParser("sample");
    alert(parser.getName());
    alert(parser.getPi());
  • Converting a string to XML in JavaScript

    XmlHttpRequest (XHR) often does a lot of the heavy lifting with converting text into an XML document when performing a resource request, but sometimes requires a little bit of a boost. It will only convert the document to an XML node structure if the MIME type from the server indicate it’s an xml-structured document. This can be anything from “text/xml” to more custom formats like “application/ttml+xml”. This all requires the MIME type to be registered on the server for the file extension, like so. If it isn’t, too bad, the file is coming back as “text/plain”, and the browser doesn’t convert it to XML. I hope the calling application wasn’t requiring the user to do this, because if so, the app just broke.

    What does this mean for software developers? Is it fair to expect every user to have to update mime.types or .htaccess so they can use the application? Even if it weren’t for the technological burden it places on the user, it’s just plain unfair to ask 100 people to do what you could just do yourself. So XHR allows you to overrideMimeType for the expected result, allowing for browsers to treat xml documents as xml, even if they come back as text/plain. Which would be great in a world of universal browser support.

    For example, IE 6 and below didn’t use XHR, and relied on a different mechanism (ActiveX) to perform requests from JavaScript. With the introduction of it in IE7, there still wasn’t support for mime type overriding. Which meant a convoluted process of indicating the browser should convert it when XHR.overrideMimeType was supported, and converting it manually when it wasn’t. This is great, but still brings us back to placing the burden of the user to configure what the developer was too lazy to do explicitly.

    After some digging into why some code was crashing recently, I realized this, and decided a good solution would be to manually convert the XHR result to an xml node structure if it wasn’t already. In typical circumstances, this would be the case only because the mime type was wrong. In atypical cases, the document itself is invalid XML, at which point the fix is out of the developer’s hands and responsibility shifts to the creator of the document. 95% of the time failures in situation occur though, it’ could’ve been avoided by defensive coding and re-parsing the xml content if it wasn’t automatically by the browser.

    So I made a utility function to do this. Most browsers already have the tools, all it took was creating a cross-browser wrapper for them. Grab it from GitHub, or see it below:

    // Convert a string to XML Node Structure
    // Returns null on failure
    function textToXML ( text ) {
          try {
            var xml = null;
    
            if ( window.DOMParser ) {
    
              var parser = new DOMParser();
              xml = parser.parseFromString( text, "text/xml" );
    
              var found = xml.getElementsByTagName( "parsererror" );
    
              if ( !found || !found.length || !found[ 0 ].childNodes.length ) {
                return xml;
              }
    
              return null;
            } else {
    
              xml = new ActiveXObject( "Microsoft.XMLDOM" );
    
              xml.async = false;
              xml.loadXML( text );
    
              return xml;
            }
          } catch ( e ) {
            // suppress
          }
        }
  • How I learned to stop worrying and love clean code

    In past bloggings, I’ve mentioned how my coding style has changed over time to reflect a deeper technical knowledge. Recently I’ve also been trying to learn more about software design and engineering from a maintainability and clean practices standpoint. While they are an important tool for accomplishing this, I’m not just talking about design patterns but a knowledge suite of best practices that make for intuitive-to-read and even easier to use code.

    Concepts like descriptive function and variable names, small functions, and intuitive design  are stressed heavily, as is design by functional decomposition. All of this I thought I knew, until I got torn apart at my first code review.

    Now I’m taking this, applying it to my code, and finding much cleaner and better results. JavaScript I’d written just 8 months ago looks horrendous by comparison to how I write now. Giant C-style functions with a whack of declarations at the top, 100+ lines of functionally independent code, and a general mass of structured but difficult to maintain code. In “modernizing” it and splitting it up into components, I find it reads easier, writes quicker, and even executes faster. I can only chalk this last part up to smaller scope for function JITs and tracing JITs to worry about, but it just goes to show:

    Work with the compiler, not against it.

  • Working with cookies in JS

    Well, it has certainly been a while since I’ve blogged.

    I’ve been working with data-driven tables a little bit recently, and the need came up to allow users to click on the table cells, and to persist a record of these clicks. Rather than store this in the database, it made more sense to use cookies. Not having worked with cookies for a while, I started playing around. I ran into a few gotchas.

    FIRST GOTCHA: Cookies can only be managed in the context of a web server.

    Everything started great. I found some sample code online to base the solution off of, and I began to I hooked all the events in, but data wasn’t persisting. No errors were being thrown. After some debugging work, it looked like it was never being set. Incidentally, this was because I was running the file off the file system (file://clickClick.html). No errors are thrown, no warnings are raised, it just won’t set unless you run it from a web server. After starting up Apache and running it from localhost, everything worked great. For a while.

    SECOND GOTCHA: With jQuery, the unload event is on ‘window’, not ‘document’

    My plan was to save the click results to a cookie when the page leaves, either via refresh or leaving the page altogether. Not bothering to read the documentation thoroughly, I tried this and expected it to work:

    $(document).unload(function() {   ...   });

    Turns out it didn’t. After some trawling of jquery’s documentation, I discovered it was the window object I wanted to hook into, not document. As with the cookies, this didn’t fire off an error, it just hooks into a user-created event that, unsurprisingly, is never fired by the browser. Switching ‘document’ to ‘window’ fixed this.

    FINAL GOTCHA: Internet Explorer does not seem to support character indexing via [] operator

    My method of saving data to a cookie is serializing a table into a string of ‘1’s and ‘0’s and storing it in a cookie, then reading that string back from the cookie and acting on it. Firefox and Chrome could handle reading individual characters fine by indexing the string like an array:

    if(oldCookieVal[i] === '1') {
                  ...
    }

    When testing on IE, I got an “unsupported property” error. Turns out IE treats strings like any other object, and will use indexing to perform a property lookup on the object. So if i = 3, instead of retrieving the fourth character in a string, IE was trying to do this:

    if(oldCookieVal.3 === '1') {
                  ...
    }

    Which broke the code. Switching to using the ‘charAt’ js function fixed this. Another solution would’ve been to split the string into an array before processing it.

    With these lessons learned, I successfully created a working prototype of a solution. You can see the final result here. It has been tested on Firefox 3.5.19, 6.0.2, Chrome 14, IE 9, Safari 5, and Opera 11.01/11.51. Presently there’s an issue with Opera not hooking into the unload event through jQuery, but moving the cookie setting code into the ‘mousedown’ event handler solves this.

  • Popcorn and Soundcloud

    Recently, Popcorn.js began to support custom players. When Henrik Moltke started a conversation going to get Soundcloud working with Popcorn, beautiful things started to happen. Soundcloud and Popcorn developers collaborated to create a Soundcloud player as well as some great plugins. Watch out for upcoming work from Henrik, Mark Boas and more as Mozilla’s Hyper Audio project continues: they’ve been cooking up some great works and demos. The union of Popcorn.js, Soundcloud, Radiolab, combined with Henrik, Mark and many others has produced a great Radiolab Player demo. For my own part in the process, working with everyone has been terrific.

    Popcorn 0.5 has also come out today, and includes some of the results of this effort. A custom player for use with Soundcloud has landed, which can be used with Popcorn simply, like so:

    var popcorn = Popcorn( Popcorn.soundcloud( "contentId", "http://soundcloud.com/fitn/cotton-in-the-ears" } ));

    Using the Soundcloud player with Popcorn like this will place Soundcloud’s player inside the HTML Element on the web page with the corresponding id “contentId”. The Soundcloud player will then play the track found at “http://soundcloud.com/fitn/cotton-in-the-ears”. This can then all be controlled through Popcorn, complete with timed track events. Be sure to check it and more out in the new release.

  • Custom HTML5 Video Objects: Timing

    In my last blog posting, I touched on defining your own implementation of an HTML5 Video. Basically all it takes is to implement the HTMLMediaElement interface on an object by defining the methods and attributes listed. It’s easy. In fact, here’s a starting skeleton I’ve whipped up:

    var undef;
    
    var MediaElement = {
      load: function() {},
      play: function() {},
      pause: function() {},
    
      readyState: 0,
      currentTime: 0,
      duration: 0,
      paused: 1,
      ended: 0,
      volume: 1,
      muted: 0,
      playbackRate: 1
      // These are considered to be "on" by being defined. Initialized to undefined
      autoplay: undef,
      loop: undef,
    };

    Those are a subset of methods and attributes and a give a good start, though there is a whole lot more functionality that may be implemented if desired. Even though we have the attributes, one important mechanism is missing. Videos update at regular intervals, which is something we’ll need to account for in our video object. This is also incredibly easy to do. According to the spec, time updates should occur every “15 to 250ms”:

    var msDelay = 250;
    
    function timerTick() {
      // Run code here
    
      setTimeout( timerTick, msDelay );
    }

    The above code will execute the “timerTick” function every 250 ms. I’ve created a timed loop using setTimeout instead of setInterval because setInterval has the unfortunate side-effects of not firing at reliable times as well as eating errors. In other words, setTimeout is used so that the program will let me know if it’s not working properly, as well as it will not be delayed by other js code that is executing on the page.

    With this in place, these two code snippets can be tied together (with less than 10 extra lines of code) to create a basic video wrapper:

    var undef;
    var msDelay = 250;
    
    var MediaElement = {
      load: function() {},
      play: function() {
        this.paused = 0;
        // So we can keep track of the instance
        timerTick.call( this );
      },
      pause: function() {
        this.paused = 1;
      },
    
      readyState: 0,
      currentTime: 0,
      duration: 0,
      paused: 1,
      ended: 0,
      volume: 1,
      muted: 0,
      playbackRate: 1,
    
      // These are considered to be "on" by being defined. Initialize to undefined
      autoplay: undef,
      loop: undef
    };
    
    function timerTick() {
      // The player was paused since the last time update
      if ( this.paused ) {
        return;
      }
    
      // So we can refer to the instance when setTimeout is run
      var self = this;
    
      // Run code here
    
      setTimeout( function() {
        timerTick.call( self );
      }, msDelay );
    }

    And just like that, you have a custom HTML5 “Video”. Check out a simple demo or view the source here.

  • Defining your own HTML5 Video Object

    With the introduction of HTML5, the <video> element offers a great deal of flexibility and scriptability to web-based video technologies. Popcorn.js takes this and runs with it, allowing everything on the page to work with a video to create great interactive webpages. Just check out what secretrobotron has made to see what I’m talking about. This can be taken further if you wrap non-HTML5 video sources so that they appear to look and act like HTML5 video.

    I’ve been doing a lot of twiddling with this lately, and see lots of applications for it. A simple example is a slideshow, made up of an array of images timed to change every, oh, five seconds or so. This is no different from an ordinary video where thousands of images change at a rate of 24 or more times per second. If this ordinary array of images were wrapped to look like a video, it could then be tied into Popcorn and let loose. Not only could a slideshow be started, stopped and seeked through but other neat options begin to open up.

    What if we want to dynamically caption the slide show images? What if we want to cue an <audio> element to play a sound for different sections of the slide show? What if we want to show additional information about the images or author like Twitter, Google Maps or more? This functionality is readily-available through Popcorn’s plugins. But if we really want to get creative…

    We could make one of the images in the slide show actually be a <canvas> element hosting a Processing.js sketch which plays for a few seconds in the middle of a slideshow. In that Processing.js sketch we could then have JavaScript that runs completely independent of Popcorn but may interact and control it to create a relationship where the player and video feed off of each other. We could also simplify things and just go back to our array of ordinary images but increase the cycling time from once every 5 seconds to once every 1/24 of a second to create fluid motion. Doing this would emulate a video in every sense, but 100% dynamic images means 100% dynamic video content.

    Eventually, I see the only limit being imagination.

    HTML5 Video (like HTML5 Audio) implements a standard interface called “HTMLMediaElement”. You can check out the spec here. To get a video-like object going, all one has to do is have a JavaScript object define the methods and attributes of this interface. Such is the nature of open web, where innovation only requires knowledge and expectation of an interface. While some work in this area has been done for the 0.4 version of Popcorn (out now), the real playground will open for the 0.5 release where it will be as easy to create custom “player plugins” as it is right now to make ordinary plugins.

    Time to start getting inspired.

  • More subtitle formats for Popcorn.js

    What began as a custom subtitle command is growing into a larger amount of work on Popcorn.js. While initially work was being done to include TTXT subtitle support, support for many more standardized formats will soon be popping into Popcorn. This is inspired by the Universal Subtitles project, which supports a variety of formats. As a combination of efforts between Simon and myself, we’re also working on creating parsers for:

    One caveat in this wide support is that, like TTXT before them, the initial implementation will have much of the style information being ignored for now. This won’t affect SBV or standard-compliant SRT files, but the remaining will have their styling information stripped from them… for now. We hope to be supporting style information soon, however. In the mean time those formats that support HTML-compliant in-text styling information will work courtesy of the browser’s native display capabilities.

    For example, since many media players have expanded on the basic SRT support to handle underlining with the <u></u> tags, existing SRT files with these tags will not break. However, SSA-style commands, which follow a syntax like this:

    {\commandArg1} or {\command(Arg1,Arg2,…)}

    are also found in SRT files. Even though styling these tags is not immediately supported, the commands still won’t show up as part of the subtitle text: they will be hidden from view. So if you have a subtitle file and want to use it, what do you do? Just include popcorn, the parser plugin and the subtitle plugin in the web page like so:

    <head>
       <script src="../../popcorn.js"></script>
       <script src="../../plugins/subtitle/popcorn.subtitle.js"></script>
       <script src="popcorn.parserSRT.js"></script>
    </head>

    These files will register all the appropriate code with popcorn, meaning all that’s left is to specify the subtitle file. This is done on the video element via the data-timeline-sources attribute:

    <video id='video' controls data-timeline-sources="data/data.srt" >
      <source id='mp4' src="../../test/trailer.mp4" type='video/mp4; codecs="avc1, mp4a"'>
      <source id='ogv' src="../../test/trailer.ogv" type='video/ogg; codecs="theora, vorbis"'>
    </video>

    And with that bit of work, Popcorn will do what it does best, which is to take care of the rest.

  • Popping up TTXT Support for Popcorn.js

    In a past blog, I discussed some work I’ve had with the GPAC’s TTXT subtitle standard. I’ve begun working on Popcorn.js and after not  too much work, Popcorn is beginning to gain TTXT support. While this would’ve been much more work before the 0.2 re-engineering, plugins are now supported and it’s as simple as registering a parser function for a specific file extension.

    What does this mean?

    For developers, it’s easy to add onto popcorn. Their page covers just about everything you could need to know, and once you learn the intuitive API it’s all systems go. For this initial TTXT support it was as simple as using the existing subtitle plugin and writing a custom parser to convert a TTXT file into subtitle objects. Probably about 40 executable lines of code needed in all.

    For Popcorn.js users, I can see this being quite advantageous as well. With the ease of adding functionality, new features are able to be developed quickly and with minimal impact on what’s already in use by Popcorn.js. This means the web pages using Popcorn can only get more dynamic as time goes on.

    Back to TTXT: It is a robust standard. I’ve studied the spec and am beginning to learn it all, but thus far only the text information from a file is processed; not the styling information One of the benefits of TTXT is it’s rich support for styles down to a per-subtitle, per-character level. This means one subtitle can be half 12pt Arial font, half 36pt Courier. Another subtitle could be all Verdana and in red, except for a desired letter to be blue. This styling information is what I’m least familiar with about the standard.

    My friend Anna has already put the call out if anyone has some more complicated TTXT files to contribute to be studied and run by our parser. I’d like to re-issue the call here, and would be interested in hearing from any developers or film makers who have more familiarity with this standard.

  • Visualization and Emulation of the 6502 Processor in HTML 5

    As a student and as a software developer, I’m constantly trying to learn more, dig deeper and further educate myself on anything related to my field. What has my attention right now is lower-level software development and optimization targeted for specific hardware. There are a great many papers out there written on the subject, specifically optimization practices on Intel hardware and the importance of keeping cache size and cache line size in mind. What really caught my eye in this research, was a mixture of the old and the new.

    In 1970s, there was a 8-bit CPU war going on between (amongst others) Intel and Motorola. Motorola’s team in charge of development of a new chip were soon moved to the small-time MOS company. To make a long story short, the team ended up producing the 6502, a competing 8-bit processor at 1/6 the cost of Intel’s and Motorola’s leading designs, sparking “a series of computer projects that would eventually result in the home computer revolution of the 1980s”. How influential was the 6502? For starters, it came bundled with the wildly popular Commodore, Apple and Atari home computers of the time, with variants of the 6502 also gracing Nintendo’s NES and Atari’s 2600 video game systems.

    Moving forward in history, we now have cutting edge HTML 5 running on web browsers on computers with 1,000,000 times the memory that the Atari 2600 could support (8 KB could still do amazing things). And now, the group from Visual6502.org has made a great visualization of the processor in action using HTML 5’s canvas. The demo comes with a custom program which can be executed step-by-step with each instruction lighting up different transistors on the processor.

    The best part? There’s a github repo: it’s open source.