Raspivid v Gst-rpicamsrc (Updated)

Introduction

User bocorps pointed me in the direction of gst-rpicamsrc.  This is “… a GStreamer wrapper around the raspivid/raspistill functionality of the RaspberryPi, providing a GStreamer source element capturing from the Rpi camera.”

What this means is that instead of piping the output of raspivid into gstreamer, gstreamer has a source element to read the camera directly.  This is similar to using the video4linux (v4l) source element, but negates the need for a v4l driver.

My hope was that by integrating the camera functionality into a gstreamer source element the latency would be reduced.  Unfortunately, I actually saw an 18% increase in latency.

Installation

Before I could use the gst-rpicamsrc element, I needed to download the source and build it.  As I was working with a minimal install of Raspbian Jessie, I needed to install the git package before I could do anything else

sudo apt-get install git

With git installed I could download the latest sources for gst-rpicamsrc.

git clone https://github.com/thaytan/gst-rpicamsrc.git

With that done a look in the REQUIREMENTS file indicated what other packages were needed in order to accomplish the build.

sudo apt-get install autoconf automake libtool libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev libraspberrypi-dev

Finally, I was able to complete the build and install.

./autogen --prefix=/usr --libdir=/usr/lib/arm-linux-gnueabihf/
make
sudo make install

