stbt.py: Incorrect first-pass "matched" text in match visualisation debug output

`stbt run -vv` and `stbt templatematch -v` output an html file in
`./stbt-debug/detect_match/*/index.html` to aid debugging of match
problems.

For the first-pass result, this file was saying "Matched" even when it
didn't match.

Note that the first-pass of the matching algorithm uses a "pyramid"
optimisation, where it operates on smaller versions (higher pyramid
levels) of the source & template images; only if a match is found does
it try the next larger version (lower level) of the images. Thus, if
there exists a lower level, it means that the higher level matched.
At the lowest level, we check `first_pass_matched`.

Really all of this information should be passed to
`_log_image_descriptions`, perhaps using the observer pattern, so that
`_log_image_descriptions` doesn't have to figure it out by inference.

Note also that the `levels` passed in to `jinja2.Template.render` is now
used more than once, so it has to be a list, not a lazy sequence.
test_runner_results_server: Fix curl IPv6 failures

Depending on which network I was connected to when I ran the tests,
"test_runner_results_server" and
"test_runner_results_server_shows_directory_listing" would fail with:

    curl: (7) Failed to connect to localhost port 5787: Connection refused

Manually starting up the server and running curl in verbose mode
revealed the problem:

    $ extra/runner/server localhost:5787 &
     * Running on http://localhost:5787/

    $ curl -v http://localhost:5787/
    * Hostname was NOT found in DNS cache
    *   Trying ::1...
    [...]
    * connect to ::1 port 5787 failed: Connection refused
    *   Trying fe80::1...
    * Connection failed
    * connect to fe80::1 port 5787 failed: Connection refused
    * Closing connection 0
    curl: (7) Failed to connect to localhost port 5787: Connection refused

Removing the IPv6 entries for localhost from /etc/hosts fixes this, but
obviously it isn't the correct solution. So I've made the server and
curl both explicitly use 127.0.0.1 (the IPv4 localhost address).

My version of curl is 7.34.0. This curl bug is possibly the same as
http://curl.haxx.se/mail/lib-2012-03/0045.html

Other tests that use "localhost" (such as "test_irnetbox_proxy") but
don't use curl, don't suffer from this problem.
stbt.MatchResult: Refactor: Implement as class, not namedtuple

The user-facing Python API remains the same. I'm making this change so
that in the next commit I can add an optional argument to the
`MatchResult` constructor.

I also simplified a caller that instantiates `MatchResult` to use
positional instead of keyword arguments, to avoid unnecessary
repetition. Both the class definition and the caller are in the same
file, and anyway we shouldn't ever reorder the `MatchResult` arguments
because that would break backwards compatibility with user code in a
very confusing way.
MatchTimeout.screenshot is the exact frame that wait_for_match saw

...instead of a frame captured a split-second after the match failure.

Why? So that the screenshot saved by `stbt run` (when the user's script
raises a `MatchTimeout`) shows exactly the same frame that failed the
match. We have seen situations where a UI item is *just* too slow to
appear, and fails a `wait_for_match`, but appears in the screenshot --
very confusing to users. More annoying still, sometimes there are minute
differences (in colour? brightness? encoder artifacts?) between
subsequent frames, such that a false no-match causes a `MatchTimeout` to
be raised but the screenshot saved by `stbt run` does actually match.

Another practical use is that the `MatchResult.frame` returned from
`wait_for_match` can be fed directly into, for example, an OCR function.

`MatchResult` now has a `frame` member. Each `MatchResult` yielded by
`detect_match` includes the video frame that `detect_match` checked, and
`wait_for_match` uses this frame for the `MatchTimeout.screenshot`
parameter, instead of calling `get_frame` to fetch a new frame from the
GStreamer pipeline.

Notes:

* The match visualisation (the red or yellow rectangle drawn on the
  video output) is done on a different copy of the frame that is
  attached to the `MatchResult`, so that users of the
  `MatchResult.frame` see a pristine screenshot.

