Raspberry Pi 2でH.264ハードウェアエンコーダを試してみた

Raspberry Pi 1/2 にはH.264のハードウェアエンコーダが載っているとスペックシートには書いてあります。それをどうやって使うのか調べました。

参考にさせてもらったのは以下のページ
Connecting The Dots: Raspberry Piでgstreamerを使ったh264エンコード
raspbian - Hardware h.264 encoding and decoding on the GPU core - Raspberry Pi Stack Exchange
GStreamer-devel - Stopping a gst-launch-ed pipeline

H.264のハードウェアエンコーダはgstreamerのomxh264encに実装されているということです。

Raspbian jessie では必要なものは以下のコマンド一発で揃います。

$ sudo apt-get install gstreamer1.0-*

以下のコマンドで、USB Webcamの映像をH.264エンコードしてmp4の動画ファイルとして保存することができます。

gst-launch-1.0 -e \
v4l2src device=/dev/video0 ! "video/x-raw,width=640,height=480,framerate=30/1" ! \
omxh264enc ! "video/x-h264,profile=high" ! \
h264parse ! queue max-size-bytes=10000000 ! \
mp4mux ! \
filesink location=test1.mp4

これをcap1.sh に書いておいて実行し、コントロールCで止めます。

$ ./cap1.sh 
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
^Chandling interrupt.
Interrupt: Stopping pipeline ...
EOS on shutdown enabled -- Forcing EOS on the pipeline
Waiting for EOS...
Got EOS from element "pipeline0".
EOS received - stopping pipeline...
Execution ended after 0:01:36.699275713
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...

mp4にmuxする場合は、gst-launch-1.0に -eオプションをつけておく必要があります。そうでないとコントロールCで止めたときに中途半端に切れたmp4ファイルができて再生不能になります。

エンコードの最中にtopコマンドでCPUの負荷をみるとidleが90%以上でした。確かにハードウェアでエンコードしていると思われます。

できたtest1.mp4をffprobeで調べると以下の通り。

$ ffprobe test1.mp4 
ffprobe version 2.7.2 Copyright (c) 2007-2015 the FFmpeg developers
  built with gcc 4.9.2 (Raspbian 4.9.2-10)
  configuration: --enable-gpl --enable-libass --enable-libfdk-aac --enable-libfreetype --enable-libtheora --enable-libvorbis --enable-libx264 --enable-nonfree
  libavutil      54. 27.100 / 54. 27.100
  libavcodec     56. 41.100 / 56. 41.100
  libavformat    56. 36.100 / 56. 36.100
  libavdevice    56.  4.100 / 56.  4.100
  libavfilter     5. 16.101 /  5. 16.101
  libswscale      3.  1.101 /  3.  1.101
  libswresample   1.  2.100 /  1.  2.100
  libpostproc    53.  3.100 / 53.  3.100
[mov,mp4,m4a,3gp,3g2,mj2 @ 0x2d8bfb0] Invalid timestamps stream=0, pts=-421387831, dts=0, size=4307
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from 'test1.mp4':
  Metadata:
    major_brand     : mp42
    minor_version   : 0
    compatible_brands: mp42mp41isomiso2
    creation_time   : 2015-10-11 23:51:53
  Duration: 00:01:36.67, start: -140462.610333, bitrate: 189 kb/s
    Stream #0:0(eng): Video: h264 (High) (avc1 / 0x31637661), yuv420p, 640x480, 186 kb/s, 27.69 fps, 29.75 tbr, 3k tbn, 6k tbc (default)
    Metadata:
      creation_time   : 2015-10-11 23:51:53
      handler_name    : VideoHandler

タイプスタンプがおかしい箇所があるようですが、このファイルは普通に再生できました。

続きを書きました。
Raspberry Pi 2 でWebcamの映像音声を録画する - 組み込みの人。