The command `gst-inspect-1.0 rpicamsrc’ produces a list of the available parameters.

Factory Details:
  Rank                     none (0)
  Long-name                Raspberry Pi Camera Source
  Klass                    Source/Video
  Description              Raspberry Pi camera module source
  Author                   Jan Schmidt <jan@centricular.com>

Plugin Details:
  Name                     rpicamsrc
  Description              Raspberry Pi Camera Source
  Filename                 /usr/lib/arm-linux-gnueabihf/gstreamer-1.0/libgstrpicamsrc.so
  Version                  1.0.0
  License                  LGPL
  Source module            gstrpicamsrc
  Binary package           GStreamer
  Origin URL               http://gstreamer.net/

GObject
 +----GInitiallyUnowned
       +----GstObject
             +----GstElement
                   +----GstBaseSrc
                         +----GstPushSrc
                               +----GstRpiCamSrc

Pad Templates:
  SRC template: 'src'
    Availability: Always
    Capabilities:
      video/x-h264
                  width: [ 1, 2147483647 ]
                 height: [ 1, 2147483647 ]
              framerate: [ 0/1, 2147483647/1 ]
          stream-format: byte-stream
              alignment: au
                profile: { baseline, main, high }


Element Flags:
  no flags set

Element Implementation:
  Has change_state() function: gst_base_src_change_state

Element has no clocking capabilities.
Element has no URI handling capabilities.

Pads:
  SRC: 'src'
    Implementation:
      Has getrangefunc(): gst_base_src_getrange
      Has custom eventfunc(): gst_base_src_event
      Has custom queryfunc(): gst_base_src_query
      Has custom iterintlinkfunc(): gst_pad_iterate_internal_links_default
    Pad Template: 'src'

Element Properties:
  name                : The name of the object
                        flags: readable, writable
                        String. Default: "rpicamsrc0"
  parent              : The parent of the object
                        flags: readable, writable
                        Object of type "GstObject"
  blocksize           : Size in bytes to read per buffer (-1 = default)
                        flags: readable, writable
                        Unsigned Integer. Range: 0 - 4294967295 Default: 4096 
  num-buffers         : Number of buffers to output before sending EOS (-1 = unlimited)
                        flags: readable, writable
                        Integer. Range: -1 - 2147483647 Default: -1 
  typefind            : Run typefind before negotiating
                        flags: readable, writable
                        Boolean. Default: false
  do-timestamp        : Apply current stream time to buffers
                        flags: readable, writable
                        Boolean. Default: true
  bitrate             : Bitrate for encoding
                        flags: readable, writable
                        Integer. Range: 1 - 25000000 Default: 17000000 
  preview             : Display preview window overlay
                        flags: readable, writable
                        Boolean. Default: true
  preview-encoded     : Display encoder output in the preview
                        flags: readable, writable
                        Boolean. Default: true
  preview-opacity     : Opacity to use for the preview window
                        flags: readable, writable
                        Integer. Range: 0 - 255 Default: 255 
  fullscreen          : Display preview window full screen
                        flags: readable, writable
                        Boolean. Default: true
  sharpness           : Image capture sharpness
                        flags: readable, writable
                        Integer. Range: -100 - 100 Default: 0 
  contrast            : Image capture contrast
                        flags: readable, writable
                        Integer. Range: -100 - 100 Default: 0 
  brightness          : Image capture brightness
                        flags: readable, writable
                        Integer. Range: 0 - 100 Default: 50 
  saturation          : Image capture saturation
                        flags: readable, writable
                        Integer. Range: -100 - 100 Default: 0 
  iso                 : ISO value to use (0 = Auto)
                        flags: readable, writable
                        Integer. Range: 0 - 3200 Default: 0 
  video-stabilisation : Enable or disable video stabilisation
                        flags: readable, writable
                        Boolean. Default: false
  exposure-compensation: Exposure Value compensation
                        flags: readable, writable
                        Integer. Range: -10 - 10 Default: 0 
  exposure-mode       : Camera exposure mode to use
                        flags: readable, writable
                        Enum "GstRpiCamSrcExposureMode" Default: 1, "auto"
                           (0): off              - GST_RPI_CAM_SRC_EXPOSURE_MODE_OFF
                           (1): auto             - GST_RPI_CAM_SRC_EXPOSURE_MODE_AUTO
                           (2): night            - GST_RPI_CAM_SRC_EXPOSURE_MODE_NIGHT
                           (3): nightpreview     - GST_RPI_CAM_SRC_EXPOSURE_MODE_NIGHTPREVIEW
                           (4): backlight        - GST_RPI_CAM_SRC_EXPOSURE_MODE_BACKLIGHT
                           (5): spotlight        - GST_RPI_CAM_SRC_EXPOSURE_MODE_SPOTLIGHT
                           (6): sports           - GST_RPI_CAM_SRC_EXPOSURE_MODE_SPORTS
                           (7): snow             - GST_RPI_CAM_SRC_EXPOSURE_MODE_SNOW
                           (8): beach            - GST_RPI_CAM_SRC_EXPOSURE_MODE_BEACH
                           (9): verylong         - GST_RPI_CAM_SRC_EXPOSURE_MODE_VERYLONG
                           (10): fixedfps         - GST_RPI_CAM_SRC_EXPOSURE_MODE_FIXEDFPS
                           (11): antishake        - GST_RPI_CAM_SRC_EXPOSURE_MODE_ANTISHAKE
                           (12): fireworks        - GST_RPI_CAM_SRC_EXPOSURE_MODE_FIREWORKS
  metering-mode       : Camera exposure metering mode to use
                        flags: readable, writable
                        Enum "GstRpiCamSrcExposureMeteringMode" Default: 0, "average"
                           (0): average          - GST_RPI_CAM_SRC_EXPOSURE_METERING_MODE_AVERAGE
                           (1): spot             - GST_RPI_CAM_SRC_EXPOSURE_METERING_MODE_SPOT
                           (2): backlist         - GST_RPI_CAM_SRC_EXPOSURE_METERING_MODE_BACKLIST
                           (3): matrix           - GST_RPI_CAM_SRC_EXPOSURE_METERING_MODE_MATRIX
  awb-mode            : White Balance mode
                        flags: readable, writable
                        Enum "GstRpiCamSrcAWBMode" Default: 1, "auto"
                           (0): off              - GST_RPI_CAM_SRC_AWB_MODE_OFF
                           (1): auto             - GST_RPI_CAM_SRC_AWB_MODE_AUTO
                           (2): sunlight         - GST_RPI_CAM_SRC_AWB_MODE_SUNLIGHT
                           (3): cloudy           - GST_RPI_CAM_SRC_AWB_MODE_CLOUDY
                           (4): shade            - GST_RPI_CAM_SRC_AWB_MODE_SHADE
                           (5): tungsten         - GST_RPI_CAM_SRC_AWB_MODE_TUNGSTEN
                           (6): fluorescent      - GST_RPI_CAM_SRC_AWB_MODE_FLUORESCENT
                           (7): incandescent     - GST_RPI_CAM_SRC_AWB_MODE_INCANDESCENT
                           (8): flash            - GST_RPI_CAM_SRC_AWB_MODE_FLASH
                           (9): horizon          - GST_RPI_CAM_SRC_AWB_MODE_HORIZON
  image-effect        : Visual FX to apply to the image
                        flags: readable, writable
                        Enum "GstRpiCamSrcImageEffect" Default: 0, "none"
                           (0): none             - GST_RPI_CAM_SRC_IMAGEFX_NONE
                           (1): negative         - GST_RPI_CAM_SRC_IMAGEFX_NEGATIVE
                           (2): solarize         - GST_RPI_CAM_SRC_IMAGEFX_SOLARIZE
                           (3): posterize        - GST_RPI_CAM_SRC_IMAGEFX_POSTERIZE
                           (4): whiteboard       - GST_RPI_CAM_SRC_IMAGEFX_WHITEBOARD
                           (5): blackboard       - GST_RPI_CAM_SRC_IMAGEFX_BLACKBOARD
                           (6): sketch           - GST_RPI_CAM_SRC_IMAGEFX_SKETCH
                           (7): denoise          - GST_RPI_CAM_SRC_IMAGEFX_DENOISE
                           (8): emboss           - GST_RPI_CAM_SRC_IMAGEFX_EMBOSS
                           (9): oilpaint         - GST_RPI_CAM_SRC_IMAGEFX_OILPAINT
                           (10): hatch            - GST_RPI_CAM_SRC_IMAGEFX_HATCH
                           (11): gpen             - GST_RPI_CAM_SRC_IMAGEFX_GPEN
                           (12): pastel           - GST_RPI_CAM_SRC_IMAGEFX_PASTEL
                           (13): watercolour      - GST_RPI_CAM_SRC_IMAGEFX_WATERCOLOUR
                           (14): film             - GST_RPI_CAM_SRC_IMAGEFX_FILM
                           (15): blur             - GST_RPI_CAM_SRC_IMAGEFX_BLUR
                           (16): saturation       - GST_RPI_CAM_SRC_IMAGEFX_SATURATION
                           (17): colourswap       - GST_RPI_CAM_SRC_IMAGEFX_COLOURSWAP
                           (18): washedout        - GST_RPI_CAM_SRC_IMAGEFX_WASHEDOUT
                           (19): posterise        - GST_RPI_CAM_SRC_IMAGEFX_POSTERISE
                           (20): colourpoint      - GST_RPI_CAM_SRC_IMAGEFX_COLOURPOINT
                           (21): colourbalance    - GST_RPI_CAM_SRC_IMAGEFX_COLOURBALANCE
                           (22): cartoon          - GST_RPI_CAM_SRC_IMAGEFX_CARTOON
  rotation            : Rotate captured image (0, 90, 180, 270 degrees)
                        flags: readable, writable
                        Integer. Range: 0 - 270 Default: 0 
  hflip               : Flip capture horizontally
                        flags: readable, writable
                        Boolean. Default: false
  vflip               : Flip capture vertically
                        flags: readable, writable
                        Boolean. Default: false
  roi-x               : Normalised region-of-interest X coord
                        flags: readable, writable
                        Float. Range:               0 -               1 Default:               0 
  roi-y               : Normalised region-of-interest Y coord
                        flags: readable, writable
                        Float. Range:               0 -               1 Default:               0 
  roi-w               : Normalised region-of-interest W coord
                        flags: readable, writable
                        Float. Range:               0 -               1 Default:               1 
  roi-h               : Normalised region-of-interest H coord
                        flags: readable, writable
                        Float. Range:               0 -               1 Default:               1

Usage

Because of the way gstreamer works, the parameters for the feed needed to be split and re-arranged in the streamer pipeline. Previously all the parameters are specified as part of raspivid.

/opt/vc/bin/raspivid -t $DURATION -w $WIDTH -h $HEIGHT -fps $FRAMERATE -b $BITRATE -n -pf high -o - | gst-launch-1.0 -v fdsrc ! 

GStreamer parameters like width, height and frame rate are configured through capabilities (caps) negotiation with the next element. Other parameters like the bit rate and preview screen are controlled as part of the source element.

gst-launch-1.0 rpicamsrc bitrate=$BITRATE preview=0 ! video/x-h264,width=$WIDTH,height=$HEIGHT,framerate=$FRAMERATE/1 !

The new stream script is

#!/bin/bash

source remote.conf

if [ "$1" != "" ]
then
  export FRAMERATE=$1
fi

NOW=`date +%Y%m%d%H%M%S`
FILENAME=$NOW-Tx.h264

gst-launch-1.0 rpicamsrc bitrate=$BITRATE preview=0 ! video/x-h264,width=$WIDTH,height=$HEIGHT,framereate=$FRAMERATE/1,profile=high ! h264parse ! rtph264pay config-interval=1 pt=96 ! udpsink host=$RX_IP port=$UDPPORT

Tests

This test was a straight comparison between the old and new scripts using the same settings and the same testing methodology as previously.  The resolution was 1280 x 720 pixels with a 6Mbps bitrate.

Update : Since the original article was published use Jan Schmitt spotted that I had misspelled “framerate” as “framereate” in the gst-rpicamsrc script.  He also suggested I should try using the baseline profile and a queue element to decouple the video capture from the UDP transmission.  With this in mind I have re-run the tests.

Results

Almost immediately I had the feeling that gst-rpicamsrc has slower.  Analysis of the video showed I was correct.  The latency using gst-rpicamsrc was 18% higher than using raspivid.

Update:

Running the original erroneous script with debugging on showed that the capture was running at 30fps instead of the intended 48 fps. Here are the new results averaged from 10 cycles.

Script gst-rpicamsrc @ 48 fps
raspivid @ 48 fps
Profile No queue With queue No queue With queue
baseline 184.2 175.4 153.9 156.9
high 186.2 185 154.1 159.7

gst-rpicamsrc @ 30 fps, high profile, no queue = 198.2 ms

Analysis

The first thing to note is that the raspivid latency (no queue, high profile) has risen from the 126ms found in the last tests to 154ms.  The only difference was that I cloned the Sandisk microSDHC card onto a Transcend 8GB.  I’ll set up some more tests to compare the cards.  As these tests were run from the same card and from the same boot, they are still valid for comparison.

It is immediately obvious that the gst-rpicamsrc latency is about 20% higher than the raspivid script, so the conclusion from the first publish of this article still stands.

What can be added is that using the baseline profile, does reduce the latency a little: 1 to 3ms in most cases.

Adding a queue element does provide a benefit for the gst-rpicamsrc script, especially with the baseline profile where a 9ms reduction in latency was observed.  For the raspivid script adding a queue element actually increased the latency by 3 to 4ms.  I suspect this is because the video stream is already decoupled from gstreamer by being piped in from an external process.

Conclusion

Using gst-rpicamsrc provides no benefit for reducing latency over raspivid.  That is not to say gst-rpicamsrc provides no other benefits.  For any use other than FPV, I would definitely use gst-rpicamsrc instead of having to pipe the video in through stdin.  It provides plenty of options for setting up the video stream as the command `gst-inspect-1.0 rpicamsrc’ above showed.