* In `wait_for_match` we disable the pylint warning W0631 ("Using
  possibly undefined loop variable 'res'") because we know that
  `frames` (and thus `detect_match`) will always yield at least one
  frame, and thus `res` will always be set after the loop.

* In theory we should also apply a similar change to `MotionTimeout`,
  for consistency's sake; but I am not aware of any practical need for
  that.
Show stbt.MatchResult frame=None deprecation warning

The deprecation warning introduced in eb658d20 wasn't shown by the
existing warnings filter. I have added the word "stb-tester" into all
other deprecation warnings in the stbt module, and changed the warnings
filter to match.
stbt.ocr: Perform Optical Character Recognition using Tesseract

Tesseract is an open-source (Apache License 2.0) OCR engine.

Note that we use tesseract's command-line interface instead of an
existing Python wrapper, to avoid licensing restrictions
(python-tesseract and pyocr are GPL) and deployment difficulties (none
of the python wrappers are available in mainstream Linux distributions'
package repositories, so stb-tester users would have to use `pip` or a
similar Python packaging system). To use `stbt.ocr` you only need to
install Tesseract, which is available in Fedora ("tesseract"),
Debian/Ubuntu ("tesseract-ocr"), and macports ("tesseract") package
repositories.

TODO: Replace the `_Rect` class used by the image processing code with
the new `Region` class.

TODO: Add more-convenient ways of specifying a region. For example,
search for a label using `wait_for_match`, then specify the region
immediately to the right of that label (offsetting the region by the
width of the label template image).

Note that the unit test `test_ocr_on_static_images` violates our
standard 80-character line width, but only for the tabular test
data (which is more readable that way), not for the code. I think this
is an acceptable violation of the standard. Note that pylint only
applies this exemption inside of the array literal that contains the
"pylint: disable" directive.
stbt.ocr: Can specify Tesseract's page segmentation mode

If you have narrowed the region down to contain a single line of text,
you will often get better results with the `SINGLE_LINE` mode.

We default to Tesseract's default mode (fully automatic page
segmentation, but no Orientation or Script Detection).
stbt.Position: Tidy up docstring
Merge branch 'ocr'

* ocr:
  stbt.Position: Tidy up docstring
  stbt.ocr: Can specify Tesseract's page segmentation mode
  stbt.ocr: Perform Optical Character Recognition using Tesseract
  Show stbt.MatchResult frame=None deprecation warning
  MatchTimeout.screenshot is the exact frame that wait_for_match saw
  stbt.MatchResult: Refactor: Implement as class, not namedtuple
stbt.OcrMode: Add docstring with link to Tesseract manual
stbt.ocr: Use $XDG_RUNTIME_DIR and mkstemp for temporary files

On systems that support it, `$XDG_RUNTIME_DIR` is likely to be a tmpfs
(which is more appropriate for these short-lived files) and unlike
`/tmp` is only readable/writable by the user. On systems that don't set
`$XDG_RUNTIME_DIR`, we just use `mkstemp`'s default (the standard Unix
`$TMPDIR`). See the XDG Base Directory Specification:
http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html

`mktemp` is deprecated, though I'm not convinced that, in this
particular scenario, `mkstemp` is any more secure: We don't pass a
filehandle to tesseract, we pass the file *name*, so an attacker could
still overwrite the temporary file after it was created my `mkstemp` but
before tesseract reads from / writes to it. I suppose that the benefit
of `mkstemp` in this case is to avoid a race conditions where 2
processes calling `mktemp` at the same time could get the same filename
back (though I imagine that this is very unlikely).
extra/runner report: Do not show "404" while the first test is running

It's quite misleading that there is no index.html in the test results
directory until the first test is completed; users new to `runner`
might think that they entered the wrong address or an error occurred
when they are trying to open the test results.

