InnoTab 2 Video Conversion

VTech Innotab 2 video conversion isn’t hard, but getting those settings right the first time can be, so I thought I’d share how I managed it.

The InnoTab 2 needs videos to have the following settings:

File Type AVI
Video Encoder MJPEG
Display Size 480×272
Frame Rate 15 fps
Bit Rate 2400 kbps
Audio Encoder PCM
Audio Channel Mono
Sampling Rate 22.05 kHz
Maximum File Size 2 GB

I have a Mac, so I used Handbrake which is an open source multiplatform video transcoder. It means it’s a free piece of software, that will run on Mac’s, PC’s and Linux boxes, and can be used to transform video from one format to another, such as one that will run on the InnoTab 2.

Once you have Handbrake installed, you need to use the following settings.

The Output Settings Format needs to be MP4 File.

In the video tab you need:

Video Codec: MPEG-4 (FFmpeg
Framerate (FPS): 15
Peak Framerate (VFR): selected
Video Quality: Constant Quality Selected, QP 20

In the audio tab you need:
Codec: AAC (CoreAudio)
Mixdown: Mono
Samplerate: 22.05
Bitrate: 48

In Picture Settings you need:
Width: 480
Height: 272

At this point you may want to save this as new preset, to save entering these details again for each video you want to convert. Click on Preset in the menu bar, and New Present. Call your Preset Name “InnoTab 2”, set the picture size to custom, and enter 480 272 for the width and height. The description is optional so enter something useful here if you want to, then Add.

To use a preset, you need to make sure the Preset Drawer is visible. It should be on the right hand side of the screen, and if not, click on Window in the menu bar, and select Preset Draw. Click on InnoTab 2 to get your InnoTab 2 settings.

Now, to convert a video, click on the Source icon on the top left of the screen. This will let you pick a video. Once selected, choose a name for the Destination File. Make sure you change the extension at the end from .mp4 to .avi, else your InnoTab 2 won’t be able to use the video. Now “Add To Queue”, and “Start”. It may take a while to convert but Handbrake will let you know when it’s ready.

To copy the video to your InnoTab 2, connect it to the your computer. Browse to one of the drives, and click on “LLN” then “MOVIES”. Drag and drop the movie you just converted into this folder. Unmount the InnoTab 2 from your computer and try looking for a movie on it. Your new movie should be at the top of the list and ready to watch.

Downloading A YouTube Movie

YouTube is a great source of videos to watch on your InnoTab 2, but you do need to be able to save them.

There are a few online sites that can help.

I have found an easy one to be You enter a URL of a page with the video you want to download, this can be a YouTube page. Select “Download” and save this so you can load it into Handbrake for conversion to your InnoTab 2.

A word of warning, does launch popup windows, so be aware of this. Also be aware of Copyright and make sure you have the right to download and save a video to your InnoTab 2.


I hope this has helped other Innotab 2 users out there to get video content onto their device.

I have saved these settings to GitHub, so they are ready to import directly into Handbrake, Innotab 2 Handbrake Settings.

POSTing JSON To A Web Service With PHP

I needed to POST JSON formatted data to a RESTful web service using PHP earlier, so I thought I’d share my solution.

There are a couple of approaches that could be taken, using the CURL extension, or file_get_contents and a http context. I took the later way.

When POSTing JSON to a RESTful web service we don’t send post fields or pretend to be a form, instead we have to send the JSON data in body of the request, and let the web service know it’s JSON data by setting the Content-type header to application/json.

$article = new stdClass();
$article->title = "An example article";
$article->summary = "An example of posting JSON encoded data to a web service";

$json_data = json_encode($article);

$post = file_get_contents('http://localhost/rest/articles',null,stream_context_create(array(
    'http' => array(
        'protocol_version' => 1.1,
        'user_agent'       => 'PHPExample',
        'method'           => 'POST',
        'header'           => "Content-type: application/json\r\n".
                              "Connection: close\r\n" .
                              "Content-length: " . strlen($json_data) . "\r\n",
        'content'          => $json_data,

if ($post) {
    echo $post;
} else {
    echo "POST failed";

Here I’m first creating an example PHP stdClass object, populating it with some data, then serialising it to a JSON string. The real magic is using file_get_contents to POST it over HTTP to my test web service. If the POST succeeds, then it’s displayed, else an error message is shown.

It’s important to note I send the header, Connection: close . Without this, your script will hang until the web server closes the connection. If we include it, then as soon as the data has POSTed the connection is closed and control returned to the script.

jQuery To Scroll To A Specific Element

I thought I’d share a useful snippit of jQuery code for scrolling to a specific element on a page.

$('html, body').animate({
    scrollTop: ($('#element').offset().top)

We use the .animate() method to scroll to the top of #element, over a period of 500 milliseconds.

jQuery To Scroll To The First Element With A Specific Class

A practical use of this could be in validating a form and you want to scroll to the first error for the user to correct. Assuming all elements with problems have been given the class of error, we can scroll to the first one using jQuery’s .first() method before chaining on .offset() and the property top as before.

$('html, body').animate({
    scrollTop: ($('.error').first().offset().top)

Now, go get scrolling!

Using SQL Server ntext Columns In PHP

I had to connect to a SQL Server database from a PHP script earlier, and I came across an error I wasn’t expecting.

My SQL was working fine, until I tried to select one particular column, it would then give me a 4004 error. Other columns in this table worked fine, so I investigated more.

The error string returned with the 4004 error code was “Unicode data in a Unicode-only collation or ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.”

Looking at the table definition, the column I was trying to SELECT was of type ntext. This is used to hold UTF-8 data.

By default the driver I had installed for PHP on Ubuntu Linux using

apt-get install php5-sybase

couldn’t understand this UTF-8 data. The solution is to edit the conf file used by freetds, which is the code used to talk to the SQL Server database by the PDO DBLib library.

So, in /etc/freedts/freetds.conf I added these settings

tds version = 8.0
client charset = UTF-8

After adding those settings, I was successfully able to SELECT the ntext column from the SQL Server database.

Unit Testing JavaScript With QUnit And Phing

Recently I’ve been using both Phing for my PHP builds, and QUnit for my JavaScript unit tests, so I’ve been looking for a way to run these QUnit tests when Phing builds my application.

By default Phing can run PHPUnit tests, but not QUnit. However Martin Jonsson has come to the rescue with his Qunit Phing Task.

QUnit Phing Tasks lets QUnit tests be run during a build and Phing can either pass or fail based on these results. As QUnit is written in JavaScript, QUnit Phing Task runs PhantomJS to call a JavaScript wrapper that passes the output back to PHP and Phing. PhantomJS is a headless JavaScript browser that can excute on a command line.

Using QUnit Phing Task

To run the QUnit Phing Task you need to install PhantomJS. I downloaded a binary and placed it in /usr/local/bin on my system.

You need to download the QUnit Phing Task. I placed the files in a local ./lib directory in my project.

You will also need to download QUnit. I placed the files in a local ./tests directory in my project.

In the ./tests directory I created an HTML file called runner.html. This is the page we need to call to run our tests.

<!DOCTYPE html>

                <meta chatset="utf-8" />
                <title>Qunit Tests</title>
                <link rel="stylesheet" href="./qunit.css">
                <script src="./qunit.js"></script>
                <script src="./test.js"></script>

                <div id="qunit"></div>

I also create a JavaScript file called ./test.js in ./tests to hold my JavaScript tests in.

test("testing for true", function() {
        ok(true, "true is true");

Finally, I create a build.xml for my Phing build.

<?xml version="1.0" encoding="UTF-8"?>
<project name="qunit example" basedir="." default="qunit">

        <path id="project.class.path">
                <pathelement dir="./lib/" />

        <taskdef name="qunit" classname="QunitTask">
                <classpath refid="project.class.path" />

        <target name="qunit" description="JavaScript Unit Test">
                <qunit executable="DISPLAY=:0 /usr/local/bin/phantomjs" haltonfailure="true" runner="./lib/run-qunit.js">
                        <fileset dir=".">
                                <include name="tests/runner.html" />


In this I am specifying a path to my ./lib directory as this is where the QUnit Phing Task code is. The path is then used in the taskdeftask which is used to create the <qunit> task. Now when I call <qunit> in my qunit target I just pass in the location of the executable – in this case where PhantomJS is, whether Phing should halt if the QUnit tests fail, and where to find the the JavaScript that runs QUnit. Inside the task, we pass in where our runner pages are, as we only have the one in this example we include it by name tests/runner.html.

Running this gives us the following…

rob@lamp ~/qunitphing> phing
Buildfile: /root/qunitphing/build.xml

qunit example > qunit:

    [qunit] ./tests/runner.html: 1 tests of 1 passed, 0 failed


Total time: 0.3275 seconds

So we can see our tests have passed. Let’s change our test.js so that it fails.

test("testing for true", function() {
        ok(true, "true is true");
        ok(false, "false is true");

This test should fail, as false is not true and will fail the ok assertion.

rob@lamp ~/qunitphing> phing
Buildfile: /root/qunitphing/build.xml

qunit example > qunit:

    [qunit] 1 tests failed on: ./tests/runner.html
    [qunit] Failed test: testing for true (1, 1, 2)
Execution of target "qunit" failed for the following reason: /root/qunitphing/build.xml:13:41: QUnit tests failed

/root/qunitphing/build.xml:13:41: QUnit tests failed
Total time: 0.3258 seconds

So we can see that Phing has failed our build due to the QUnit tests failing, which is what we want.


Although a very simple and contrived example, I hope this has shown you how to add JavaScript unit tests using QUnit to your Phing build.

Using QUnit To Unit Test JavaScript

In this article I wanted to give you an introduction to unit testing in JavaScript using QUnit.

QUnit was originally developed by John Resig for testing jQuery, but it is now a stand alone project, without any dependancies on jQuery.

A quick example of using QUnit

Firstly, you need to download qunit.js and qunit.css, and store them locally.

Secondly you need to create an HTML page something like this to run your tests in.

<!DOCTYPE html>

		<meta charset="utf-8">
		<title>QUnit Example</title>
		<link rel="stylesheet" href="./qunit.css">
		<script src="./qunit.js"></script>
		<script src="./test.js"></script>
		<div id="qunit"></div>

You’ll notice the references to qunit.css and qunit.js are to the two files we downloaded just now. tests.js is the file where we’ll be placing our unit tests, and we’ll be creating this shortly. Finally, you’ll also see a <div> with an id of qunit. Ths is where the results of our unit tests will be displayed.

One of the simpliest tests is testing for true. Create a file called test.js and add the following.

test("testing for true", function() {
	ok(true, "true is true");

This should give us a result like looking like this.

QUnit Results

We can see that one test was successfully run, and that there were no errors found.

The name of our test, “testing for true” is shown, and clicking onto this expands the result and shows our success message “true is true”.

Qunit Results

So what is going on?

Well, we are calling the test function from QUnit, and we are passing in a name for our test – “testing for true”, and a function to execute the test in. Inside this function we calling the assertion ok from QUnit, passing in a value to test for truth against – in this case true, and a message about the assertion – “true is true”.

When the page is loaded into a browser, the script is run and the results of our unit test shown in the qunit <div>.

Testing For Equality

One of the most common unit tests is to compare the expected and actual values from a function.

QUnit has the equal assertion to help us here. Let’s add some more tests to test.js.

test("testing equality", function() {
	equal(1, 1, "1 is 1");
	equal("1","1", ""1" is "1"");
	equal(1, "1", "1 is "1"");
	equal(1, true, "1 is true");
	equal(1, !false, "1 is not false");

Run this and expand the results for “testing equality”, it should look something like this…

Qunit Results

You should see the obvious results such as 1 and 1 being equal, and “1” and “1” being equal. You should also see that 1 is the same as “1” as JavaScript is converting between types and checking the values are the same. Finally, you can see that 1 is also true, and not false, this is because 1 is truthy in JavaScript. The point to remember here is that the equal assertion behaves like JavaScript’s == comparator.

There may be occassions where you need to compare the value and the type, so the number 1 isn’t the same as the string “1”. In these situations we need to use the strictEqual assertion as this works like JavaScript’s === comparator.

Let’s add some more assertions to our “testing equality” test.

	strictEqual(1, "1", "1 is "1"");

Running this we can see that the number 1 is not the same as the string “1”, and QUnit has thrown an error to tell us this.

Qunit Results

However this isn’t very useful, as we know that 1 isn’t really “1”, so we want to test for this. This is where QUnit’s notStrictEqual assertion will come in handy, as it tests for false results.

Replace the strictEqual with the following…

	notStrictEqual(1, "1", "1 is not "1"");

Running this we can see that the number 1 is not the same as the string “1”, and QUnit has tested successfully for this.

QUnit Results

It’s useful to be able to compare objects, so let’s try this but adding the following code…

	var a = {'name' : 'rob'};
	var b = a;
	equal(a, b, "variables a and b are equal");
	b = {'name' : 'rob'};
	equal(a, b, "variables a and b are equal");

Running this we see that our first asserting that a and b are equal is correct, however, creating what looks like the same object and testing equality fails.

QUnit Results

This is because we’re not testing the actual contents of the object, just that the reference the variable points to is the same. In the first case they both point to the same object, in the second case they are different objects.

QUnit has another equality function called deepEqual that compares the content of an object with the content of another object. Let’s change the failing equal in our last example with the deepEqual and try again.

	deepEqual(a, b, "contents of variables a and b are equal");

QUnit Results

Our tests are working again now, as we are now comparing the actual contents of the objects.


QUnit can do much more than just testing for equality and I hope to touch on some of the other functionality in another article soon. However, I hope this basic overview has been a useful introduction to unit testing JavaScript and has provided enough information to get you started in testing your own JavaScript code.

Using Phing To Deploy A PHP Project

Deploying a PHP project to a production or even a staging environment isn’t always as simple as copying a directory. One project I have been working on recently has benefited from using Phing as a deployment system. To deploy my code, I just have to call a single build script, and let Phing do all the hard work.

So what is Phing? Well Phing is a tool based on Apache Ant, specifically designed to build PHP projects. It takes an XML file that defines specific tasks and executes them. It is designed to be platform independent so should be at home running on Windows as well as Unix based systems.

Phing is available using PEAR, and can be installed quickly using the following commands…

pear channel-discover
pear install phing/phing

Hello World! In Phing

It wouldn’t be an overview without a Hello World example. Save the following as build.xml.


Now let’s run this, we just call phing on the command line, and we get something like this back.

rob@lamp /tmp/helloworld> phing
Buildfile: /tmp/helloworld/build.xml

helloworld > helloworld:

     [echo] Hello World!


Total time: 0.0487 seconds

rob@lamp /tmp/helloworld>

So what is going on? Well in the project element we have a default setting of “helloworld”. This tells Phing the target to call by default. We can call this on the command line as well, phing helloworld, so if we have multiple tasks we can create a target for each of those. As you can see we only have a target of “helloworld” in our example. Inside the target we have tasks. In this example, we have a single EchoTask that just prints out the message “Hello World!”.

Adding A Clean Up

There is so much more Phing can do that just print Hello World!. One of the common tasks you may have is to cleanup a deployment directory. Let’s assume you have a build directory, when you call phing clean you want this to be removed. We can add a simple task to do this to our build.xml.


As you can see, as well as adding a target called “clean”, I’ve also added a property called “builddir” with the value “./build”. I can access this later as variable, so when I call the DeleteTask, I can reference this value using ${builddir}, and Phing will delete the directory ./build.

Create an empty directory called build and run this using phing clean.

rob@lamp /tmp/helloworld> phing clean
Buildfile: /tmp/helloworld/build.xml

helloworld > clean:

     [echo] Clean...


Total time: 0.0493 seconds

rob@lamp /tmp/helloworld>

When you check the contents of your working directory you should have found the build directory has been deleted.

Adding A Deployment Target

Deployment is the area where Phing really comes into it’s own. Let’s create a target that creates a build directory then uploads the contents of that via FTP to a remote server.




We’re doing a few things here, first we are deleting the ${builddir}, and creating it from scratch to ensure it is clean. Then we are copying all the files in the current directory across, except for the build directory, any build file with any extension, the docs directory and the tests directory. Then we are FTP’ing up the contents of the ${builddir} using a FTPDeployTask. Assume I have already set a selection of FTP variables earlier using the same syntax as earlier when I defined ${builddir}.

OK, so that is useful, but there are other useful things that could be done as part of the process. We may want our JavaScript minified on production, but not when we are developing. We can add a task to do this as part of the deploy using the JSMinTask.

There are plenty of other tasks that can be usefully integrated, such as running phpcs to ensure your code is meeting coding standards, building your documentation using phpdocumentor, running your phpunit unit tests. If anything fails you can prevent the deployment and stop your site breaking unnecessarily.


This has just been a quick overview of how to use Phing. We’ve seen various simple tasks take place, and we’ve seen we can easily add more tasks to increase functionality and usefulness. In the real world adding tests to check your code before it gets deployed is essential and prevents silly errors hitting your production environment. Taking the time to write a build script will also save you time in the future when you come to make changes to your site and you can’t quite remember how your production environment was setup. Using Phing, you just have to run your build script.

UTF-8 Aware Cron Scripts

I’ve recently been having a spot of bother with UTF-8 data in a Perl script on an old linux box.

Specifically, I have been importing data from a RESTful service that includes the name Michael Bublé. That accented e at the end of Michael’s name has been problematic.

When I run my code from the command line, it imports correctly into my system, however, when run as a cron job, it imports as Michael Bublé. The é is a multibyte character, but the script was trying to read it seperate characters and getting into a muddle.

At first I assumed the service I was consuming had change the encoding, but running via the command line showed no problems. The problem was down a difference between the command line and cron environments.

Checking the locale using the locale command I got this on the command line…


… but when running that command as a cron job and piping the results to a file in /tmp, I got the following…


Cron jobs were being executed that weren’t UTF-8 aware. The solution was to set the LANG in the /etc/environment file like this…


… then restart the cron daemon using

/etc/rc.d/init.d/crond restart

Now my scripts can successfully import multibyte UTF-8 data correctly when run on the command line or as a cron job.

The /etc/environment file is used to set variables that specify the basic environment for all processes so should be the best place to set the lANG variable.

Recursive Functions In PHP

Recursive functions can be very useful when developing in PHP.

A recursive function is simply a function that calls itself, but why would you want your function to be able to call itself?

They are best used when a problem needs to be solved by breaking it up into a smaller instance of itself. Examples of this would be calculation a factorial or the Fibonacci Series.

Let’s take a look at the Fibonacci Series as an example. The series looks like this…

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, …

It can be described using the following formula,

Fn = Fn-1 + Fn-2

with the seed values,

F0 = 0, F1 = 1

As you can see in the formula’s definition, it has to call itself for n-1 and n-2 to work out the current value for n.

So how would we write this in PHP?

A simple function like this should do the trick.

function fib($n) {
	if ($n < 0) {
		return NULL;
	} elseif ($n === 0) {
		return 0;
	} elseif ($n === 1 || $n === 2) {
		return 1;
	} else {
		return fib($n-1) + fib($n-2);

As you can see I have added some guard statements, so if $n is 0, we return NULL (as the Fibonacci series starts at 0 and works up from there), for 0 we know the seed value is 0 and for 1 and 2 we know the seed values are 1. As we now know the start of the series, we can call our function to work out any part of the series.

For very large values of $n, there will be a lot of recursion, and this could use a lot of computer resources. Each call to fib (apart from to values 0, 1 & 2) costs us at least two more calls to fib, and these calls could be making more calls as it recurses. For example, when $n is 19, there would be 8361 calls made to the fib function to calculate the result, and when $n is 29, there would be 1028457 calls. It’s easy to see that although this is a very simple formula, it can end up being very expensive to use.

However, we can optimise the code and make things easier. We are constantly calculating the same values multiple times, so this should be telling you that this is an ideal candidate for caching.

Let’s modify our function to keep already calculated values of $n in an array and return those if possible rather than recalculating each call.

function fib($n) {
	static $cache;

	if ($n < 0) {
		return NULL;
	} elseif ($n === 0) {
		return 0;
	} elseif ($n === 1 || $n === 2) {
		return 1;
	} else {
		if (!(!is_null($cache) && array_key_exists($n, $cache))) {
			$cache[$n] = fib($n-1) + fib($n-2);
		return $cache[$n]; 

Here we are using a static variable to persist the $cache between calls. Then before recursively calling the fib function we check if the $cache isn’t null and if the $cache has data stored with the key value of $n. If it doesn’t we calculate the can cache the data. Finally we return the value from the cache.

Now when we call the function for when $n = 19, our function is only called 35 times, and for $n = 29, our function is only called 55 times. That’s saved us 1028402 calls!

I hope this has been a useful quick look at recursive functions using PHP.

Replacing Text In A MySQL Database

There are times when you find yourself having to rename data in your MySQL database based on a specific pattern.

I had this very problem today. A designer had changed the dimensions of the thumbnails on a website and needed the data in the database updated to reflect the new path if they were stored in a specific directory.

My first thought was to write a script to iterate through every row in the database, extract the data, manipulate it, then write it back. Thankfully, warning bells rang in my head and I thought about the problem again.

MySQL offers various string manipulate routines and the REPLACE takes a string, a substring to match, and a replacement to insert if a match occurs.

UPDATE artists 
SET thumbnail_url=REPLACE(thumbnail_url, '/160x90/','/150x84/') 
WHERE thumbnail_url IS NOT NULL;

This SQL goes through each row in the artists table where the thumbnail_url is not null, replacing each instance of /160×90/ with /150×84/, keeping the other data intact.