The problem here is that I am targeting this development for FPV use where low latency is the driving factor. At the moment my lowest latency for a adequate quality HD stream is 125ms and I really need to get this under 100ms to compete with current analog standard definition systems.  Whether it is possible to shave of another 25ms remains to be seen.

Update: Following the additional tests I would add that it is better to use the baseline profile over the high profile.

Advertisements

Current Raspberry Pi FPV Scripts

I have created a page that will hold the latest bash scripts and configuration files for the Raspberry Pi and Laptop ends of the FPV link.

This will save having to work back through the posts to find them.

You can find the page here.

Effect of Frame & Bit rates on Latency

Extract

Back in March, an update to the Raspberry Pi camera software introduced some new video modes with higher frame rates for resolutions below full 1080p HD.  For 720p HD, frame rates up to 49 fps are now available and for VGA (640×480) there are new modes for 60 and 90 fps.  There were reports that, at these higher frame rates, the latency was reduced.  This didn’t come as a surprise as it has been known for a while that the GoPro video out has lower latency at 48 fps than at 30 fps.  The reasons for this are not totally clear, but is thought to be due to the differences between frames being less at the higher frame rates allowing for more efficient compression.

In order to investigate this I ran some back-to-back tests at various frame rates.  I was expecting that with twice as many frames being squeezed into the same bit rates, the video quality would suffer, so the tests where repeated at three different bit rates.  The result of this testing was a 25% reduction in latency, with a new minimum of 121 milliseconds at 720p and 48 fps.  As expected the video quality at the old bit rate of 2.5Mbps suffered for fast moving backgrounds, but even when increased to 6.0Mbps, the latency was still only 126 Mbps; a 23% reduction.