Generate a row in the table of the index page while a test is being
executed. It has white background with grey text, and the exit status
is "still running".

This is done by skipping `report` if it's run with no arguments or
--classify-only and no exit-status is found in the test run directory,
but executing it if it's run with --html-only.
extra/runner summary report: Display the plot when no passed test

jqplot has a limitation that it considers the data set passed to its
constructor invalid if `plotSeries[0]` is an empty array, which is
the case when no completed tests passed.

Work around this limitation by passing `null` to `plotSeries[0]`
before the constructor is invoked, and removing the fake element
afterwards. It's only the constructor that has the limitation,
`plot1.replot()` is working fine if `plotSeries[0]` is empty.
extra/runner summary report: Remove dash from exit status "still running -"
extra/runner report: Don't show details pane for "still running" test

This makes the row of the test non-clickable, and skipped by the up/down
arrow keyboard navigation.

Reasons:

- The page doesn't contain any valuable information until the testrun
  has completed.
- The user mustn't hide the page with the "[Hide this result]" link.
Merge branch 'runner-to-add-index-page-at-start'

* runner-to-add-index-page-at-start:
  extra/runner report: Don't show details pane for "still running" test
  extra/runner summary report: Remove dash from exit status "still running -"
  extra/runner summary report: Display the plot when no passed test
  extra/runner report: Do not show "404" while the first test is running
stbt.ocr: Avoid leaking file descriptors

This avoids leaking file descriptors[1], and is neater because
`NamedTemporaryFile` handles removing the files after us.

Also set a filename prefix of "stbt-ocr-" in case some files get left
behind in /tmp, so that you can easily identify the culprit.

Thanks to Will Manley for review & advice.

Note that we already use multiple "with" expressions elsewhere in
stbt.py, so this isn't introducing a new incompatibility with python
2.6.

I had real trouble getting a `with` statement split over multiple lines
to look nice *and* comply with pylint, so I need to use
`functools.partial` to make the `with` expressions shorter.

[1] http://www.logilab.org/blogentry/17873
stbt.py: Refactor mask loading into separate function

This refactors the code that loads an image mask from a file. It was
moved from `detect_motion` to a new function `_load_mask(mask)`.

This is needed in the subsequent commit, which would benefit from the
checks that the existing code performs. It would also ensure that mask
loading errors are consistent throughout stb-tester.
stbt.py: Adds `black_screen` function and 4x tests

This adds a new function `black_screen` to detect the presence of a
black screen in a video frame. It converts the video frame to grayscale,
applies a binary threshold [1] with an optional mask, and then checks
that the maximum intensity value is zero. It returns `True` if it
detects a black screen and `False` otherwise.

The logic was copied from code in the existing test
`test_using_frames_to_measure_black_screen` added in commit c96503e.
However, this version adds an optional image `mask` as well as making
the threshold value configurable.

This adds new tests for `stbt.black_screen()`:
1. `test_that_black_screen_is_true_for_black_pattern`
2. `test_that_black_screen_is_false_for_smpte_pattern`
3. `test_that_black_screen_is_true_for_smpte_pattern_when_masked`
4. `test_black_screen_threshold_bounds_for_almost_black_frame`

This also adds two new images:
* `tests/videotestsrc-mask-non-black.png`: An image mask for videotestsrc
  that masks all the non-black pixels (used by test 3).
* `tests/almost-black.png`: A 720p screenshot of a typical STB black
  screen captured with a Blackmagic card (used by test 4). It is
  detected as a black screen when `threshold>=3` but not when
  `threshold<3`.

[1] OpenCV Tutorials: Basic Thresholding Operations
    http://docs.opencv.org/doc/tutorials/imgproc/threshold/threshold.html
test_using_frames_to_measure_black_screen: Use `stbt.black_screen()`

This removes the redundant function `is_black_screen()` from the Python
code in the test and replaces the the function call with
`stbt.black_screen()`. The latter function was added in the previous
commit.