stbt.py: Refactor: Separate source & sink pipelines, joined with app{sink,src}

This will allow the caller of `stbt.Display.frames` to modify the
GStreamer buffer (the video frame) before passing it to the sink
pipeline. The next commit will do just that.

This is very similar to 5a0770e6's change to the source restarting
mechanism (which was reverted in a189e0c9) but using appsink/appsrc
instead of udpsink/udpsrc.

The implementation is as follows. We split the GStreamer pipeline into
two separate pipelines: A "source pipeline" ending in an appsink, and a
"sink pipeline" starting with an appsrc.

    -source pipeline--   on_new_buffer/frames   -sink pipeline--
    | ... ! appsink  |  --------buffer------->  | appsrc ! ... |
    ------------------                          ----------------

Every time a new buffer is available on the source pipeline's appsink,
we push it to the sink pipeline's appsrc (see `Display.on_new_buffer`).

But when we're inside `Display.frames` (i.e. inside `wait_for_match` or
similar) we *don't* want to display new frames, we only want to display
the frames processed by `wait_for_match`. Note that the `wait_for_match`
image-processing algorithm is slow, so it only processes one out of
every few frames (and we drop the rest). If we displayed the unprocessed
frames in between the frames that `wait_for_match` *did* process, the
user wouldn't see the `wait_for_match` visualisation (see the next
commit) because it would only be present in one out of every few frames.

So we use a lock to disable `on_new_buffer` while we're inside `frames`.
Note that `frames` calls arbitrary user code (via `yield`) which may
throw an exception; thus exceptions from `frames` are not necessarily
fatal and may even be caught in the calling user code. So it's important
that `frames` always releases the lock.

Note that `stbt.get_frame` can be safely called at any time -- we don't
need to lock there, because `Display.last_frame` has its own locking
built-in. `Display.on_new_buffer` pushes the buffer to
`Display.last_frame` even when the lock is held by `Display.frames`, in
case the user calls `stbt.get_frame`.

Note that `Display.init` keeps a reference to `sink_pipeline`, even
though it isn't referenced elsewhere, just to keep it alive.
stbt.py: Match & motion visualisation

This fixes the regression introduced in ca4201df.

Match: Show the red/yellow "wait_for_match" rectangle.

Motion: The visualisation has changed slightly from the pre-ca4201df
visualisation. Instead of flashing the whole screen red, just highlight
in red the areas where motion is detected. Note that we dilate the area
just to make it slightly more obvious. Also unlike the pre-ca4201df,
we don't darken the masked-out areas. Instead, the mask will be obvious
if there is any motion passing through the masked-out area.

Implementation notes
--------------------

I'm not 100% sure whether or not we're copying buffers more than is
necessary.

I *think* that we're *not* copying data from the GStreamer buffer into
the OpenCV/numpy array:

    >>> image = gst_to_opencv(gst_buffer)
    >>> print image.flags
    OWNDATA : False
    WRITEABLE : False
    ...

Compare with:

    >>> image2 = image.copy()
    >>> print image2.flags
    OWNDATA : True
    WRITEABLE : True
    ...

However:

    >>> print id(gst_buffer.data)
    4418195456
    >>> print id(image.base)
    4418195456
    >>> print id(image.data)
    4418004912

What is "image.data" and why is it different to "gst_buffer.data"?

It *is* possible to modify the OpenCV image (e.g. with "cv2.rectangle").
The changes aren't reflected in the GStreamer buffer.

    >>> cv2.rectangle(image, pt1, pt2, color)
    >>> cv2.imwrite("image.png", image)
    >>> appsrc.emit("push-buffer", gst_buffer)
    >>> print id(image.base)
    4418195456
    >>> print id(image.data)
    4418004912

Note that "image.data" is still pointing at the same location in memory,
so there doesn't seem to be any copy-on-write going on. Maybe we *did*
do a copy from the GStreamer buffer when we created the OpenCV/numpy
image? I know that the rectangle *is* present in the OpenCV image,
because it's there when I open "image.png" in an image viewer. The
rectangle isn't present in the xvimagesink that is showing the GStreamer
buffers from appsrc.

I also couldn't figure out how to modify the GStreamer buffer data
directly. I tried this:

    >>> data = memoryview(gst_buffer.data)
    >>> data[0] = 0
    TypeError: cannot modify read-only memory

"memoryview" is the python interface to directly reading or writing
memory without copying. It only works on data structures implemented in
a python C extension where the data structure implements the python C
api's "buffer" interface.

I couldn't even modify the memory of a new buffer, where the memory
is allocated by GStreamer:

    >>> newbuf = gst.buffer_new_and_alloc(gst_buffer.size)
    >>> data = memoryview(newbuf.data)
    >>> data[0] = 0
    TypeError: cannot modify read-only memory

I don't know if this is because the GStreamer python bindings don't
support python's memoryview/buffer interface, or because GStreamer has
marked this memory as read-only.

Note that memoryview will fail if given an object that doesn't implement
the buffer interface:

    >>> memoryview([1,2,3,4,5])
    TypeError: cannot make memory view because object does not have the
               buffer interface

However, it could be that GStreamer is just providing a python string,
which is immutable:

    >>> m = memoryview("12345")
    >>> m
    <memory at 0x11070f510>
    >>> m[0] = 0
    TypeError: cannot modify read-only memory

In the end I had to create a new GStreamer buffer pointing at the OpenCV
image:

    >>> newbuf = gst.Buffer(image.data)
    >>> newbuf.set_caps(gst_buffer.get_caps())
    >>> newbuf.timestamp = gst_buffer.timestamp
    >>> self.appsrc.emit("push-buffer", newbuf)

This works perfectly so far. I don't know if this copies the data, or
merely points at it. If it doesn't copy the data, I don't understand who
owns the image.data memory, but it seems to survive unharmed all the way
to the xvimagesink and to the recorded video, so maybe the GStreamer
python bindings take ownership of it in such a way that python doesn't
garbage-collect it.

I'm satisfied that this is good enough for now. Performance seems much
the same as before, but I haven't done any measurements; I'm just
estimating based on the visible frame rate. The `wait_for_match`
algorithm is so slow that it dwarfs any performance effects from this
commit. However I might try to understand the copying (or not) behaviour
more thoroughly when I port to GStreamer 1.0.
stbt.Display.frames: Display the last frame processed

When `frames` is called from `wait_for_match`, this is usually the frame
that contains the match.

(Once a match is found, `wait_for_match` stops iterating over the
`frames` generator, so the code after the `yield` wasn't being run for
the frame with the match. The `finally` block presumably gets run when
the generator object is destroyed -- in the CPython implementation this
will be when `wait_for_match` returns.)
stbt.Display.__init__: Move member variables to the top of the function

`Display.on_new_buffer` was failing with:

    AttributeError: Display instance has no attribute 'lock'

I don't fully understand how `Display.on_new_buffer` is being called
*before* we've called `_mainloop.run()` (which is called after
`Display.lock` has been defined). If I take out the GLib mainloop
altogether, `stbt run` still functions correctly! Maybe the GStreamer
*signal* handlers are called from the corresponding GStreamer element's
thread, and we only need the GLib mainloop for handling GStreamer bus
*messages*.