With VGA resolution at 60fps and 2.5 Mbps the latency dropped to 87 ms and while this is useful, in terms of hardware size, convenience and even latency, it is still bettered by dedicated FPV hardware.  If you include the cost of the laptop, it looses out on price too.  Where the Pi has the advantage is at the 1280 x 720p HD resolution where there is currently no affordable competition.

Setup

The test environment was set up the same as previously, with the camera pointing at the laptop screen.  The camera was positioned so that at least ten iterations of the image were visible at once. I used a single LED torch as the measurement indicator.  The tests were run with no overclocking.

I used a UDP stream with some improved scripts to simplify running all the variations. The scripts can be found on the Current Scripts Page.

A GoPro 3 Black was used to record the screen at 120 fps.

Tests were run at frame rates of 25, 30, 36, 42, 45, 48 and 49 fps and at bit rates of 2.5, 4.5 and 6.0 Mbps.   Up to 5 LED on/led off cycles were recorded on the GoPro for later analysis.  With 10 iteration for each of the 5 on/offs, the calculated latency represents the average of 100 tests.

Results 1 – Latency

Across all the bit rates, the results show a definite reduction in latency with increasing frame rate right up to 48 frames per second. At 49 fps the latency increased slightly. The lowest latency achieved was 121ms at 48 fps for the 2.5 Mbps stream.  A reduction of 25% over the 25 fps result.  The 6.0 Mps stream still managed a reduced latency of 126 ms at 48 fps and the 4.5 Mbps stream achieved 125 ms.

The VGA test showed a much lower latency at 87ms, even though it was using the same bit rate as the smallest 720p HD stream.

The graph shows some odd behavior between the 4.5 and 6.0 Mbps curves.  Below about 40 fps the 4.5 Mbps stream has higher latency than the 6.0 Mbps stream.  Beyond 40 fps the curves switch over to what you would expect.

fps

In addition to the average latency, the graph below shows the minimum and maximums for each bit rate.  What is apparent is that there is a lot of overlap between the results and that the latency can vary +/- 20 fps, particularly at the lower bit rates.

fps2

Results 2 – Video Quality

The frame grabs below show a clear difference between the three bit rates at 48 fps. The 2.5 Mbps stream shows extreme pixelation and a general blurring of the image.

Quality25

Frame grab from 2.5 Mbps stream @ 48 fps

The  4.5 Mbps shows a reduction in the pixelation.  This is apparent in the sky and on the tiled roof.

Quality45

Frame grab from 4.5 Mbps Stream @ 48 fps

The 6.0 Mbps is the clear winner, with a minimum of pixelation and the sharpest image.

Quality60

Frame grab from 6.0 Mbps Stream @ 48 fps

Conclusion

The total latency is made up of capture, compression, transmission and display components.  The capture and  display components should be the same for the three bit rates as the resolution is the same.  The transmission component should increase in relation to the higher bit rates.  That just leaves the compression component.  The compressor has to work hard to squeeze the stream into a smaller bit rate whilst maintaining the best video quality possible.  For this reason decreasing the bit rate can increase the latency, although there is probably a point where the extreme pixelation starts reducing the latency again.

These opposing affects between compression and transmission are likely what has caused the odd behavior between the 4.5 Mbps and 6.0 Mbps streams.  At the lower frame rates, the compression delay for the 4.5 Mbps stream was more significant.  At the higher frame rates the transmission delay in the 6.0 Mbps stream became more significant.

While the VGA test used the same 2.5 Mbps bit rate as the HD test, with only a third of the pixels, the capture, compression and display components resulted in a much lower latency of 87 ms.

While the lowest latency was achieved for the 2.5 Mbps stream, the extreme pixelation of the image renders it pretty much unusable.  The 4.5 Mbps stream could be used but it only has a 1 ms advantage over the superior image quality of the 6.0 Mbps stream.  For this reason I plan to adopt the 48 fps, 6.0 Mbps, 126 ms stream as my new baseline when flying.

I will probably also switch to a 24 fps pipeline for youtube videos to get the best image quality from the 48 fps video, dropping every other frame.  I have seen this done where people have used the 48 fps recording on GoPro cameras.

Raspberry FPiV – Flight 4 – 1, 2, Tree

Extract

The aim of this flight was to test the airframe and the electronics after the unplanned lawn dart into the mud.  It was also the first test of the CRIUS CN-06 V2 U-blox GPS module.  I didn’t bother to stream the video to the laptop.  Instead I used the JuiceSSH app on my phone to access the Raspberry Pi and start a local 1080p HD and GPS recording.

Setup

The Crius GPS cable terminates in a standard 0.1″ pitch, four pin socket.  The pin outs on the Raspberry Pi are spread out over five pins, so I borrowed a single socket housing from a PCB development jumper and re-arranged the connections as shown in the photo below.

2014-05-23 13.11.08

The GPS was held on to the case with BluTak.

The only other change was to mount the camera on an extension so I could point it further down and to the right.  The aim being to get the propeller out of shot.

I didn’t plan for any big tests on this flight so didn’t bother setting up the laptop.  Instead I used the JuiceSSH app on my phone to start recording the GPS and video output on the Pi using a short script.  As I wasn’t streaming the video, I bumped the resolution up to full 1080p.

#!/bin/sh
cat $0

# Zero duration is continuous
DURATION=0
WIDTH=1920
HEIGHT=1080
FRAMERATE=25
BITRATE=10000000
NOW=`date +%Y%m%d%H%M%S`
FILENAME=$NOW-Pi.h264
gpxlogger -i 2 -f $NOW-Pi.gpx &

/opt/vc/bin/raspivid -t $DURATION -w $WIDTH -h $HEIGHT -fps $FRAMERATE -b $BITRATE -n -o $FILENAME

The Flight

Almost immediately I felt something wasn’t working properly.  Whilst the model was flying at normal speed, the climb rate was very low.  The wind wasn’t as strong as previously, but there still seemed to be some significant turbulence tossing the plane around.  After only one and a half circuits it started descending whilst over the far boundary and landed in a tree.

PlaneStuckInATree

The only visible damage was a broken tailplane and a broken prop.  I still had a WiFi connection from my phone to the Pi and was able to stop the recording and shut it down.  I had a 4m long strap in the car with a heavy buckle on one end, but it wasn’t long enough to reach the plane.  As this was lunchtime, I eventually had to leave it up the tree and return to work.

After work I stopped in at a local hardware store and bought 15m of chord and a pack of 10mm shackles.  The plane was still up the tree when I got back to the field, so I tied two of the shackles chord and started launching it skywards.  I soon found out I needed to tie some shackles to the loose end to stop the whole lot ending up in the tree.  After about 10 minutes, I managed to get the chord over the fuselage and pull it free of the branches.

After disconnecting the battery, a more detailed examination revealed the only other damage as a dent in the nose.  As the ESC had been connected for five hours, the battery had continued to drain and when checked was well past the minimum voltage.  One of the cells was reading 2.15V, so that battery will be going for recycling.

Post-Mortem

I was able to extract the video and gps files from the SD card.  It turns out the propeller was still partly visible in the video and because of this I could see the low voltage cutout had activated just as the plane crossed the far boundary. This is why it started descending and ended up in the tree.  Why the battery went flat so quickly was another matter, as was the lack of power and the inability to climb.

Once I got everything on the bench I found the motor felt a bit rough.  I can only assume that grit had got into the bearings after the mud bath.  This could account for the increased current draw with the reduced power output.

Results

I think pointing the camera off to the side was a bad idea, even for a non FPV flight.

The one positive result was the CRIUS GPS.  There was an excellent correlation between the video and the GPS track, as the two pictures below show.

Flight4-PowerLine

Flight4-Trees

Additional benefits for the CRIUS are:

  • Doesn’t require a separate power supply as it doesn’t draw too much power from the Raspberry Pi.
  • It’s a compact all-in-one unit.
  • Freely available from eBay.

Conclusion

From now I shall be using the CRIUS GPS.

As the aircraft needs some rebuilding, I’m going to rework the internals so that I can mount the Raspberry Pi internally, with the camera above the nose.  I also need to build a new power pod the will mount above the wing.

As an alternative platform for some actual First Person View flying, I’m also building a tricopter.

Raspberry FPiV – Flight 3 – Recording on the Ground

Extract

After much trawling through the forums, I found a way to record the video stream at the receiving end using gst-launch-1.0 in such a way that it can be converted to a playable format later on without re-encoding and the resulting loss of quality.  Eventually, replacing gst-launch-1.0 with a dedicated gstreamer application would allow a valid video file to be recorded straight from the stream without the current post processing. This flight also included a test of the external amplified antenna for the Ultimate GPS Breakout board. The results were disappointing, not attaining sufficient accuracy for the desired application. The flight was cut short due to a combination of high, turbulent wind and dumb thumbs, but was long enough to get meaningful results. You need to watch the video at 720p for a meaningful comparison. Please bear in mind that the video has been re-encoded at least once, possibly three times between the Pi and your browser. https://www.youtube.com/watch?v=eCazn-JbR_0

Hardware Setup

The amplified GPS antenna comes with 5 metres of cable and a heavy magnet.  I shortened the cable and removed the magnet, but the parts were still unwieldy when strapped to the top of the plane.  Hardware wise this was the only addition to the previous test. 2014-04-25 13.15.03

 Software Setup

I had already generated and swapped ssh keys between the Pi and the laptop to remove the need to enter a password when connecting. While I’ve been testing different GPS setups , I’ve started gpsd using a small shell script

#!/bin/bash
echo Starting gpsd
sudo gpsd /dev/ttyAMA0 -n -F /var/run/gpsd.sock

I want to use the current time and date for the video and gpx file names.  As the Pi does not have a real time clock, I set the time from GPS using a  script based on one I found at  http://blog.petrilopia.net

#!/bin/bash
sudo date -s '01/01/2014 00:01'
sleep 1
GPSDATE=`gpspipe -w | head -10 | grep TPV | sed -r 's/.*"time":"([^"]*)".*/\1/' | head -1`
echo $GPSDATE
sudo date -s "$GPSDATE"

Next I run cgps to check the GPS accuracy.  Once it stops improving I exit cgps and run the third script to start gps logging and record the video stream.  The video is recorded as the raw h264 stream with a Tx (Transmitter) suffix.

#!/bin/sh
cat $0

# Duration in milliseconds. Use 0(Zero) for continuous
DURATION=1800000
WIDTH=1280
HEIGHT=720
FRAMERATE=25
BITRATE=2500000
NOW=`date +%Y%m%d%H%M%S`
FILENAME=$NOW-Tx.h264
gpxlogger -i 2 -f $NOW.gpx &
IP=$(ip -o addr show wlan0 | sed -n 's/.*inet \([0-9.]*\)\/.. .*/\1/p')
PORT=5000

/opt/vc/bin/raspivid -t $DURATION -w $WIDTH -h $HEIGHT -fps $FRAMERATE -b $BITRATE -n -o - | tee $FILENAME | gst-launch-1.0 -v fdsrc ! h264parse ! rtph264pay config-interval=1 pt=96 ! gdppay ! tcpserversink host=$IP port=$PORT

Finally, back on the laptop, in a new terminal window, I run a script to capture and display the video stream.  The h264 file is multiplexed (muxed) into an mpeg transport stream (ts) container with a Rx (Receiver) suffix.

#!/bin/bash
# Read the Settings file
source ./settings.conf

# Set file name from current time
NOW=`date +%Y%m%d%H%M%S`
FILENAME=$NOW-Rx.ts

# Read the stream.
gst-launch-1.0 -v tcpclientsrc host=$IP port=$PORT ! \
 gdpdepay ! rtph264depay ! \
 h264parse config-interval=96 ! \
 tee name=t ! queue ! \
 video/x-h264, framerate=25/1 ! avdec_h264 ! videoconvert ! autovideosink sync=false t. ! \
 queue ! mpegtsmux ! filesink location=$FILENAME

# Try to copy the file from SD card to Hard Disk
if [ ! -d $TARGETDIR ]; then
 sudo mount /dev/sdb4 /mnt
fi
cp $FILE $TARGETDIR/$FILENAME

Here is a sample settings.conf

#!/bin/bash
export IP=192.168.42.1
export PORT=5000
export FRAMERATE=25
export TARGETDIR=/mnt/home/user

The Flight

When I arrived at the field the wind felt to be blowing at a constant 10 mph.  In the short time it took to get everything ready it had started gusting much harder.  Having driven to the field and got everything setup I was determined to fly so opened the throttle and gave it a good chuck. My first realisation was that the wind was stronger than anything I had flown in before.  In order to get the aircraft to track up the field and not be blown out the back, I had to point it 20 to 30 degrees past the desired direction of flight.  Also, as the aircraft got further up the field and closer to the trees, the turbulence made it harder to control.  Eventually, it got bucked around to the point I lost orientation, dumb thumbed the rudder flipping it upside down and I wasn’t able to recover it before it hit the ground. When I checked later, the met office were quoting 26 mph gusts.

The Aftermath

The previous months rain had softened the ground enough that the aircraft nose was stuck in three or four inches with no apparent damage.  The rubber bands had separated, releasing the wings.  Any electronics that weren’t screwed down were scattered around the crash site and given a liberal coating of mud. Everything was dismantled and cleaned in fresh water, then left to dry.   When I did reconnect everything, it all worked.  The only problem was that camera now has a green tint.  I suspect that that the mud has abraded the lens coating, either on impact or during cleaning.  As they are cheap I bought a new one.

Results

I was worried that the crash would have lost or corrupted the on-board video recording.  As it turned out, only the last few seconds of the flight were lost, as you can see in the video.  After collecting the scattered components, I found the X terminal on the laptop reporting that the SD card had become read only.  It was still receiving and recording a video stream, although this was mostly a totally brown frame which turned to a greeny orange when I removed most of the mud.

GPS

I’ll cover the GPS first as it’s going to be short. The results using the larger amplified antenna were better, but still not good enough.  There seems to be either a lag or an offset in the computation.  The two images below show the problem.  For the next flight I’m going to use the CRIUS CN-06 V2 U-blox GPS module. Flight3-CrashSite Flight3-CricketSquare

Video 

The video recorded on the Pi (Tx) was copied to a Windows PC using WinSCP.  Then I used MP4BoxGUI to mux it into a MP4 file.  I have not had any problems using the generated file. With the video recorded on the laptop (Rx) as a transport stream, the first task was to convert it into an mp4. The following script takes the file name as an argument and creates two new videos.  This need to be run on a machine using Gstreamer version 1.2 (Check using gst-launch-1.0 –version).

#!/bin/bash
echo .
echo Remux
echo .
gst-launch-1.0 -v filesrc location=$1 ! tsdemux ! h264parse ! video/x-h264,framerate=25/1 ! mp4mux ! filesink location=$1.remux.mp4
echo .
echo Re-encode
echo .
gst-launch-1.0 -v filesrc location=$1 ! tsdemux ! h264parse ! video/x-h264,framerate=25/1 ! avdec_h264 ! videoconvert ! x264enc bitrate=2500 ! mp4mux ! filesink location=$1.reenc.mp4 

The first gstreamer pipeline (Remux), simply extracts the h264 video from the transport stream container and them multiplexes it into an mp4 container.  The h264 stream is unchanged, so there is no loss of video quality.  To make this file viewable on Windows required a couple of extra steps.  With the file copied on to the Windows PC I used MP4BoxGUI to demux and extract the h264 stream (again) and then to Mux it back into an MP4 file.  This new file was playable in Windows media Player. The second gstreamer pipeline (Re-encode), re-encodes the video as a new h264 file and multiplexes it into an mp4 container.  While re-encoding has to reduce the picture quality, it is not obvious without close inspection.  I use the re-encoded video in Sony Movie Studio 11.0, which had trouble reading the first remuxed file.  I also had to manually set the frame rate in Sony Movie Studio 11 to 25 fps as by default it was using 29.97 fps making it impossible to sync the Tx and Rx videos together.

Conclusion

The video posted on Youtube shows the Tx and Rx videos side by side.  They are fully synced and without a gap between I don’t think you can spot a join or see any difference in video quality.  Although a bit of a faff, for now I have a working pipeline to record usable video on the ground. As for the GPS, the search goes on.

Raspberry FPiV – Flight 1 (Line of Sight)

Extract

Having established from my tests with gstreamer that a low latency video stream over WiFi could be achieved from the Raspberry Pi and that a usable range could be achieved,  I decided to mount the system on an aircraft for some line of sight testing.  In order to extend the range test, I added an Adafruit Ultimate GPS Breakout Board.

The results were mixed: the video stream remained consistent throughout the flight although with higher latency than expected and the GPS accuracy was poor.   The reasons for the problems have been identified and fixed, so the overall results are still promising.

Computing Setup

To save booting from a thumb drive every time, I resized the Windows partition on my laptop and installed Lubuntu to the end of the hard disk.  This was fine for a while, but then an update to gstreamer made it impossible to install the bad and ugly plugin packages together.  In the end I gave up on Lubuntu and installed Arch Linux on both the Laptop and the RPi.  The driving force for this was that version 1.2 of gstreamer was available on both platforms.  Having never used Arch Linux before it took me most of the Christmas holidays to get everything running properly.

To save a bit of weight I replaced the Raspberry Pi model B with a model A.  The SD card can be moved between the two boards without changes.  An  Adafruit Ultimate GPS Breakout board was added to extend the range testing.  This was connected to the Pi’s UART pins.  I didn’t solder on the battery holder for the real time clock.

The board was mounted in a bright raspberry pink case, so it would be easier to find should it become detached from the plane.  I trimmed the plastic around the SD card slot so the camera cable could be run out above the card.  The camera was mounted in a PiBow holder and bolted to the case.  As the PiBow holder clips together, I glued the joints to secure everything.

Finally, I created some scripts to get everything configured and talking.

Aircraft Setup

I retrieved my old “Sorcerer” slope soaring trainer from the loft.  This design dates from 1969, although mine was built during the eighties.  It’s not pretty, but it is tough.  The radio system was a Futaba Attack 4 channel system on 35MHz and so wouldn’t interfere with the 2.4GHz WiFi signal.  As it hadn’t been used for 25-30 years, I replaced the transmitter battery, but apart from that everything worked fine.

As this was a glider, I built a power pod from birch and lite plywood to sit in place of the hatch.  Having the motor up front put the centre of gravity in the right place without adding additional weight.  The flight battery was replaced with a 1300 mAh LiPo which powered the receiver and servos through the ESC’s Battery Eliminator Circuit (BEC). I used a propeller that had previously been used on a multirotor that was well balanced.

2014-01-10 13.28.19

The Pi was powered by a dedicated 5V 3A BEC connected to the LiPo battery’s balance connector.  Everything was held on with rubber bands.

2014-01-10 13.28.28

The Flight

The first launch turned into a powered glide.  I hadn’t allowed enough throttle for the extra weight and drag.   The second launch had it climbing and zig-zagging up the field.  The Sorcerer has a huge rudder on a fin that is little more than a post.  With the added prop wash over the rudder, turbulence from the everything strapped on top of the wing and the gusting wind, it was difficult to keep it straight and smooth.  Once some height had been achieved and the throttle reduced everything settled down. I flew for about 5 minutes doing big circuits of our local playing field, before bringing it in to land.

Flight1-ScreenSetup

Results

As I was flying without a spotter, I didn’t look at the laptop screen until the flight was finished.

After retrieving the glider, I found the stream was still running which was a good start.  I hadn’t checked the latency with the new system before the flight, so it was disappointing to find it was running noticeably higher than I had achieved in my earlier tests.  I still had the original Raspian SD card and Lubuntu Thumb drive and a quick check showed that that setup still ran with low latency.  Research suggests the higher latency is due to incompatibilities between Arch Linux and the particular Intel chipset in the laptop.  It could also be that the hard drive speed is slower than the thumb drive, especially as the linux partition is at the end of the available drive space.

The next check was the GPS track.   I used WinSCP to get the video and gpx files off the RPi.  I found a really useful website that animated the track in real-time: www.gpsanimator.com/StarTraX.   I did a video capture from the screen using Applian Replay Video Capture which I then synced with the on-board and head camera footage in Sony Movie Studio 11.  As well as producing the video, this also allowed me to get frame grabs to calculate the gps error.

The animation showed the track jumping all over the place.   If it is to be believed, most of the flight was spent on the wrong side of the trees and I was flying behind where I was standing.  When synchronized with the video it is easy to see the inaccuracy.

Here is an example.  This image shows the glider crossing left to right in front of me.  In the bottom right hand corner is a tree.

Flight1-GPS1

 

Now look at the GPS track. I’ve marked on where I was stood, the position of the tree and the observed track.  The recorded track shows aircraft moving right to left, well behind me and over a small wood. The error is about 60 metres.

Flight1-GPS3

 

An even clearer example is the landing.  The error is about 130 metres.  Seeing as the current maximum tested range is only 240 metres, this is not good.  After being stationary for a little while, the GPS eventually caught up.

 

 

 

Flight1-Landing

I’ve got a Crius CN-06 V2 U-Blox based GPS which has a much larger antenna as the picture below demonstrates.  I also have the high gain remote antenna for the Ultimate GPS breakout, which is the same size as the Crius.  Finally, I’m going to add the real time clock battery holder, which should improve the warm start times.  At least one of these should improve things. 

 

 

GPS Size

 

Conclusion

While there were issues with the latency and the GPS, as a first flight the main purpose was achieved.  The streaming from air to ground worked and remained stable throughout the flight.  There is certainly enough promise to keep the project moving forward.

 

Raspberry Pi Camera Wifi Ground Range Testing

Inspired by the results from the gstreamer latency testing, I wanted to check the usable WiFi range before getting airborne.

With my portable power setup, I took a trip to our local playing field one lunchtime and set the Raspberry Pi on the roof of my car in the car park pointing it towards the far end.

2013-11-03 11.58.21

Everything was switched on, the WiFi link was established to the laptop and the stream started.  I used the Strava app on my phone to record the GPS track. Finally I started walking up the field monitoring the stream to check for drop-out.  At the far end of the field, I still had a solid stream.  I could have gone further, but the Raspberry Pi would have been out of sight where anyone passing could have just walked off with it.

Feeding the GPS output into Google Earth gave a distance of 212 metres (232 yards).

GroundRangeTest

Based on this encouraging result, the next step is to load the Pi+Camera onto an aircraft.